From 46703499915e97568e5db12fd2ceac25919bfd75 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Fri, 17 Jan 2020 16:33:36 -0800 Subject: [PATCH 01/46] EventTrace for NetFx, changes made to SqlConnection --- .../netfx/src/Microsoft.Data.SqlClient.csproj | 1 + .../Data/SqlClient/SqlClientEventSource.cs | 91 +++++++++++++++ .../Microsoft/Data/SqlClient/SqlConnection.cs | 104 +++++++++--------- 3 files changed, 141 insertions(+), 55 deletions(-) create mode 100644 src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj index f6571605f5..1e5f951c19 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj @@ -117,6 +117,7 @@ + diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs new file mode 100644 index 0000000000..a0155a3365 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Diagnostics.Tracing; + +namespace SqlClient.Microsoft.Data.SqlClient +{ + /// + /// + /// + [EventSource(Name = "Microsoft.Data.SqlClient.Logger")] + public class SqlClientEventSource : EventSource + { + /// + /// + /// + class Tasks + { + + } + /// + /// + /// + class Keywords + { + + } + + /// + /// + /// + /// + [Event(1, Message = "Scope Name: {0}", Opcode = EventOpcode.Start, Level = EventLevel.Informational)] + public void ScopeEnter(string Message) { WriteEvent(1, Message); } + + /// + /// + /// + /// + [Event(2, Message = "", Level = EventLevel.Informational, Channel = EventChannel.Analytic)] + public void Trace(string Message) { WriteEvent(2, Message); } + + /// + /// + /// + /// + [Event(3, Message = "", Level = EventLevel.Informational, Channel = EventChannel.Analytic)] + public void CorrelationTrace(string Message) { WriteEvent(3, Message); } + + /// + /// + /// + /// + [Event(4, Message = "", Level = EventLevel.Informational, Channel = EventChannel.Analytic)] + public void NotificationsTrace(string Message) { WriteEvent(4, Message); } + + /// + /// + /// + /// + [Event(5)] + public void NotificationsScopeEnter(string Message) { WriteEvent(5, Message); } + + /// + /// + /// + /// + [Event(6)] + public void PoolerScopeEnter(string Message) { WriteEvent(6, Message); } + + /// + /// + /// + /// + [Event(7)] + public void PoolerTrace(string Message) { WriteEvent(7, Message); } + + /// + /// + /// + [Event(8, Message = "Scope Name: {0}")] + public void ScopeLeave() { WriteEvent(8); } + + /// + /// + /// + public static SqlClientEventSource Log = new SqlClientEventSource(); + } +} diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index f7b88667d6..62950abc39 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -34,6 +34,7 @@ namespace Microsoft.Data.SqlClient { + using global::SqlClient.Microsoft.Data.SqlClient; using Microsoft.Data.Common; /// @@ -1102,9 +1103,7 @@ public SqlTransaction BeginTransaction(string transactionName) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { - IntPtr hscp; - - Bid.ScopeEnter(out hscp, " %d#, isolationLevel=%d{ds.IsolationLevel}", ObjectID, (int)isolationLevel); + SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, isolationLevel={(int)isolationLevel}"); try { @@ -1120,7 +1119,7 @@ override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLeve } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeave(); } } @@ -1129,10 +1128,8 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam { WaitForPendingReconnection(); SqlStatistics statistics = null; - IntPtr hscp; string xactName = ADP.IsEmpty(transactionName) ? "None" : transactionName; - Bid.ScopeEnter(out hscp, " %d#, iso=%d{ds.IsolationLevel}, transactionName='%ls'\n", ObjectID, (int)iso, - xactName); + SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, iso={(int)iso}, transactionName='{xactName}'\n"); try { @@ -1160,7 +1157,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeave(); SqlStatistics.StopTimer(statistics); } } @@ -1170,7 +1167,7 @@ override public void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -1179,7 +1176,8 @@ override public void ChangeDatabase(string database) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -1189,7 +1187,8 @@ override public void ChangeDatabase(string database) InnerConnection.ChangeDatabase(database); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -1244,7 +1243,6 @@ static public void ClearPool(SqlConnection connection) object ICloneable.Clone() { SqlConnection clone = new SqlConnection(this); - Bid.Trace(" %d#, clone=%d#\n", ObjectID, clone.ObjectID); return clone; } @@ -1262,9 +1260,8 @@ void CloseInnerConnection() /// override public void Close() { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); try { SqlStatistics statistics = null; @@ -1277,7 +1274,8 @@ override public void Close() TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -1309,7 +1307,8 @@ override public void Close() } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -1344,7 +1343,7 @@ override public void Close() { SqlDebugContext sdc = _sdc; _sdc = null; - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeave(); if (sdc != null) { sdc.Dispose(); @@ -1397,9 +1396,8 @@ public void EnlistDistributedTransaction(System.EnterpriseServices.ITransaction /// override public void Open() { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource.Log.ScopeEnter($" ObjectID: {ObjectID}, ActivityID %ls\n"); + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); try { @@ -1433,7 +1431,7 @@ override public void Open() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeave(); } } @@ -1467,7 +1465,7 @@ private async Task ReconnectAsync(int timeout) { if (ctoken.IsCancellationRequested) { - Bid.Trace(" Orginal ClientConnectionID %ls - reconnection cancelled\n", _originalConnectionId.ToString()); + SqlClientEventSource.Log.Trace($" Orginal ClientConnectionID: {_originalConnectionId.ToString()} - reconnection cancelled.\n"); return; } try @@ -1488,15 +1486,15 @@ private async Task ReconnectAsync(int timeout) _impersonateIdentity = null; ForceNewConnection = false; } - Bid.Trace(" Reconnection suceeded. ClientConnectionID %ls -> %ls \n", _originalConnectionId.ToString(), ClientConnectionId.ToString()); + SqlClientEventSource.Log.Trace($" Reconnection suceeded. ClientConnectionID {_originalConnectionId.ToString()} -> {ClientConnectionId.ToString()} \n"); return; } catch (SqlException e) { - Bid.Trace(" Orginal ClientConnectionID %ls - reconnection attempt failed error %ls\n", _originalConnectionId.ToString(), e.Message); + SqlClientEventSource.Log.Trace($" Orginal ClientConnectionID {_originalConnectionId} - reconnection attempt failed error {e.Message}\n"); if (attempt == retryCount - 1) { - Bid.Trace(" Orginal ClientConnectionID %ls - give up reconnection\n", _originalConnectionId.ToString()); + SqlClientEventSource.Log.Trace($" Orginal ClientConnectionID {_originalConnectionId.ToString()} - give up reconnection\n"); throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) @@ -1562,7 +1560,7 @@ internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) if (cData._unrecoverableStatesCount == 0) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; - Bid.Trace(" Connection ClientConnectionID %ls is invalid, reconnecting\n", _originalConnectionId.ToString()); + SqlClientEventSource.Log.Trace($" Connection ClientConnectionID {_originalConnectionId.ToString()} is invalid, reconnecting\n"); _recoverySessionData = cData; if (beforeDisconnect != null) { @@ -1654,9 +1652,8 @@ void CancelOpenAndWait() /// public override Task OpenAsync(CancellationToken cancellationToken) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource.Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); try { @@ -1733,7 +1730,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeave(); } } @@ -1754,7 +1751,7 @@ public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource retryTask) { - Bid.Trace(" %d#\n", _parent.ObjectID); + SqlClientEventSource.Log.Trace($" {_parent.ObjectID}#\n"); _registration.Dispose(); try { @@ -1867,7 +1864,8 @@ private bool TryOpenInner(TaskCompletionSource retry) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -1921,7 +1919,8 @@ private bool TryOpenInner(TaskCompletionSource retry) } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -2099,7 +2098,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action %d#, Connection broken.\n", ObjectID); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection broken.\n"); Close(); } }; @@ -2108,7 +2107,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action %d#, Connection broken.\n", ObjectID); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection broken.\n"); Close(); } } @@ -2213,11 +2212,11 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent) internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) { - if (Bid.TraceOn) - { - Debug.Assert(null != imevent, "null SqlInfoMessageEventArgs"); - Bid.Trace(" %d#, Message='%ls'\n", ObjectID, ((null != imevent) ? imevent.Message : "")); - } + + Debug.Assert(null != imevent, "null SqlInfoMessageEventArgs"); + var imeventValue = (null != imevent) ? imevent.Message : ""; + SqlClientEventSource.Log.Trace($" {ObjectID}#, Message='{imeventValue}'\n"); + SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage]; if (null != handler) { @@ -2430,9 +2429,8 @@ private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, s /// public static void ChangePassword(string connectionString, string newPassword) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, ""); - Bid.CorrelationTrace(" ActivityID %ls\n"); + SqlClientEventSource.Log.ScopeEnter(""); + SqlClientEventSource.Log.CorrelationTrace(" ActivityID %ls\n"); try { if (ADP.IsEmpty(connectionString)) @@ -2471,16 +2469,15 @@ public static void ChangePassword(string connectionString, string newPassword) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeave(); } } /// public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, ""); - Bid.CorrelationTrace(" ActivityID %ls\n"); + SqlClientEventSource.Log.ScopeEnter(""); + SqlClientEventSource.Log.CorrelationTrace(" ActivityID %ls\n"); try { if (ADP.IsEmpty(connectionString)) @@ -2542,7 +2539,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeave(); } } @@ -2648,16 +2645,13 @@ private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) Debug.Assert(TypeSystemAssemblyVersion != null, "TypeSystemAssembly should be set !"); if (string.Compare(asmRef.Name, "Microsoft.SqlServer.Types", StringComparison.OrdinalIgnoreCase) == 0) { - if (Bid.TraceOn) + if (asmRef.Version != TypeSystemAssemblyVersion) { - if (asmRef.Version != TypeSystemAssemblyVersion) - { - Bid.Trace(" SQL CLR type version change: Server sent %ls, client will instantiate %ls", - asmRef.Version.ToString(), TypeSystemAssemblyVersion.ToString()); - } + SqlClientEventSource.Log.Trace($" SQL CLR type version change: Server sent {asmRef.Version.ToString()}, client will instantiate {TypeSystemAssemblyVersion.ToString()}"); } asmRef.Version = TypeSystemAssemblyVersion; } + try { return Assembly.Load(asmRef); From c7c1504704bd543b613bd070dff662050aae5eb1 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Mon, 27 Jan 2020 16:08:09 -0800 Subject: [PATCH 02/46] EventSource for NetFx --- .../src/BID/INC/CS/AssemblyTemplate_BID.cs | 44 -- .../netfx/src/BID/INC/CS/BidPrivateBase.cs | 145 ---- .../netfx/src/BID/INC/CS/InProcSxSBid.htm | 647 ------------------ .../netfx/src/Microsoft.Data.SqlClient.csproj | 3 - .../Data/Common/ActivityCorrelator.cs | 1 - .../src/Microsoft/Data/Common/AdapterUtil.cs | 6 +- .../Data/Common/DBConnectionString.cs | 12 +- .../Data/Common/DbConnectionOptions.cs | 204 +++--- .../Microsoft/Data/Common/System.Data_BID.cs | 308 --------- .../netfx/src/Microsoft/Data/DataException.cs | 35 +- .../Data/ProviderBase/DbConnectionFactory.cs | 47 +- .../Data/ProviderBase/DbConnectionInternal.cs | 49 +- .../Data/ProviderBase/DbConnectionPool.cs | 109 ++- .../ProviderBase/DbConnectionPoolGroup.cs | 7 +- .../Data/ProviderBase/SqlConnectionHelper.cs | 25 +- ...rectoryAuthenticationTimeoutRetryHelper.cs | 10 +- .../Microsoft/Data/SqlClient/LocalDBAPI.cs | 15 +- .../SqlClient/Server/SmiEventSink_Default.cs | 17 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 9 +- .../Data/SqlClient/SqlClientEventSource.cs | 220 +++--- .../Data/SqlClient/SqlClientLogger.cs | 7 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 165 ++--- .../Microsoft/Data/SqlClient/SqlCommandSet.cs | 11 +- .../Microsoft/Data/SqlClient/SqlConnection.cs | 63 +- .../Data/SqlClient/SqlConnectionFactory.cs | 2 +- .../SqlConnectionPoolGroupProviderInfo.cs | 4 +- .../Data/SqlClient/SqlDataAdapter.cs | 6 +- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 307 +++++---- .../Data/SqlClient/SqlDataReaderSmi.cs | 73 +- .../Data/SqlClient/SqlDelegatedTransaction.cs | 12 +- .../Microsoft/Data/SqlClient/SqlDependency.cs | 157 ++--- .../Data/SqlClient/SqlDependencyListener.cs | 190 +++-- .../Data/SqlClient/SqlDependencyUtils.cs | 94 ++- .../src/Microsoft/Data/SqlClient/SqlError.cs | 4 +- .../Data/SqlClient/SqlInternalConnection.cs | 78 +-- .../SqlClient/SqlInternalConnectionSmi.cs | 136 +--- .../SqlClient/SqlInternalConnectionTds.cs | 243 +++---- .../Microsoft/Data/SqlClient/SqlParameter.cs | 3 +- .../Data/SqlClient/SqlQueryMetadataCache.cs | 3 +- .../Data/SqlClient/SqlTransaction.cs | 67 +- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 247 ++++--- .../Data/SqlClient/TdsParserSessionPool.cs | 42 +- .../Data/SqlClient/TdsParserStateObject.cs | 322 +++++---- .../Data/SqlClient/TdsValueSetter.cs | 2 +- .../Data/SqlClient/sqlinternaltransaction.cs | 31 +- .../Microsoft/Data/SqlTypes/SqlFileStream.cs | 10 +- 46 files changed, 1450 insertions(+), 2742 deletions(-) delete mode 100644 src/Microsoft.Data.SqlClient/netfx/src/BID/INC/CS/AssemblyTemplate_BID.cs delete mode 100644 src/Microsoft.Data.SqlClient/netfx/src/BID/INC/CS/BidPrivateBase.cs delete mode 100644 src/Microsoft.Data.SqlClient/netfx/src/BID/INC/CS/InProcSxSBid.htm delete mode 100644 src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/System.Data_BID.cs diff --git a/src/Microsoft.Data.SqlClient/netfx/src/BID/INC/CS/AssemblyTemplate_BID.cs b/src/Microsoft.Data.SqlClient/netfx/src/BID/INC/CS/AssemblyTemplate_BID.cs deleted file mode 100644 index 8c61c8dc29..0000000000 --- a/src/Microsoft.Data.SqlClient/netfx/src/BID/INC/CS/AssemblyTemplate_BID.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Text; -using System.Security; -using System.Reflection; -using System.Security.Permissions; -using System.Runtime.InteropServices; -using System.Runtime.Versioning; - -[module: BidIdentity("MyAssemblyName.1")] -[module: BidMetaText(":FormatControl: InstanceID='' ")] - -internal static partial class Bid -{ - private const string dllName = "BidLdr.dll"; - - // - // Strongly Typed Overloads example. - // Use SignatureGenerator or edit manually in order to create actual set of overloads. - // - internal static void Trace(string fmtPrintfW, System.Int32 a1) { - if ((modFlags & ApiGroup.Trace) != 0 && modID != NoData) - NativeMethods.Trace (modID, UIntPtr.Zero, UIntPtr.Zero, fmtPrintfW,a1); - } - - internal static void TraceEx(uint flags, string fmtPrintfW, System.Int32 a1) { - if (modID != NoData) - NativeMethods.Trace (modID, UIntPtr.Zero, (UIntPtr)flags, fmtPrintfW,a1); - } - - // - // Interop calls to pluggable hooks [SuppressUnmanagedCodeSecurity] applied - // - private static partial class NativeMethods - { - [ResourceExposure(ResourceScope.None)] - [DllImport(dllName, CharSet=CharSet.Unicode, CallingConvention=CallingConvention.Cdecl, EntryPoint="DllBidTraceCW")] extern - internal static void Trace (IntPtr hID, UIntPtr src, UIntPtr info, string fmtPrintfW, System.Int32 a1); - } // Native -} // Bid - diff --git a/src/Microsoft.Data.SqlClient/netfx/src/BID/INC/CS/BidPrivateBase.cs b/src/Microsoft.Data.SqlClient/netfx/src/BID/INC/CS/BidPrivateBase.cs deleted file mode 100644 index 7562835bf8..0000000000 --- a/src/Microsoft.Data.SqlClient/netfx/src/BID/INC/CS/BidPrivateBase.cs +++ /dev/null @@ -1,145 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -[ComVisible(false)] -internal static partial class Bid -{ - //+////////////////////////////////////////////////////////////////////////////////////////// - // // - // INTERFACE // - // // - //+////////////////////////////////////////////////////////////////////////////////////////// - // - // ApiGroup control flags are accessible from attached diagnostic subsystem via corresponding - // delegate, so the output can be enabled/disabled on the fly. - // - internal enum ApiGroup : uint - { - Off = 0x00000000, - - Default = 0x00000001, // Bid.TraceEx (Always ON) - Trace = 0x00000002, // Bid.Trace, Bid.PutStr - Scope = 0x00000004, // Bid.Scope{Enter|Leave|Auto} - Perf = 0x00000008, // TBD.. - Resource = 0x00000010, // TBD.. - Memory = 0x00000020, // TBD.. - StatusOk = 0x00000040, // S_OK, STATUS_SUCCESS, etc. - Advanced = 0x00000080, // Bid.TraceEx - - Pooling = 0x00001000, - Dependency = 0x00002000, - StateDump = 0x00004000, - Correlation = 0x00040000, - - MaskBid = 0x00000FFF, - MaskUser = 0xFFFFF000, - MaskAll = 0xFFFFFFFF - } - - internal static bool TraceOn - { - get { return (modFlags & ApiGroup.Trace) != 0; } - } - - internal static bool AdvancedOn - { - get { return (modFlags & ApiGroup.Advanced) != 0; } - } - - internal static bool IsOn(ApiGroup flag) - { - return (modFlags & flag) != 0; - } - - private static IntPtr __noData = (IntPtr)(-1); - - internal static IntPtr NoData - { - get { return __noData; } - } - - internal static void PutStr(string str) - { - } - - internal static void Trace(string strConst) - { - } - - internal static void Trace(string fmtPrintfW, string a1) - { - } - - internal static void ScopeLeave(ref IntPtr hScp) - { - hScp = NoData; - } - - internal static void ScopeEnter(out IntPtr hScp, string strConst) - { - hScp = NoData; - } - - internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, int a1) - { - hScp = NoData; - } - - internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, int a1, int a2) - { - hScp = NoData; - } - - internal static void TraceBin(string constStrHeader, byte[] buff, UInt16 length) - { - } - - private static ApiGroup modFlags = ApiGroup.Off; - -} // Bid{PrivateBase} - -/// -/// This attribute is used by FxCopBid rule to mark methods that accept format string and list of arguments that match it -/// FxCopBid rule uses this attribute to check if the method needs to be included in checks and to read type mappings -/// between the argument type to printf Type spec. -/// -/// If you need to rename/remove the attribute or change its properties, make sure to update the FxCopBid rule! -/// -[System.Diagnostics.ConditionalAttribute("CODE_ANALYSIS")] -[System.AttributeUsage(AttributeTargets.Method)] -internal sealed class BidMethodAttribute : Attribute -{ - internal BidMethodAttribute() - { - } -} - -/// -/// This attribute is used by FxCopBid rule to tell FXCOP the 'real' type sent to the native trace call for this argument. For -/// example, if Bid.Trace accepts enumeration value, but marshals it as string to the native trace method, set this attribute -/// on the argument and set ArgumentType = typeof(string) -/// -/// It can be applied on a parameter, to let FxCopBid rule know the format spec type used for the argument, or it can be applied on a method, -/// to insert additional format spec arguments at specific location. -/// -/// If you need to rename/remove the attribute or change its properties, make sure to update the FxCopBid rule! -/// -[System.Diagnostics.ConditionalAttribute("CODE_ANALYSIS")] -[System.AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)] -internal sealed class BidArgumentTypeAttribute : Attribute -{ - // this overload can be used on the argument itself - internal BidArgumentTypeAttribute(Type bidArgumentType) - { - this.ArgumentType = bidArgumentType; - this.Index = -1; // if this c-tor is used on methods, default index value is 'last' - } - - public readonly Type ArgumentType; - // should be used only if attribute is applied on the method - public readonly int Index; -} diff --git a/src/Microsoft.Data.SqlClient/netfx/src/BID/INC/CS/InProcSxSBid.htm b/src/Microsoft.Data.SqlClient/netfx/src/BID/INC/CS/InProcSxSBid.htm deleted file mode 100644 index 727033f3ae..0000000000 --- a/src/Microsoft.Data.SqlClient/netfx/src/BID/INC/CS/InProcSxSBid.htm +++ /dev/null @@ -1,647 +0,0 @@ - - - - - - - - - - - - - - - - - - -
- -

Bid is ‘safe’ for InProc SxS, but I’ve added an initial trace line for each AppDomain to make it more human friendly.

- -

                -<ds.Bid|Info> -VersionSafeName=’<AppDomain.CurrentDomain.FriendlyName>_p#_InstanceID_ad#’

- -

via System.Runtime.Versioning.VersionHelper.MakeVersionSafeName(AppDomain.CurrentDomain.FriendlyName, -ResourceScope.Machine, ResourceScope.AppDomain);

- -

example: C78:102: <ds.Bid|Info> -VersionSafeName='XdoTracingTest.exe_p192_rOVlOOOEfcORz8ON24OC-ONOLyOGOIOVwOOOJlkOXk_ad1'

- -

C78:102: -<ds.DataSet.DataSet|API> 1#

- -

C78:103: <ds.Bid|Info> -VersionSafeName='friendly_MyComputer_p192_rOVlOOOEfcORz8ON24OC-ONOLyOGOIOVwOOOJlkOXk_ad2'

- -

C78:103: -<ds.DataSet.DataSet|API> 1#

- -

 

- -

Why it’s safe:

- -

                -For every managed AppDomain and native Dll that loads, a new unique (recyclable) module id is -acquired from the loader via DllBidEntryPoint.

- -

There is only a single loader (aka. -AdoNetDiag.dll running in native code) loaded per process.

- -

                -Yes, you could be malicious and change the registry key that identifies the -loader per DLL load - but that’s not supported scenario.

- -

 

- -

                -The Thread ID and Module ID are included with every trace.

- -

                -The Module ID is agnostic to the NetFx40 or NetFx35 instance since it is a -unique identifiers for the process; the ‘friendly name’ and ad# are not unique -to the process.

- -

                -Allows a single thread to be followed through the process and -different application domains uniquely identified.

- -

                -For managed code to be more human friendly, that initial trace point per -application domain helps identify the running instance/domain more clearly.

- -

 

- -

Removed the following files to share a common Bid\inc\cs\BidPrivateBase.cs

- -

                -Data\System\Data\Common\BidPrivateBase.cs

- -

                -DataOracleClient\System\Data\Common\BidPrivateBase.cs

- -

The common file was originally not shared in V2.0 because -when the work started

- -

a)      partial -class hadn’t been introduced yet

- -

b)      reliability -work with constrained execution regions hadn’t been introduced yet

- -

c)       the supposed common code was modified with each copy for -individual needs at the time.

- -

 

- -

In bid\inc\cs\bidprivatebase.cs

- -

                -Dead code removal relating to tracing.

- -

                -Removed the V1 support code

- -

                -Added other #defines to “remove unused” code by System.Data.dll -, System.Data.OracleClient.dll and System.Data.Entity.dll

- -

Added [ResourceExposure(ResourceScope.None)] to all Bid.NativeMethods -since they don’t expose any resources.

- -

 

- -

                -Did not add ResourceExposure to modID -since it doesn’t expose a resource, it just represents a unique identitifer.

- -

                -Similar to how XmlReader doesn’t expose the resource, -however its creation with a filename does.

- -

 

- -

I have already checked in the start of a tracing unit test (changeset #629692, #629897)

- -

                -It can enable BidStub, BidLabProto -or AdoNetDiag for tracing.  AdoNetDiag -is the one used by the unit test.

- -

                -Then launches a program to traces the 24 permutations of (FullTrust -tracing first or partial trust tracing first) and (initial domain tracing first -or secondary domain tracing first).

- -

                -Remaining work: programmatically analyze the output to verify the expected -traces.

- -

 

- -
- - - - diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj index 1e5f951c19..836f5ebe6d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj @@ -229,7 +229,6 @@ - @@ -304,8 +303,6 @@ - - diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/ActivityCorrelator.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/ActivityCorrelator.cs index 90f4981b4b..550cbf24e0 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/ActivityCorrelator.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/ActivityCorrelator.cs @@ -14,7 +14,6 @@ namespace Microsoft.Data.Common internal static class ActivityCorrelator { - internal const Bid.ApiGroup CorrelationTracePoints = Bid.ApiGroup.Correlation; internal class ActivityId { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index d067507056..cd354d72ee 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -96,15 +96,13 @@ static internal Task FalseTask } } - [BidMethod] // this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it static private void TraceException( - string trace, - [BidArgumentType(typeof(String))] Exception e) + string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); if (null != e) { - Bid.Trace(trace, e.ToString()); // will include callstack if permission is available + SqlClientEventSource._log.Trace(e.ToString()); // will include callstack if permission is available } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs index 2f502a12ef..8897905b83 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs @@ -12,6 +12,7 @@ namespace Microsoft.Data.Common using System.Diagnostics; using System.Linq; using System.Text; + using Microsoft.Data.SqlClient; [Serializable] // MDAC 83147 internal sealed class DBConnectionString @@ -175,7 +176,8 @@ internal string Restrictions builder.Append("=;"); } #if DEBUG - else { + else + { Debug.Assert(false, "empty restriction"); } #endif @@ -468,9 +470,7 @@ static private string[] NoDuplicateUnion(string[] a, string[] b) private static string[] ParseRestrictions(string restrictions, Hashtable synonyms) { #if DEBUG - if (Bid.AdvancedOn) { - Bid.Trace(" Restrictions='%ls'\n", restrictions); - } + SqlClientEventSource._log.Trace($" Restrictions='{restrictions}'\n"); #endif List restrictionValues = new List(); StringBuilder buffer = new StringBuilder(restrictions.Length); @@ -486,9 +486,7 @@ private static string[] ParseRestrictions(string restrictions, Hashtable synonym if (!ADP.IsEmpty(keyname)) { #if DEBUG - if (Bid.AdvancedOn) { - Bid.Trace(" KeyName='%ls'\n", keyname); - } + SqlClientEventSource._log.Trace($" KeyName='{keyname}'\n"); #endif string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144 if (ADP.IsEmpty(realkeyname)) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs index f446add866..6d83210530 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs @@ -12,6 +12,7 @@ namespace Microsoft.Data.Common using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; + using Microsoft.Data.SqlClient; internal class DbConnectionOptions { @@ -39,13 +40,13 @@ internal class DbConnectionOptions + "(?([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)" // allow any visible character for keyname except '=' which must quoted as '==' + "\\s*=(?!=)\\s*" // the equal sign divides the key and value parts + "(?" - + "(\"([^\"\u0000]|\"\")*\")" // double quoted string, " must be quoted as "" - + "|" - + "('([^'\u0000]|'')*')" // single quoted string, ' must be quoted as '' - + "|" - + "((?![\"'\\s])" // unquoted value must not start with " or ' or space, would also like = but too late to change - + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted - + "(?([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}])+)" // allow any visible character for keyname except '=' + "\\s*=\\s*" // the equal sign divides the key and value parts + "(?" - + "(\\{([^\\}\u0000]|\\}\\})*\\})" // quoted string, starts with { and ends with } - + "|" - + "((?![\\{\\s])" // unquoted value must not start with { or space, would also like = but too late to change - + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted + + "(\\{([^\\}\u0000]|\\}\\})*\\})" // quoted string, starts with { and ends with } + + "|" + + "((?![\\{\\s])" // unquoted value must not start with { or space, would also like = but too late to change + + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted - + ")" // VSTFDEVDIV 94761: although the spec does not allow {} - // embedded within a value, the retail code does. - // + "(? KeyName='%ls', KeyValue='%ls'\n", keyname, keyvalue); - } - else { - Bid.Trace(" KeyName='%ls'\n", keyname); - } + private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hashtable synonyms) + { + Debug.Assert(keyname == keyname.ToLower(CultureInfo.InvariantCulture), "missing ToLower"); + + string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); + if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) + { // don't trace passwords ever! + if (null != keyvalue) + { + SqlClientEventSource._log.Trace($" KeyName='{keyname}', KeyValue='{keyvalue}'\n"); + } + else + { + SqlClientEventSource._log.Trace($" KeyName='{keyname}'\n"); } } } @@ -918,7 +921,8 @@ static private bool IsKeyNameValid(string keyname) } #if DEBUG - private static Hashtable SplitConnectionString(string connectionString, Hashtable synonyms, bool firstKey) { + private static Hashtable SplitConnectionString(string connectionString, Hashtable synonyms, bool firstKey) + { Hashtable parsetable = new Hashtable(); Regex parser = (firstKey ? ConnectionStringRegexOdbc : ConnectionStringRegex); @@ -926,61 +930,75 @@ private static Hashtable SplitConnectionString(string connectionString, Hashtabl Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index"); Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index"); - if (null != connectionString) { + if (null != connectionString) + { Match match = parser.Match(connectionString); - if (!match.Success || (match.Length != connectionString.Length)) { + if (!match.Success || (match.Length != connectionString.Length)) + { throw ADP.ConnectionStringSyntax(match.Length); } int indexValue = 0; CaptureCollection keyvalues = match.Groups[ValueIndex].Captures; - foreach(Capture keypair in match.Groups[KeyIndex].Captures) { + foreach (Capture keypair in match.Groups[KeyIndex].Captures) + { string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLower(CultureInfo.InvariantCulture); string keyvalue = keyvalues[indexValue++].Value; - if (0 < keyvalue.Length) { - if (!firstKey) { - switch(keyvalue[0]) { - case '\"': - keyvalue = keyvalue.Substring(1, keyvalue.Length-2).Replace("\"\"", "\""); - break; - case '\'': - keyvalue = keyvalue.Substring(1, keyvalue.Length-2).Replace("\'\'", "\'"); - break; - default: - break; + if (0 < keyvalue.Length) + { + if (!firstKey) + { + switch (keyvalue[0]) + { + case '\"': + keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\"\"", "\""); + break; + case '\'': + keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\'\'", "\'"); + break; + default: + break; } } } - else { + else + { keyvalue = null; } DebugTraceKeyValuePair(keyname, keyvalue, synonyms); string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); - if (!IsKeyNameValid(realkeyname)) { + if (!IsKeyNameValid(realkeyname)) + { throw ADP.KeywordNotSupported(keyname); } - if (!firstKey || !parsetable.ContainsKey(realkeyname)) { - parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first) + if (!firstKey || !parsetable.ContainsKey(realkeyname)) + { + parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first) } } } return parsetable; } - private static void ParseComparison(Hashtable parsetable, string connectionString, Hashtable synonyms, bool firstKey, Exception e) { - try { + private static void ParseComparison(Hashtable parsetable, string connectionString, Hashtable synonyms, bool firstKey, Exception e) + { + try + { Hashtable parsedvalues = SplitConnectionString(connectionString, synonyms, firstKey); - foreach(DictionaryEntry entry in parsedvalues) { - string keyname = (string) entry.Key; - string value1 = (string) entry.Value; - string value2 = (string) parsetable[keyname]; + foreach (DictionaryEntry entry in parsedvalues) + { + string keyname = (string)entry.Key; + string value1 = (string)entry.Value; + string value2 = (string)parsetable[keyname]; Debug.Assert(parsetable.Contains(keyname), "ParseInternal code vs. regex mismatch keyname <" + keyname + ">"); - Debug.Assert(value1 == value2, "ParseInternal code vs. regex mismatch keyvalue <" + value1 + "> <" + value2 +">"); + Debug.Assert(value1 == value2, "ParseInternal code vs. regex mismatch keyvalue <" + value1 + "> <" + value2 + ">"); } } - catch(ArgumentException f) { - if (null != e) { + catch (ArgumentException f) + { + if (null != e) + { string msg1 = e.Message; string msg2 = f.Message; @@ -991,20 +1009,24 @@ private static void ParseComparison(Hashtable parsetable, string connectionStrin { // VSTFDEVDIV 479587: we also accept cases were Regex parser (debug only) reports "wrong format" and // retail parsing code reports format exception in different location or "keyword not supported" - if (msg2.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal)) { - if (msg1.StartsWith(KeywordNotSupportedMessagePrefix, StringComparison.Ordinal) || msg1.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal)) { + if (msg2.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal)) + { + if (msg1.StartsWith(KeywordNotSupportedMessagePrefix, StringComparison.Ordinal) || msg1.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal)) + { isEquivalent = true; } } } - Debug.Assert(isEquivalent, "ParseInternal code vs regex message mismatch: <"+msg1+"> <"+msg2+">"); + Debug.Assert(isEquivalent, "ParseInternal code vs regex message mismatch: <" + msg1 + "> <" + msg2 + ">"); } - else { + else + { Debug.Assert(false, "ParseInternal code vs regex throw mismatch " + f.Message); } e = null; } - if (null != e) { + if (null != e) + { Debug.Assert(false, "ParseInternal code threw exception vs regex mismatch"); } } @@ -1015,49 +1037,51 @@ private static NameValuePair ParseInternal(Hashtable parsetable, string connecti StringBuilder buffer = new StringBuilder(); NameValuePair localKeychain = null, keychain = null; #if DEBUG - try { -#endif - int nextStartPosition = 0; - int endPosition = connectionString.Length; - while (nextStartPosition < endPosition) + try { - int startPosition = nextStartPosition; - - string keyname, keyvalue; - nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue); - if (ADP.IsEmpty(keyname)) +#endif + int nextStartPosition = 0; + int endPosition = connectionString.Length; + while (nextStartPosition < endPosition) { - // if (nextStartPosition != endPosition) { throw; } - break; - } + int startPosition = nextStartPosition; + + string keyname, keyvalue; + nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue); + if (ADP.IsEmpty(keyname)) + { + // if (nextStartPosition != endPosition) { throw; } + break; + } #if DEBUG DebugTraceKeyValuePair(keyname, keyvalue, synonyms); Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname"); Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue"); #endif - string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); - if (!IsKeyNameValid(realkeyname)) - { - throw ADP.KeywordNotSupported(keyname); - } - if (!firstKey || !parsetable.Contains(realkeyname)) - { - parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first) - } + string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); + if (!IsKeyNameValid(realkeyname)) + { + throw ADP.KeywordNotSupported(keyname); + } + if (!firstKey || !parsetable.Contains(realkeyname)) + { + parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first) + } - if (null != localKeychain) - { - localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition); - } - else if (buildChain) - { // first time only - don't contain modified chain from UDL file - keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition); + if (null != localKeychain) + { + localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition); + } + else if (buildChain) + { // first time only - don't contain modified chain from UDL file + keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition); + } } - } #if DEBUG } - catch(ArgumentException e) { + catch (ArgumentException e) + { ParseComparison(parsetable, connectionString, synonyms, firstKey, e); throw; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/System.Data_BID.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/System.Data_BID.cs deleted file mode 100644 index e3a9e7f4ac..0000000000 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/System.Data_BID.cs +++ /dev/null @@ -1,308 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; - -internal static partial class Bid -{ - internal static void PoolerTrace(string fmtPrintfW, System.Int32 a1) - { - } - - internal static void PoolerTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2) - { - } - - internal static void PoolerTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3) - { - } - - internal static void PoolerTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4) - { - } - - internal static void PoolerTrace( - string fmtPrintfW, - System.Int32 a1, - [BidArgumentType(typeof(String))] System.Exception a2) - { - } - - internal static void PoolerScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1) - { - hScp = NoData; - } - - internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, string fmtPrintfW2) - { - hScp = NoData; - } - - internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1) - { - hScp = NoData; - } - - internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, string fmtPrintfW2, string fmtPrintfW3) - { - hScp = NoData; - } - - internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, string fmtPrintfW2) - { - hScp = NoData; - } - - internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2) - { - hScp = NoData; - } - - internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, string fmtPrintfW2, string fmtPrintfW3, string fmtPrintfW4) - { - hScp = NoData; - } - - internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, string fmtPrintfW2, System.Int32 a2) - { - hScp = NoData; - } - - internal static void NotificationsScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, string fmtPrintfW2, string fmtPrintfW3, System.Int32 a4) - { - hScp = NoData; - } - - internal static void NotificationsTrace(string fmtPrintfW) - { - } - - internal static void NotificationsTrace(string fmtPrintfW, string fmtPrintfW2) - { - } - - internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1) - { - } - - internal static void NotificationsTrace(string fmtPrintfW, System.Boolean a1) - { - } - - internal static void NotificationsTrace(string fmtPrintfW, string fmtPrintfW2, System.Int32 a1) - { - } - - internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1, string fmtPrintfW2) - { - } - - internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2) - { - } - - internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1, System.Boolean a2) - { - } - - internal static void NotificationsTrace(string fmtPrintfW, System.String a1, System.String a2) - { - } - - internal static void NotificationsTrace(string fmtPrintfW, string fmtPrintfW2, string fmtPrintfW3, System.Int32 a1) - { - } - - internal static void NotificationsTrace(string fmtPrintfW, System.Boolean a1, string fmtPrintfW2, string fmtPrintfW3, string fmtPrintfW4) - { - } - - internal static void NotificationsTrace(string fmtPrintfW, System.Int32 a1, string fmtPrintfW2, string fmtPrintfW3, string fmtPrintfW4) - { - } - - internal static void CorrelationTrace(string fmtPrintfW, System.Int32 a1) - { - } - - internal static void CorrelationTrace(string fmtPrintfW) - { - } - - internal static void CorrelationTrace(string fmtPrintfW, System.Int32 a1, System.Int32 a2) - { - } - - internal static void Trace(string fmtPrintfW, System.String a1, System.String a2) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.Boolean a3) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3, System.String a4, System.Int32 a5) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3, System.UInt32 a4, System.Int32 a5, System.UInt32 a6, System.UInt32 a7) - { - } - - internal static void ScopeEnter( - out IntPtr hScp, - string fmtPrintfW, - System.Int32 a1, - [BidArgumentType(typeof(String))] System.Guid a2) - { - hScp = NoData; - } - - internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3) - { - hScp = NoData; - } - - internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Boolean a2, System.Int32 a3) - { - hScp = NoData; - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2) - { - } - - internal static void Trace(string fmtPrintfW, System.IntPtr a1) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.IntPtr a2, System.IntPtr a3) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.IntPtr a2) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.Int32 a4) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.String a4, System.String a5, System.Int32 a6) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Boolean a2) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.Int32 a5, System.Int32 a6, System.Int32 a7) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.Int32 a3, System.Int32 a4, System.Boolean a5) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int64 a2) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.String a2, System.String a3, System.String a4, System.Int32 a5, System.Int64 a6) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int64 a2, System.Int32 a3, System.Int32 a4) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int64 a3, System.Int32 a4) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.Int32 a4, System.String a5, System.String a6, System.String a7, System.Int32 a8) - { - } - - internal static void Trace(string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3, System.String a4) - { - } - - - // - // ScopeEnter overloads - // - internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2) - { - hScp = NoData; - } - - internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Boolean a2) - { - hScp = NoData; - } - - internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.String a3) - { - hScp = NoData; - } - - internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.String a2, System.Boolean a3) - { - hScp = NoData; - } - - internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3) - { - hScp = NoData; - } - - internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3, System.String a4) - { - hScp = NoData; - } - - internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Int32 a3) - { - hScp = NoData; - } - - internal static void ScopeEnter(out IntPtr hScp, string fmtPrintfW, System.Int32 a1, System.Int32 a2, System.Boolean a3, System.Int32 a4) - { - hScp = NoData; - } -} // Bid - diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs index 2340a7c2e2..be2d6f2ef2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -7,6 +7,7 @@ using System.Data; using System.Diagnostics; using System.Globalization; +using Microsoft.Data.SqlClient; namespace Microsoft.Data { @@ -22,27 +23,22 @@ internal static class ExceptionBuilder // The resource Data.txt will ensure proper string text based on the appropriate // locale. - [BidMethod] // this method accepts BID format as an argument, this attribute allows FXCopBid rule to validate calls to it static private void TraceException( - string trace, - [BidArgumentType(typeof(String))] Exception e) + string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); if (null != e) { - Bid.Trace(trace, e.Message); - if (Bid.AdvancedOn) + SqlClientEventSource._log.Trace(e.Message); + try { - try - { - Bid.Trace(", StackTrace='%ls'", Environment.StackTrace); - } - catch (System.Security.SecurityException) - { - // if you don't have permission - you don't get the stack trace - } + SqlClientEventSource._log.Trace($", StackTrace='{Environment.StackTrace}'"); } - Bid.Trace("\n"); + catch (System.Security.SecurityException) + { + // if you don't have permission - you don't get the stack trace + } + SqlClientEventSource._log.Trace("\n"); } } @@ -1168,11 +1164,12 @@ static public Exception InvalidSchemaSerializationMode(Type enumType, string mod static public Exception InvalidRemotingFormat(SerializationFormat mode) { #if DEBUG - switch(mode) { - case SerializationFormat.Xml: - case SerializationFormat.Binary: - Debug.Assert(false, "valid SerializationFormat " + mode.ToString()); - break; + switch (mode) + { + case SerializationFormat.Xml: + case SerializationFormat.Binary: + Debug.Assert(false, "valid SerializationFormat " + mode.ToString()); + break; } #endif return _InvalidEnumArgumentException(mode); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index 53de68caf1..3357c7b7dd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -13,6 +13,7 @@ namespace Microsoft.Data.ProviderBase using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Common; + using Microsoft.Data.SqlClient; internal abstract class DbConnectionFactory { @@ -65,8 +66,7 @@ internal int ObjectID public void ClearAllPools() { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " "); + var scopeID = SqlClientEventSource._log.ScopeEnter(" "); try { Dictionary connectionPoolGroups = _connectionPoolGroups; @@ -81,7 +81,7 @@ public void ClearAllPools() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -89,8 +89,7 @@ public void ClearPool(DbConnection connection) { ADP.CheckArgumentNull(connection, "connection"); - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", GetObjectId(connection)); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {GetObjectId(connection)}#"); try { DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); @@ -101,7 +100,7 @@ public void ClearPool(DbConnection connection) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -110,8 +109,7 @@ public void ClearPool(DbConnectionPoolKey key) Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, "key.ConnectionString"); - IntPtr hscp; - Bid.ScopeEnter(out hscp, " connectionString"); + var scopeID = SqlClientEventSource._log.ScopeEnter(" connectionString"); try { DbConnectionPoolGroup poolGroup; @@ -123,7 +121,7 @@ public void ClearPool(DbConnectionPoolKey key) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -155,7 +153,7 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakeNonPooledObject(owningConnection, PerformanceCounters); } - Bid.Trace(" %d#, Non-pooled database connection created.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Non-pooled database connection created.\n"); return newConnection; } @@ -170,7 +168,7 @@ internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbCo PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakePooledConnection(pool); } - Bid.Trace(" %d#, Pooled database connection created.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Pooled database connection created.\n"); return newConnection; } @@ -366,7 +364,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour if (connectionPool.IsRunning) { // If GetConnection failed while the pool is running, the pool timeout occurred. - Bid.Trace(" %d#, GetConnection failed because a pool timeout occurred.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred.\n"); throw ADP.PooledOpenTimeout(); } else @@ -384,7 +382,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour if (connection == null) { // exhausted all retries or timed out - give up - Bid.Trace(" %d#, GetConnection failed because a pool timeout occurred and all retries were exhausted.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred and all retries were exhausted.\n"); throw ADP.PooledOpenTimeout(); } @@ -409,7 +407,7 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti // however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) { - Bid.Trace(" %d#, DisabledPoolGroup=%d#\n", ObjectID, connectionPoolGroup.ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, DisabledPoolGroup={connectionPoolGroup.ObjectID}#\n"); // reusing existing pool option in case user originally used SetConnectionPoolOptions DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions; @@ -540,10 +538,7 @@ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPo private void PruneConnectionPoolGroups(object state) { // when debugging this method, expect multiple threads at the same time - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#\n", ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#\n"); // First, walk the pool release list and attempt to clear each // pool, when the pool is finally empty, we dispose of it. If the @@ -563,10 +558,9 @@ private void PruneConnectionPoolGroups(object state) if (0 == pool.Count) { _poolsToRelease.Remove(pool); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, ReleasePool=%d#\n", ObjectID, pool.ObjectID); - } + + SqlClientEventSource._log.Trace($" { ObjectID}#, ReleasePool={pool.ObjectID}#\n"); + PerformanceCounters.NumberOfInactiveConnectionPools.Decrement(); } } @@ -591,10 +585,9 @@ private void PruneConnectionPoolGroups(object state) if (0 == poolsLeft) { _poolGroupsToRelease.Remove(poolGroup); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, ReleasePoolGroup=%d#\n", ObjectID, poolGroup.ObjectID); - } + + SqlClientEventSource._log.Trace($" {ObjectID}#, ReleasePoolGroup={poolGroup.ObjectID}#\n"); + PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Decrement(); } } @@ -660,7 +653,7 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { Debug.Assert(null != poolGroup, "null poolGroup?"); - Bid.Trace(" %d#, poolGroup=%d#\n", ObjectID, poolGroup.ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, poolGroup={poolGroup.ObjectID}#\n"); lock (_poolGroupsToRelease) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index a346bedc76..ed08ac67b1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -14,6 +14,7 @@ namespace Microsoft.Data.ProviderBase using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Common; + using Microsoft.Data.SqlClient; using SysTx = System.Transactions; internal abstract class DbConnectionInternal @@ -52,7 +53,7 @@ internal abstract class DbConnectionInternal private SysTx.Transaction _enlistedTransactionOriginal; #if DEBUG - private int _activateCount; // debug only counter to verify activate/deactivates are in sync. + private int _activateCount; // debug only counter to verify activate/deactivates are in sync. #endif //DEBUG protected DbConnectionInternal() : this(ConnectionState.Open, true, false) @@ -162,11 +163,9 @@ protected internal SysTx.Transaction EnlistedTransaction if (null != value) { - if (Bid.IsOn(DbConnectionPool.PoolerTracePoints)) - { - int x = value.GetHashCode(); - Bid.PoolerTrace(" %d#, Transaction %d#, Enlisting.\n", ObjectID, x); - } + int x = value.GetHashCode(); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {x}#, Enlisting.\n"); + TransactionOutcomeEnlist(value); } } @@ -392,7 +391,7 @@ internal void ActivateConnection(SysTx.Transaction transaction) // Internal method called from the connection pooler so we don't expose // the Activate method publicly. - Bid.PoolerTrace(" %d#, Activating\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Activating\n"); #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); Debug.Assert(1 == activateCount, "activated multiple times?"); @@ -464,7 +463,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac Debug.Assert(null != owningObject, "null owningObject"); Debug.Assert(null != connectionFactory, "null connectionFactory"); - Bid.PoolerTrace(" %d# Closing.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}# Closing.\n"); // if an exception occurs after the state change but before the try block // the connection will be stuck in OpenBusy state. The commented out try-catch @@ -570,7 +569,7 @@ internal void DeactivateConnection() // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. - Bid.PoolerTrace(" %d#, Deactivating\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Deactivating\n"); #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); Debug.Assert(0 == activateCount, "activated multiple times?"); @@ -605,7 +604,7 @@ virtual internal void DelegatedTransactionEnded() // you call this method to prevent race conditions with Clear and // ReclaimEmancipatedObjects. - Bid.Trace(" %d#, Delegated Transaction Completed.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Delegated Transaction Completed.\n"); if (1 == _pooledCount) { @@ -668,7 +667,7 @@ public virtual void Dispose() protected internal void DoNotPoolThisConnection() { _cannotBePooled = true; - Bid.PoolerTrace(" %d#, Marking pooled object as non-poolable so it will be disposed\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Marking pooled object as non-poolable so it will be disposed\n"); } /// Ensure that this connection cannot be put back into the pool. @@ -676,7 +675,7 @@ protected internal void DoNotPoolThisConnection() protected internal void DoomThisConnection() { _connectionIsDoomed = true; - Bid.PoolerTrace(" %d#, Dooming\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Dooming\n"); } // Reset connection doomed status so it can be re-connected and pooled. @@ -808,11 +807,8 @@ internal void PrePush(object expectedOwner) { throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time } - if (Bid.IsOn(DbConnectionPool.PoolerTracePoints)) - { - //DbConnection x = (expectedOwner as DbConnection); - Bid.PoolerTrace(" %d#, Preparing to push into pool, owning connection %d#, pooledCount=%d\n", ObjectID, 0, _pooledCount); - } + //DbConnection x = (expectedOwner as DbConnection); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Preparing to push into pool, owning connection {0}#, pooledCount={ _pooledCount}\n"); _pooledCount++; _owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2% } @@ -841,11 +837,10 @@ internal void PostPop(object newOwner) } _owningObject.Target = newOwner; _pooledCount--; - if (Bid.IsOn(DbConnectionPool.PoolerTracePoints)) - { - //DbConnection x = (newOwner as DbConnection); - Bid.PoolerTrace(" %d#, Preparing to pop from pool, owning connection %d#, pooledCount=%d\n", ObjectID, 0, _pooledCount); - } + + //DbConnection x = (newOwner as DbConnection); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Preparing to pop from pool, owning connection {0}#, pooledCount={_pooledCount}\n"); + //3 // The following tests are retail assertions of things we can't allow to happen. if (null != Pool) { @@ -901,7 +896,7 @@ internal void DetachCurrentTransactionIfEnded() // Detach transaction from connection. internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing) { - Bid.Trace(" %d#, Transaction Completed. (pooledCount=%d)\n", ObjectID, _pooledCount); + SqlClientEventSource._log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})\n"); // potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new // transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should @@ -943,7 +938,7 @@ void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) { SysTx.Transaction transaction = e.Transaction; - Bid.Trace(" %d#, Transaction Completed. (pooledCount=%d)\n", ObjectID, _pooledCount); + SqlClientEventSource._log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})\n"); CleanupTransactionOnCompletion(transaction); @@ -961,7 +956,7 @@ private void TransactionOutcomeEnlist(SysTx.Transaction transaction) internal void SetInStasis() { _isInStasis = true; - Bid.PoolerTrace(" %d#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.\n"); PerformanceCounters.NumberOfStasisConnections.Increment(); } @@ -969,11 +964,11 @@ private void TerminateStasis(bool returningToPool) { if (returningToPool) { - Bid.PoolerTrace(" %d#, Delegated Transaction has ended, connection is closed. Returning to general pool.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" { ObjectID}#, Delegated Transaction has ended, connection is closed. Returning to general pool.\n"); } else { - Bid.PoolerTrace(" %d#, Delegated Transaction has ended, connection is closed/leaked. Disposing.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Delegated Transaction has ended, connection is closed/leaked. Disposing.\n"); } PerformanceCounters.NumberOfStasisConnections.Decrement(); _isInStasis = false; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index 3d023597d3..33c86f7a45 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -30,8 +30,6 @@ private enum State ShuttingDown, } - internal const Bid.ApiGroup PoolerTracePoints = Bid.ApiGroup.Pooling; - // This class is a way to stash our cloned Tx key for later disposal when it's no longer needed. // We can't get at the key in the dictionary without enumerating entries, so we stash an extra // copy as part of the value. @@ -84,7 +82,7 @@ internal TransactedConnectionPool(DbConnectionPool pool) _pool = pool; _transactedCxns = new Dictionary(); - Bid.PoolerTrace(" %d#, Constructed for connection pool %d#\n", ObjectID, _pool.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Constructed for connection pool {_pool.ObjectID}#\n"); } internal int ObjectID @@ -143,7 +141,7 @@ internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction) if (null != transactedObject) { - Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Popped.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource._log.PoolerTrace($" { ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Popped.\n"); } return transactedObject; } @@ -170,7 +168,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Pushing.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing.\n"); connections.Add(transactedObject); } @@ -206,14 +204,14 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Pushing.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing.\n"); connections.Add(transactedObject); } } else { - Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Adding List to transacted pool.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Adding List to transacted pool.\n"); // add the connection/transacted object to the list newConnections.Add(transactedObject); @@ -241,7 +239,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt } } } - Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Added.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Added.\n"); } Pool.PerformanceCounters.NumberOfFreeConnections.Increment(); @@ -250,7 +248,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionInternal transactedObject) { - Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Transaction Completed\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed\n"); TransactedConnectionList connections; int entry = -1; @@ -285,7 +283,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern // safely remove the list from the transacted pool. if (0 >= connections.Count) { - Bid.PoolerTrace(" %d#, Transaction %d#, Removing List from transacted pool.\n", ObjectID, transaction.GetHashCode()); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Removing List from transacted pool.\n"); _transactedCxns.Remove(transaction); // we really need to dispose our connection list; it may have @@ -302,7 +300,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern else { //Debug.Assert ( false, "TransactionCompletedEvent fired before PutTransactedObject put the connection in the transacted pool." ); - Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Transacted pool not yet created prior to transaction completing. Connection may be leaked.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transacted pool not yet created prior to transaction completing. Connection may be leaked.\n"); } } @@ -530,7 +528,7 @@ internal DbConnectionPool( _poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback _state = State.Running; - Bid.PoolerTrace(" %d#, Constructed.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Constructed.\n"); //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls // StartBackgroundCallbacks after pool is actually in the collection @@ -679,7 +677,7 @@ private void CleanupCallback(Object state) // With this logic, objects are pruned from the pool if unused for // at least one period but not more than two periods. - Bid.PoolerTrace(" %d#\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#\n"); // Destroy free objects that put us above MinPoolSize from old stack. while (Count > MinPoolSize) @@ -754,7 +752,7 @@ private void CleanupCallback(Object state) Debug.Assert(obj != null, "null connection is not expected"); - Bid.PoolerTrace(" %d#, ChangeStacks=%d#\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, ChangeStacks={obj.ObjectID}#\n"); Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); Debug.Assert(obj.CanBePooled, "pooled object is not poolable"); @@ -770,7 +768,7 @@ private void CleanupCallback(Object state) internal void Clear() { - Bid.PoolerTrace(" %d#, Clearing.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Clearing.\n"); DbConnectionInternal obj; @@ -808,7 +806,7 @@ internal void Clear() // it's been doomed, will cause it to be disposed of as well) ReclaimEmancipatedObjects(); - Bid.PoolerTrace(" %d#, Cleared.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Cleared.\n"); } private Timer CreateCleanupTimer() @@ -898,7 +896,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio } } } - Bid.PoolerTrace(" %d#, Connection %d#, Added to pool.\n", ObjectID, newObj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {newObj.ObjectID}#, Added to pool.\n"); // Reset the error wait: _errorWait = ERROR_WAIT_DEFAULT; @@ -959,7 +957,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio private void DeactivateObject(DbConnectionInternal obj) { - Bid.PoolerTrace(" %d#, Connection %d#, Deactivating.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Deactivating.\n"); obj.DeactivateConnection(); // we presume this operation is safe outside of a lock... @@ -1100,11 +1098,11 @@ internal void DestroyObject(DbConnectionInternal obj) // again. if (obj.IsTxRootWaitingForTxEnd) { - Bid.PoolerTrace(" %d#, Connection %d#, Has Delegated Transaction, waiting to Dispose.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Has Delegated Transaction, waiting to Dispose.\n"); } else { - Bid.PoolerTrace(" %d#, Connection %d#, Removing from pool.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removing from pool.\n"); bool removed = false; lock (_objectList) @@ -1116,19 +1114,19 @@ internal void DestroyObject(DbConnectionInternal obj) if (removed) { - Bid.PoolerTrace(" %d#, Connection %d#, Removed from pool.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removed from pool.\n"); PerformanceCounters.NumberOfPooledConnections.Decrement(); } obj.Dispose(); - Bid.PoolerTrace(" %d#, Connection %d#, Disposed.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Disposed.\n"); PerformanceCounters.HardDisconnectsPerSecond.Increment(); } } private void ErrorCallback(Object state) { - Bid.PoolerTrace(" %d#, Resetting Error handling.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Resetting Error handling.\n"); _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); @@ -1212,7 +1210,8 @@ void WaitForPendingOpen() Microsoft.Data.SqlClient.TdsParser.ReliabilitySection tdsReliabilitySection = new Microsoft.Data.SqlClient.TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -1224,7 +1223,8 @@ void WaitForPendingOpen() timeout = !TryGetConnection(next.Owner, delay, allowCreate, onlyOneCheckConnection, next.UserOptions, out connection); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -1301,7 +1301,7 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource %d#, DbConnectionInternal State != Running.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, DbConnectionInternal State != Running.\n"); connection = null; return true; } @@ -1347,7 +1347,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj PerformanceCounters.SoftConnectsPerSecond.Increment(); - Bid.PoolerTrace(" %d#, Getting connection.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Getting connection.\n"); // If automatic transaction enlistment is required, then we try to // get the connection from the transacted connection pool first. @@ -1400,19 +1400,19 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj switch (waitResult) { case WAIT_TIMEOUT: - Bid.PoolerTrace(" %d#, Wait timed out.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Wait timed out.\n"); Interlocked.Decrement(ref _waitCount); connection = null; return false; case ERROR_HANDLE: // Throw the error that PoolCreateRequest stashed. - Bid.PoolerTrace(" %d#, Errors are set.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Errors are set.\n"); Interlocked.Decrement(ref _waitCount); throw TryCloneCachedException(); case CREATION_HANDLE: - Bid.PoolerTrace(" %d#, Creating new connection.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Creating new connection.\n"); try { @@ -1466,7 +1466,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj if ((obj != null) && (!obj.IsConnectionAlive())) { - Bid.PoolerTrace(" %d#, Connection %d#, found dead and removed.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed.\n"); DestroyObject(obj); obj = null; // Setting to null in case creating a new object fails @@ -1477,7 +1477,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj RuntimeHelpers.PrepareConstrainedRegions(); try { - Bid.PoolerTrace(" %d#, Creating new connection.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Creating new connection.\n"); obj = UserCreateRequest(owningObject, userOptions); } finally @@ -1488,7 +1488,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj else { // Timeout waiting for creation semaphore - return null - Bid.PoolerTrace(" %d#, Wait timed out.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Wait timed out.\n"); connection = null; return false; } @@ -1498,24 +1498,24 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case WAIT_FAILED: Debug.Assert(waitForMultipleObjectsExHR != 0, "WaitForMultipleObjectsEx failed but waitForMultipleObjectsExHR remained 0"); - Bid.PoolerTrace(" %d#, Wait failed.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Wait failed.\n"); Interlocked.Decrement(ref _waitCount); Marshal.ThrowExceptionForHR(waitForMultipleObjectsExHR); goto default; // if ThrowExceptionForHR didn't throw for some reason case (WAIT_ABANDONED + SEMAPHORE_HANDLE): - Bid.PoolerTrace(" %d#, Semaphore handle abandonded.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Semaphore handle abandonded.\n"); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(SEMAPHORE_HANDLE, _waitHandles.PoolSemaphore); case (WAIT_ABANDONED + ERROR_HANDLE): - Bid.PoolerTrace(" %d#, Error handle abandonded.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Error handle abandonded.\n"); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(ERROR_HANDLE, _waitHandles.ErrorEvent); case (WAIT_ABANDONED + CREATION_HANDLE): - Bid.PoolerTrace(" %d#, Creation handle abandoned.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Creation handle abandoned.\n"); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(CREATION_HANDLE, _waitHandles.CreationSemaphore); default: - Bid.PoolerTrace(" %d#, WaitForMultipleObjects=%d\n", ObjectID, waitResult); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, WaitForMultipleObjects={waitResult}\n"); Interlocked.Decrement(ref _waitCount); throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult); } @@ -1580,7 +1580,7 @@ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal o internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) { PerformanceCounters.SoftConnectsPerSecond.Increment(); - Bid.PoolerTrace(" %d#, replacing connection.\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, replacing connection.\n"); DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); @@ -1623,7 +1623,7 @@ private DbConnectionInternal GetFromGeneralPool() if (null != obj) { - Bid.PoolerTrace(" %d#, Connection %d#, Popped from general pool.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from general pool.\n"); PerformanceCounters.NumberOfFreeConnections.Decrement(); } return (obj); @@ -1640,7 +1640,7 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac if (null != obj) { - Bid.PoolerTrace(" %d#, Connection %d#, Popped from transacted pool.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from transacted pool.\n"); PerformanceCounters.NumberOfFreeConnections.Decrement(); if (obj.IsTransactionRoot) @@ -1651,14 +1651,14 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac } catch { - Bid.PoolerTrace(" %d#, Connection %d#, found dead and removed.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed.\n"); DestroyObject(obj); throw; } } else if (!obj.IsConnectionAlive()) { - Bid.PoolerTrace(" %d#, Connection %d#, found dead and removed.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed.\n"); DestroyObject(obj); obj = null; } @@ -1674,9 +1674,8 @@ private void PoolCreateRequest(object state) // called by pooler to ensure pool requests are currently being satisfied - // creation mutex has not been obtained - IntPtr hscp; - Bid.PoolerScopeEnter(out hscp, " %d#\n", ObjectID); + var scopeID = SqlClientEventSource._log.PoolerScopeEnter($" {ObjectID}#\n"); try { @@ -1762,7 +1761,7 @@ private void PoolCreateRequest(object state) else { // trace waitResult and ignore the failure - Bid.PoolerTrace(" %d#, PoolCreateRequest called WaitForSingleObject failed %d", ObjectID, waitResult); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called WaitForSingleObject failed {waitResult}"); } } catch (Exception e) @@ -1776,7 +1775,7 @@ private void PoolCreateRequest(object state) // Now that CreateObject can throw, we need to catch the exception and discard it. // There is no further action we can take beyond tracing. The error will be // thrown to the user the next time they request a connection. - Bid.PoolerTrace(" %d#, PoolCreateRequest called CreateConnection which threw an exception: %ls", ObjectID, e); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called CreateConnection which threw an exception: {e}"); } finally { @@ -1796,7 +1795,7 @@ private void PoolCreateRequest(object state) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1810,7 +1809,7 @@ internal void PutNewObject(DbConnectionInternal obj) // against checked bits. // Debug.Assert(obj.CanBePooled, "non-poolable object in pool"); - Bid.PoolerTrace(" %d#, Connection %d#, Pushing to general pool.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Pushing to general pool.\n"); _stackNew.Push(obj); _waitHandles.PoolSemaphore.Release(1); @@ -1860,7 +1859,7 @@ internal void PutObjectFromTransactedPool(DbConnectionInternal obj) // that is using the connection, and that all pre-push logic has been // done and all transactions are ended. - Bid.PoolerTrace(" %d#, Connection %d#, Transaction has ended.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Transaction has ended.\n"); if (_state == State.Running && obj.CanBePooled) { @@ -1886,7 +1885,7 @@ private bool ReclaimEmancipatedObjects() { bool emancipatedObjectFound = false; - Bid.PoolerTrace(" %d#\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#\n"); List reclaimedObjects = new List(); int count; @@ -1940,7 +1939,7 @@ private bool ReclaimEmancipatedObjects() { DbConnectionInternal obj = reclaimedObjects[i]; - Bid.PoolerTrace(" %d#, Connection %d#, Reclaiming.\n", ObjectID, obj.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Reclaiming.\n"); PerformanceCounters.NumberOfReclaimedConnections.Increment(); emancipatedObjectFound = true; @@ -1953,7 +1952,7 @@ private bool ReclaimEmancipatedObjects() internal void Startup() { - Bid.PoolerTrace(" %d#, CleanupWait=%d\n", ObjectID, _cleanupWait); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, CleanupWait={_cleanupWait}\n"); _cleanupTimer = CreateCleanupTimer(); if (NeedToReplenish) @@ -1964,7 +1963,7 @@ internal void Startup() internal void Shutdown() { - Bid.PoolerTrace(" %d#\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#\n"); _state = State.ShuttingDown; @@ -1987,7 +1986,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern Debug.Assert(null != transactedObject, "null transactedObject?"); // Note: connection may still be associated with transaction due to Explicit Unbinding requirement. - Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Transaction Completed\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed\n"); // called by the internal connection when it get's told that the // transaction is completed. We tell the transacted pool to remove diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs index 521b820d31..fbccb7b5f0 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -7,6 +7,7 @@ namespace Microsoft.Data.ProviderBase using System.Collections.Concurrent; using System.Diagnostics; using Microsoft.Data.Common; + using Microsoft.Data.SqlClient; // set_ConnectionString calls DbConnectionFactory.GetConnectionPoolGroup // when not found a new pool entry is created and potentially added @@ -271,7 +272,7 @@ private bool MarkPoolGroupAsActive() if (PoolGroupStateIdle == _state) { _state = PoolGroupStateActive; - Bid.Trace(" %d#, Active\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Active\n"); } return (PoolGroupStateActive == _state); } @@ -333,12 +334,12 @@ internal bool Prune() if (PoolGroupStateActive == _state) { _state = PoolGroupStateIdle; - Bid.Trace(" %d#, Idle\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Idle\n"); } else if (PoolGroupStateIdle == _state) { _state = PoolGroupStateDisabled; - Bid.Trace(" %d#, Disabled\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Disabled\n"); } } return (PoolGroupStateDisabled == _state); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs index 222a78ee17..2eebf9569c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs @@ -86,7 +86,7 @@ internal DbConnectionOptions ConnectionOptions private string ConnectionString_Get() { - Bid.Trace(" %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#\n"); bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions connectionOptions = UserConnectionOptions; return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); @@ -129,11 +129,9 @@ private void ConnectionString_Set(DbConnectionPoolKey key) { throw ADP.OpenConnectionPropertySet(ADP.ConnectionString, connectionInternal.State); } - if (Bid.TraceOn) - { - string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); - Bid.Trace(" %d#, '%ls'\n", ObjectID, cstr); - } + + string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); + SqlClientEventSource._log.Trace($" {ObjectID}#, '{cstr}'\n"); } internal DbConnectionInternal InnerConnection @@ -179,15 +177,15 @@ internal void Abort(Exception e) } // NOTE: we put the tracing last, because the ToString() calls (and - // the Bid.Trace, for that matter) have no reliability contract and + // the SqlClientEventSource.Log.Trace, for that matter) have no reliability contract and // will end the reliable try... if (e is OutOfMemoryException) { - Bid.Trace(" %d#, Aborting operation due to asynchronous exception: %ls\n", ObjectID, "OutOfMemory"); + SqlClientEventSource._log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {"OutOfMemory"}\n"); } else { - Bid.Trace(" %d#, Aborting operation due to asynchronous exception: %ls\n", ObjectID, e.ToString()); + SqlClientEventSource._log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {e.ToString()}\n"); } } @@ -200,8 +198,7 @@ internal void AddWeakReference(object value, int tag) override protected DbCommand CreateDbCommand() { DbCommand command = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#\n", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#\n"); try { DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; @@ -210,7 +207,7 @@ override protected DbCommand CreateDbCommand() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } return command; } @@ -247,7 +244,7 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)); permissionSet.Demand(); - Bid.Trace(" %d#, Connection enlisting in a transaction.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Connection enlisting in a transaction.\n"); SysTx.Transaction indigoTransaction = null; if (null != transaction) @@ -273,7 +270,7 @@ override public void EnlistTransaction(SysTx.Transaction transaction) { SqlConnection.ExecutePermission.Demand(); - Bid.Trace(" %d#, Connection enlisting in a transaction.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Connection enlisting in a transaction.\n"); // If we're currently enlisted in a transaction and we were called // on the EnlistTransaction method (Whidbey) we're not allowed to diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs index 1ecfc4d681..bfbb1aaddd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs @@ -77,18 +77,12 @@ public SqlFedAuthToken CachedToken { get { - if (_sqlAuthLogger.IsLoggingEnabled) - { - _sqlAuthLogger.LogInfo(_typeName, "GetCachedToken", $"Retrieved cached token {GetTokenHash(_token)}."); - } + _sqlAuthLogger.LogInfo(_typeName, "GetCachedToken", $"Retrieved cached token {GetTokenHash(_token)}."); return _token; } set { - if (_sqlAuthLogger.IsLoggingEnabled) - { - _sqlAuthLogger.LogInfo(_typeName, "SetCachedToken", $"CachedToken changed from {GetTokenHash(_token)} to {GetTokenHash(value)}."); - } + _sqlAuthLogger.LogInfo(_typeName, "SetCachedToken", $"CachedToken changed from {GetTokenHash(_token)} to {GetTokenHash(value)}."); _token = value; } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs index 68bfdfa52c..4d4ebf0cf7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs @@ -73,7 +73,7 @@ static IntPtr UserInstanceDLLHandle SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle); if (s_userInstanceDLLHandle != IntPtr.Zero) { - Bid.Trace(" LocalDB - handle obtained"); + SqlClientEventSource._log.Trace(" LocalDB - handle obtained"); } else { @@ -117,7 +117,7 @@ static LocalDBCreateInstanceDelegate LocalDBCreateInstance if (functionAddr == IntPtr.Zero) { int hResult = Marshal.GetLastWin32Error(); - Bid.Trace(" GetProcAddress for LocalDBCreateInstance error 0x{%X}", hResult); + SqlClientEventSource._log.Trace($" GetProcAddress for LocalDBCreateInstance error 0x{hResult}"); throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); } s_localDBCreateInstance = (LocalDBCreateInstanceDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBCreateInstanceDelegate)); @@ -159,7 +159,7 @@ static LocalDBFormatMessageDelegate LocalDBFormatMessage { // SNI checks for LocalDBFormatMessage during DLL loading, so it is practically impossibe to get this error. int hResult = Marshal.GetLastWin32Error(); - Bid.Trace(" GetProcAddress for LocalDBFormatMessage error 0x{%X}", hResult); + SqlClientEventSource._log.Trace($" GetProcAddress for LocalDBFormatMessage error 0x{hResult}"); throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); } s_localDBFormatMessage = (LocalDBFormatMessageDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBFormatMessageDelegate)); @@ -314,7 +314,7 @@ internal static void CreateLocalDBInstance(string instance) } } else - Bid.Trace(" No system.data.localdb section found in configuration"); + SqlClientEventSource._log.Trace(" No system.data.localdb section found in configuration"); s_configurableInstances = tempConfigurableInstances; } } @@ -340,14 +340,11 @@ internal static void CreateLocalDBInstance(string instance) // LocalDBCreateInstance is thread- and cross-process safe method, it is OK to call from two threads simultaneously int hr = LocalDBCreateInstance(instanceInfo.version, instance, flags: 0); - Bid.Trace(" Starting creation of instance %ls version %ls", instance, instanceInfo.version); + SqlClientEventSource._log.Trace($" Starting creation of instance {instance} version {instanceInfo.version}"); if (hr < 0) throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_CreateFailed"), instance: instance, localDbError: hr); - Bid.Trace(" Finished creation of instance %ls", instance); + SqlClientEventSource._log.Trace($" Finished creation of instance {instance}"); instanceInfo.created = true; // mark instance as created - } // CreateLocalDbInstance - } - } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs index 5fd1cc87cd..549b64498d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs @@ -266,21 +266,12 @@ internal override void DefaultDatabaseChanged(string databaseName) // Called for messages and errors (ERROR and INFO tokens) internal override void MessagePosted(int number, byte state, byte errorClass, string server, string message, string procedure, int lineNumber) { + var serverValue = (null != server) ? server : ""; + var messageBody = (null != message) ? message : ""; + var proc = (null != procedure) ? procedure : ""; if (null == _parent) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, number=%d state=%d errorClass=%d server='%ls' message='%ls' procedure='%ls' linenumber=%d.\n", - 0, - number, - state, - errorClass, - (null != server) ? server : "", - (null != message) ? message : "", - (null != procedure) ? procedure : "", - lineNumber - ); - } + SqlClientEventSource._log.Trace($" {0}#, number={number} state={state} errorClass={errorClass} server='{serverValue}' message='{messageBody}' procedure='{proc}' linenumber={lineNumber}.\n"); SqlError error = new SqlError(number, state, errorClass, server, message, procedure, lineNumber); if (error.Class < TdsEnums.MIN_ERROR_CLASS) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index ca46138662..be6978029e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs @@ -593,9 +593,8 @@ private string CreateInitialQuery() private Task CreateAndExecuteInitialQueryAsync(out BulkCopySimpleResultSet result) { string TDSCommand = CreateInitialQuery(); - - Bid.Trace(" Initial Query: '%ls' \n", TDSCommand); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.Trace($" Initial Query: '{TDSCommand}' \n"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); @@ -886,7 +885,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i // private Task SubmitUpdateBulkCommand(string TDSCommand) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); @@ -2517,7 +2516,7 @@ private void CheckAndRaiseNotification() // it's also the user's chance to cause an exception ... _stateObj.BcpLock = true; abortOperation = FireRowsCopiedEvent(_rowsCopied); - Bid.Trace(" \n"); + SqlClientEventSource._log.Trace(" \n"); // just in case some pathological person closes the target connection ... if (ConnectionState.Open != _connection.State) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index a0155a3365..046341b98c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -1,91 +1,157 @@ -using System; -using System.Collections.Generic; -using System.Linq; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + using System.Text; -using System.Threading.Tasks; using System.Diagnostics.Tracing; +using System.Threading; -namespace SqlClient.Microsoft.Data.SqlClient +namespace Microsoft.Data.SqlClient { - /// - /// - /// - [EventSource(Name = "Microsoft.Data.SqlClient.Logger")] - public class SqlClientEventSource : EventSource + [EventSource(Name = "Microsoft.Data.SqlClient.EventSource")] + internal class SqlClientEventSource : EventSource { - /// - /// - /// - class Tasks + internal static readonly SqlClientEventSource _log = new SqlClientEventSource(); + private static long s_nextScopeId = 0; + private static long s_nextPoolerScopeId = 0; + private static long s_nextNotificationScopeId = 0; + + private const int TraceEventId = 1; + private const int EnterScopeId = 2; + private const int ExitScopeId = 3; + private const int TraceBinId = 4; + private const int CorrelationTraceId = 5; + private const int NotificationsScopeEnterId = 6; + private const int NotificationsTraceId = 7; + private const int PoolerScopeEnterId = 8; + private const int PoolerTraceId = 9; + private const int PutStrId = 10; + + //Any Prropery added to this class should be a power of 2. + public class Keywords + { + internal const EventKeywords Default = (EventKeywords)0X0002; //Integer 2 + internal const EventKeywords Trace = (EventKeywords)0x0004; // Integer 4 + internal const EventKeywords Scope = (EventKeywords)0x0008; // Integer 8 + internal const EventKeywords Perf = (EventKeywords)0x0010; // Integer 16 + internal const EventKeywords Resource = (EventKeywords)0x0020; // Integer 32 + internal const EventKeywords Memory = (EventKeywords)0x0040; // Integer 64 + internal const EventKeywords Pooling = (EventKeywords)0x0080; // Integer 128 + internal const EventKeywords Dependency = (EventKeywords)0x0100; // Integer 256 + internal const EventKeywords Correlation = (EventKeywords)0x200; // Integer 512 + internal const EventKeywords NotificationScope = (EventKeywords)0x400; // Integer 1024 + internal const EventKeywords PoolerScope = (EventKeywords)0X800; // Integer 2048 + internal const EventKeywords StringPrintOut = (EventKeywords)0x1000; // Integer 4096 + } + + [Event(TraceEventId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] + internal void Trace(string message) + { + if (!_log.IsEnabled(EventLevel.Informational, Keywords.Trace)) + { + return; + } + WriteEvent(TraceEventId, message); + } + + [Event(EnterScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] + internal long ScopeEnter(string message) { + StringBuilder MsgstrBldr = new StringBuilder(message); + long scopeId = 0; + if (_log.IsEnabled()) + { + scopeId = Interlocked.Increment(ref s_nextScopeId); + WriteEvent(EnterScopeId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); + } + return scopeId; + } + [Event(ExitScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] + internal void ScopeLeave(long scopeId) + { + if (!_log.IsEnabled()) + { + return; + } + WriteEvent(ExitScopeId, scopeId); } - /// - /// - /// - class Keywords + + [Event(TraceBinId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] + internal void TraceBin(string message, byte[] whereabout, int length) { + if (_log.IsEnabled(EventLevel.Informational, Keywords.Trace)) + { + WriteEvent(TraceBinId, message, whereabout, length); + } } - /// - /// - /// - /// - [Event(1, Message = "Scope Name: {0}", Opcode = EventOpcode.Start, Level = EventLevel.Informational)] - public void ScopeEnter(string Message) { WriteEvent(1, Message); } - - /// - /// - /// - /// - [Event(2, Message = "", Level = EventLevel.Informational, Channel = EventChannel.Analytic)] - public void Trace(string Message) { WriteEvent(2, Message); } - - /// - /// - /// - /// - [Event(3, Message = "", Level = EventLevel.Informational, Channel = EventChannel.Analytic)] - public void CorrelationTrace(string Message) { WriteEvent(3, Message); } - - /// - /// - /// - /// - [Event(4, Message = "", Level = EventLevel.Informational, Channel = EventChannel.Analytic)] - public void NotificationsTrace(string Message) { WriteEvent(4, Message); } - - /// - /// - /// - /// - [Event(5)] - public void NotificationsScopeEnter(string Message) { WriteEvent(5, Message); } - - /// - /// - /// - /// - [Event(6)] - public void PoolerScopeEnter(string Message) { WriteEvent(6, Message); } - - /// - /// - /// - /// - [Event(7)] - public void PoolerTrace(string Message) { WriteEvent(7, Message); } - - /// - /// - /// - [Event(8, Message = "Scope Name: {0}")] - public void ScopeLeave() { WriteEvent(8); } - - /// - /// - /// - public static SqlClientEventSource Log = new SqlClientEventSource(); + [Event(CorrelationTraceId, Level = EventLevel.Informational, Keywords = Keywords.Correlation, Opcode = EventOpcode.Start)] + internal void CorrelationTrace(string message) + { + if (!_log.IsEnabled()) + { + return; + } + WriteEvent(CorrelationTraceId, message); + } + + [Event(NotificationsScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.NotificationScope)] + internal long NotificationsScopeEnter(string message) + { + StringBuilder MsgstrBldr = new StringBuilder(message); + long scopeId = 0; + if (_log.IsEnabled()) + { + scopeId = Interlocked.Increment(ref s_nextNotificationScopeId); + WriteEvent(NotificationsScopeEnterId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); + } + return scopeId; + } + + [Event(PoolerScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.PoolerScope)] + internal long PoolerScopeEnter(string message) + { + long scopeId = 0; + StringBuilder MsgstrBldr = new StringBuilder(message); + + if (_log.IsEnabled()) + { + scopeId = Interlocked.Increment(ref s_nextPoolerScopeId); + WriteEvent(PoolerScopeEnterId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); + } + return scopeId; + } + + [Event(NotificationsTraceId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] + internal void NotificationsTrace(string message) + { + if (!_log.IsEnabled(EventLevel.Informational, Keywords.Trace)) + { + return; + } + WriteEvent(PoolerScopeEnterId, message); + } + + [Event(PoolerTraceId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] + internal void PoolerTrace(string message) + { + if (!_log.IsEnabled(EventLevel.Informational, Keywords.Trace)) + { + return; + } + WriteEvent(PoolerTraceId, message); + } + + [Event(PutStrId, Level = EventLevel.Informational, Keywords = Keywords.StringPrintOut)] + internal void PutStr(string message) + { + if (_log.IsEnabled(EventLevel.Informational, Keywords.StringPrintOut)) + { + WriteEvent(PutStrId, message); + + } + } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs index 830ad84ee1..aaa535aea6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs @@ -17,13 +17,13 @@ internal enum LogLevel /// public void LogInfo(string type, string method, string message) { - Bid.Trace($"{message}\n"); + SqlClientEventSource._log.Trace($"{message}\n"); } /// public void LogError(string type, string method, string message) { - Bid.Trace($"{message}\n"); + SqlClientEventSource._log.Trace($"{message}\n"); } /// @@ -33,8 +33,5 @@ public bool LogAssert(bool value, string type, string method, string message) LogError(type, method, message); return value; } - - /// - public bool IsLoggingEnabled => Bid.TraceOn; } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index 5caa018baa..5d037b1f1a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -10,6 +10,7 @@ using System.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; +using System.Diagnostics.Tracing; using System.IO; using System.Linq; using System.Runtime.CompilerServices; @@ -345,10 +346,7 @@ internal CommandEventSink(SqlCommand command) : base() internal override void StatementCompleted(int rowsAffected) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, rowsAffected=%d.\n", _command.ObjectID, rowsAffected); - } + SqlClientEventSource._log.Trace($" {_command.ObjectID}#, rowsAffected={rowsAffected}.\n"); _command.InternalRecordsAffected = rowsAffected; // UNDONE: need to fire events back to user code, but this may be called @@ -360,40 +358,32 @@ internal override void StatementCompleted(int rowsAffected) internal override void BatchCompleted() { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#.\n", _command.ObjectID); - } + SqlClientEventSource._log.Trace($" {_command.ObjectID}#.\n"); } internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 parameterValues) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# metaData.Length=%d.\n", _command.ObjectID, (null != metaData) ? metaData.Length : -1); - if (null != metaData) + var metaDataLength = (null != metaData) ? metaData.Length : -1; + SqlClientEventSource._log.Trace($" {_command.ObjectID}# metaData.Length={metaDataLength}.\n"); + + if (null != metaData) + { + for (int i = 0; i < metaData.Length; i++) { - for (int i = 0; i < metaData.Length; i++) - { - Bid.Trace(" %d#, metaData[%d] is %ls%ls\n", - _command.ObjectID, i, metaData[i].GetType().ToString(), metaData[i].TraceString()); - } + SqlClientEventSource._log.Trace($" {_command.ObjectID}#, metaData[{i}] is {metaData[i].GetType().ToString()}{metaData[i].TraceString()}\n"); } } + Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.YukonVersion); _command.OnParametersAvailableSmi(metaData, parameterValues); } internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter parameterValues, int ordinal) { - if (Bid.AdvancedOn) + if (null != metaData) { - if (null != metaData) - { - Bid.Trace(" %d#, metaData[%d] is %ls%ls\n", - _command.ObjectID, ordinal, metaData.GetType().ToString(), metaData.TraceString()); - } + SqlClientEventSource._log.Trace($" {_command.ObjectID}#, metaData[{ordinal}] is {metaData.GetType().ToString()}{ metaData.TraceString()}\n"); } Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion); _command.OnParameterAvailableSmi(metaData, parameterValues, ordinal); @@ -579,7 +569,8 @@ private SqlCommand(SqlCommand from) : this() _activeConnection = value; // UNDONE: Designers need this setter. Should we block other scenarios? - Bid.Trace(" %d#, %d#\n", ObjectID, ((null != value) ? value.ObjectID : -1)); + var _activeConnectionObjectID = (null != value) ? value.ObjectID : -1; + SqlClientEventSource._log.Trace($" {ObjectID}#, {_activeConnectionObjectID}#\n"); } } @@ -657,7 +648,7 @@ public SqlNotificationRequest Notification } set { - Bid.Trace(" %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#\n"); _sqlDep = null; _notification = value; } @@ -708,7 +699,7 @@ internal SqlStatistics Statistics } // TODO: Add objid here - Bid.Trace(" %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#\n"); _transaction = value; } } @@ -743,12 +734,11 @@ override public string CommandText } set { - if (Bid.TraceOn) - { - Bid.Trace(" %d#, '", ObjectID); - Bid.PutStr(value); // Use PutStr to write out entire string - Bid.Trace("'\n"); - } + + SqlClientEventSource._log.Trace($" {ObjectID}# '"); + SqlClientEventSource._log.PutStr(value); // Use PutStr to write out entire string + SqlClientEventSource._log.Trace("'\n"); + if (0 != ADP.SrcCompare(_commandText, value)) { PropertyChanging(); @@ -785,7 +775,7 @@ override public int CommandTimeout } set { - Bid.Trace(" %d#, %d\n", ObjectID, value); + SqlClientEventSource._log.Trace($" {ObjectID}#, {value}\n"); if (value < 0) { throw ADP.InvalidCommandTimeout(value); @@ -829,7 +819,7 @@ override public CommandType CommandType } set { - Bid.Trace(" %d#, %d{ds.CommandType}\n", ObjectID, (int)value); + SqlClientEventSource._log.Trace($" {ObjectID}#, {(int)value}{_commandType}\n"); if (_commandType != value) { switch (value) @@ -972,7 +962,7 @@ internal void OnStatementCompleted(int recordCount) { try { - Bid.Trace(" %d#, recordCount=%d\n", ObjectID, recordCount); + SqlClientEventSource._log.Trace($" {ObjectID}#, recordCount={recordCount}\n"); handler(this, new StatementCompletedEventArgs(recordCount)); } catch (Exception e) @@ -1010,9 +1000,8 @@ override public void Prepare() } SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); statistics = SqlStatistics.StartTimer(Statistics); // only prepare if batch with parameters @@ -1113,7 +1102,7 @@ override public void Prepare() } SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } private void InternalPrepare() @@ -1177,7 +1166,7 @@ internal void Unprepare() } _cachedMetaData = null; - Bid.Trace(" %d#, Command unprepared.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Command unprepared.\n"); } // Cancel is supposed to be multi-thread safe. @@ -1187,10 +1176,8 @@ internal void Unprepare() /// override public void Cancel() { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($"< sc.SqlCommand.Cancel | API > {ObjectID}#"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); SqlStatistics statistics = null; try @@ -1309,7 +1296,7 @@ override public void Cancel() finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1352,9 +1339,8 @@ override public object ExecuteScalar() _pendingCancel = false; SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); bool success = false; int? sqlExceptionNumber = null; @@ -1376,7 +1362,7 @@ override public object ExecuteScalar() finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1421,9 +1407,8 @@ override public int ExecuteNonQuery() _pendingCancel = false; SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); bool success = false; int? sqlExceptionNumber = null; try @@ -1443,7 +1428,7 @@ override public int ExecuteNonQuery() finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1459,8 +1444,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) _pendingCancel = false; SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1470,7 +1454,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1486,7 +1470,7 @@ public IAsyncResult BeginExecuteNonQuery() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); return BeginExecuteNonQueryInternal(0, callback, stateObject, 0, inRetry: false); } @@ -1712,7 +1696,7 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) } finally { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); } } @@ -1730,7 +1714,7 @@ private void ThrowIfReconnectionHasBeenCanceled() private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -1990,7 +1974,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st else { // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); - Bid.Trace(" %d#, Command executed as RPC.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Command executed as RPC.\n"); SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, methodName, completion, timeout, out task, out usedCache, asyncWrite, inRetry); if (null != reader) { @@ -2042,9 +2026,8 @@ public XmlReader ExecuteXmlReader() _pendingCancel = false; SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); bool success = false; int? sqlExceptionNumber = null; try @@ -2067,7 +2050,7 @@ public XmlReader ExecuteXmlReader() finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -2084,7 +2067,7 @@ public IAsyncResult BeginExecuteXmlReader() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); return BeginExecuteXmlReaderInternal(CommandBehavior.SequentialAccess, callback, stateObject, 0, inRetry: false); } @@ -2237,13 +2220,13 @@ public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) } finally { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); } } private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2362,7 +2345,7 @@ public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObjec /// override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); return ExecuteReader(behavior, ADP.ExecuteReader); } @@ -2370,9 +2353,8 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) new public SqlDataReader ExecuteReader() { SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -2381,23 +2363,22 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } /// new public SqlDataReader ExecuteReader(CommandBehavior behavior) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#, behavior=%d{ds.CommandBehavior}", ObjectID, (int)behavior); - Bid.CorrelationTrace(" ObjectID%d#, behavior=%d{ds.CommandBehavior}, ActivityID %ls\n", ObjectID, (int)behavior); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#, behavior={(int)behavior}"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {SqlClientEventSource._log.Guid}\n"); try { return ExecuteReader(behavior, ADP.ExecuteReader); } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -2412,7 +2393,7 @@ public IAsyncResult BeginExecuteReader(CommandBehavior behavior) [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior) { - Bid.CorrelationTrace(" ObjectID%d#, behavior=%d{ds.CommandBehavior}, ActivityID %ls\n", ObjectID, (int)behavior); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {SqlClientEventSource._log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); return BeginExecuteReaderInternal(behavior, callback, stateObject, 0, inRetry: false); } @@ -2494,13 +2475,13 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) } finally { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); } } private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2902,7 +2883,7 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -2988,7 +2969,7 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b new public Task ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { - Bid.CorrelationTrace(" ObjectID%d#, behavior=%d{ds.CommandBehavior}, ActivityID %ls\n", ObjectID, (int)behavior); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {SqlClientEventSource._log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3123,7 +3104,7 @@ public Task ExecuteXmlReaderAsync() public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3730,7 +3711,7 @@ private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, b // no parameters are sent over // no data reader is returned // use this overload for "batch SQL" tds token type - Bid.Trace(" %d#, Command executed as SQLBATCH.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Command executed as SQLBATCH.\n"); Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(this.CommandText, timeout, this.Notification, _stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -3792,10 +3773,7 @@ private void RunExecuteNonQuerySmi(bool sendToPipe) SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, innerConnection=%d#, transactionId=0x%I64x, cmdBehavior=%d.\n", ObjectID, innerConnection.ObjectID, transactionId, (int)CommandBehavior.Default); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{(int)CommandBehavior.Default}, cmdBehavior=%d.\n"); if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { @@ -5274,7 +5252,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi Debug.Assert(!IsUserPrepared, "CommandType.Text with no params should not be prepared!"); if (returnStream) { - Bid.Trace(" %d#, Command executed as SQLBATCH.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Command executed as SQLBATCH.\n"); } string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior); //If the query requires enclave computations, pass the enclavepackage in the SQLBatch TDS stream @@ -5338,7 +5316,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi rpc.options = TdsEnums.RPC_NOMETADATA; if (returnStream) { - Bid.Trace(" %d#, Command executed as RPC.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Command executed as RPC.\n"); } // TODO: Medusa: Unprepare only happens for SQL 7.0 which may be broken anyway (it's not re-prepared). Consider removing the reset here if we're really dropping 7.0 support. @@ -5361,7 +5339,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi optionSettings = GetSetOptionsString(cmdBehavior); if (returnStream) { - Bid.Trace(" %d#, Command executed as RPC.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Command executed as RPC.\n"); } // turn set options ON if (null != optionSettings) @@ -5456,10 +5434,7 @@ private SqlDataReader RunExecuteReaderSmi(CommandBehavior cmdBehavior, RunBehavi SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, innerConnection=%d#, transactionId=0x%I64x, commandBehavior=%d.\n", ObjectID, innerConnection.ObjectID, transactionId, (int)cmdBehavior); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, commandBehavior={(int)cmdBehavior}.\n"); if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { @@ -5679,7 +5654,7 @@ private void NotifyDependency() public SqlCommand Clone() { SqlCommand clone = new SqlCommand(this); - Bid.Trace(" %d#, clone=%d#\n", ObjectID, clone.ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, clone={clone.ObjectID}#\n"); return clone; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index d47f33ed67..375194228c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -129,7 +129,7 @@ internal int ObjectID internal void Append(SqlCommand command) { ADP.CheckArgumentNull(command, "command"); - Bid.Trace(" %d#, command=%d, parameterCount=%d\n", ObjectID, command.ObjectID, command.Parameters.Count); + SqlClientEventSource._log.Trace($" {ObjectID}#, command={command.ObjectID}, parameterCount={command.Parameters.Count}\n"); string cmdText = command.CommandText; if (ADP.IsEmpty(cmdText)) @@ -264,7 +264,7 @@ internal static void BuildStoredProcedureName(StringBuilder builder, string part internal void Clear() { - Bid.Trace(" %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#\n"); DbCommand batchCommand = BatchCommand; if (null != batchCommand) { @@ -280,7 +280,7 @@ internal void Clear() internal void Dispose() { - Bid.Trace(" %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#\n"); SqlCommand command = _batchCommand; _commandList = null; _batchCommand = null; @@ -295,8 +295,7 @@ internal int ExecuteNonQuery() { SqlConnection.ExecutePermission.Demand(); - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); try { if (Connection.IsContextConnection) @@ -316,7 +315,7 @@ internal int ExecuteNonQuery() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index 62950abc39..d02d82ce26 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -8,7 +8,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; -using System.Configuration; using System.Data; using System.Data.Common; using System.Diagnostics; @@ -34,7 +33,7 @@ namespace Microsoft.Data.SqlClient { - using global::SqlClient.Microsoft.Data.SqlClient; + using System.Diagnostics.Tracing; using Microsoft.Data.Common; /// @@ -1103,7 +1102,7 @@ public SqlTransaction BeginTransaction(string transactionName) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { - SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, isolationLevel={(int)isolationLevel}"); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#, isolationLevel={(int)isolationLevel}"); try { @@ -1119,7 +1118,7 @@ override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLeve } finally { - SqlClientEventSource.Log.ScopeLeave(); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1129,7 +1128,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam WaitForPendingReconnection(); SqlStatistics statistics = null; string xactName = ADP.IsEmpty(transactionName) ? "None" : transactionName; - SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, iso={(int)iso}, transactionName='{xactName}'\n"); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#, iso={(int)iso}, transactionName='{xactName}'\n"); try { @@ -1157,7 +1156,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam } finally { - SqlClientEventSource.Log.ScopeLeave(); + SqlClientEventSource._log.ScopeLeave(scopeID); SqlStatistics.StopTimer(statistics); } } @@ -1167,7 +1166,7 @@ override public void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -1260,8 +1259,8 @@ void CloseInnerConnection() /// override public void Close() { - SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); try { SqlStatistics statistics = null; @@ -1343,7 +1342,7 @@ override public void Close() { SqlDebugContext sdc = _sdc; _sdc = null; - SqlClientEventSource.Log.ScopeLeave(); + SqlClientEventSource._log.ScopeLeave(scopeID); if (sdc != null) { sdc.Dispose(); @@ -1396,8 +1395,8 @@ public void EnlistDistributedTransaction(System.EnterpriseServices.ITransaction /// override public void Open() { - SqlClientEventSource.Log.ScopeEnter($" ObjectID: {ObjectID}, ActivityID %ls\n"); - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); + var scopeID = SqlClientEventSource._log.ScopeEnter($" ObjectID: {ObjectID}, ActivityID {SqlClientEventSource._log.Guid}\n"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); try { @@ -1431,7 +1430,7 @@ override public void Open() } finally { - SqlClientEventSource.Log.ScopeLeave(); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1465,7 +1464,7 @@ private async Task ReconnectAsync(int timeout) { if (ctoken.IsCancellationRequested) { - SqlClientEventSource.Log.Trace($" Orginal ClientConnectionID: {_originalConnectionId.ToString()} - reconnection cancelled.\n"); + SqlClientEventSource._log.Trace($" Orginal ClientConnectionID: {_originalConnectionId.ToString()} - reconnection cancelled.\n"); return; } try @@ -1486,15 +1485,15 @@ private async Task ReconnectAsync(int timeout) _impersonateIdentity = null; ForceNewConnection = false; } - SqlClientEventSource.Log.Trace($" Reconnection suceeded. ClientConnectionID {_originalConnectionId.ToString()} -> {ClientConnectionId.ToString()} \n"); + SqlClientEventSource._log.Trace($" Reconnection suceeded. ClientConnectionID {_originalConnectionId.ToString()} -> {ClientConnectionId.ToString()} \n"); return; } catch (SqlException e) { - SqlClientEventSource.Log.Trace($" Orginal ClientConnectionID {_originalConnectionId} - reconnection attempt failed error {e.Message}\n"); + SqlClientEventSource._log.Trace($" Orginal ClientConnectionID {_originalConnectionId} - reconnection attempt failed error {e.Message}\n"); if (attempt == retryCount - 1) { - SqlClientEventSource.Log.Trace($" Orginal ClientConnectionID {_originalConnectionId.ToString()} - give up reconnection\n"); + SqlClientEventSource._log.Trace($" Orginal ClientConnectionID {_originalConnectionId.ToString()} - give up reconnection\n"); throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) @@ -1560,7 +1559,7 @@ internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) if (cData._unrecoverableStatesCount == 0) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; - SqlClientEventSource.Log.Trace($" Connection ClientConnectionID {_originalConnectionId.ToString()} is invalid, reconnecting\n"); + SqlClientEventSource._log.Trace($" Connection ClientConnectionID {_originalConnectionId.ToString()} is invalid, reconnecting\n"); _recoverySessionData = cData; if (beforeDisconnect != null) { @@ -1652,8 +1651,8 @@ void CancelOpenAndWait() /// public override Task OpenAsync(CancellationToken cancellationToken) { - SqlClientEventSource.Log.Trace($" {ObjectID}#"); - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); + var scopeID = SqlClientEventSource._log.PoolerScopeEnter($" {ObjectID}#"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); try { @@ -1730,7 +1729,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.ScopeLeave(); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1751,7 +1750,7 @@ public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource retryTask) { - SqlClientEventSource.Log.Trace($" {_parent.ObjectID}#\n"); + SqlClientEventSource._log.Trace($" {_parent.ObjectID}#\n"); _registration.Dispose(); try { @@ -2098,7 +2097,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {ObjectID}#, Connection broken.\n"); + SqlClientEventSource._log.Trace($" {ObjectID}#, Connection broken.\n"); Close(); } }; @@ -2107,7 +2106,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {ObjectID}#, Connection broken.\n"); + SqlClientEventSource._log.Trace($" {ObjectID}#, Connection broken.\n"); Close(); } } @@ -2215,7 +2214,7 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) Debug.Assert(null != imevent, "null SqlInfoMessageEventArgs"); var imeventValue = (null != imevent) ? imevent.Message : ""; - SqlClientEventSource.Log.Trace($" {ObjectID}#, Message='{imeventValue}'\n"); + SqlClientEventSource._log.Trace($" {ObjectID}#, Message='{imeventValue}'\n"); SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage]; if (null != handler) @@ -2429,8 +2428,8 @@ private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, s /// public static void ChangePassword(string connectionString, string newPassword) { - SqlClientEventSource.Log.ScopeEnter(""); - SqlClientEventSource.Log.CorrelationTrace(" ActivityID %ls\n"); + var scopeID = SqlClientEventSource._log.ScopeEnter(""); + SqlClientEventSource._log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); try { if (ADP.IsEmpty(connectionString)) @@ -2469,15 +2468,15 @@ public static void ChangePassword(string connectionString, string newPassword) } finally { - SqlClientEventSource.Log.ScopeLeave(); + SqlClientEventSource._log.ScopeLeave(scopeID); } } /// public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { - SqlClientEventSource.Log.ScopeEnter(""); - SqlClientEventSource.Log.CorrelationTrace(" ActivityID %ls\n"); + var scopeID = SqlClientEventSource._log.ScopeEnter(""); + SqlClientEventSource._log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); try { if (ADP.IsEmpty(connectionString)) @@ -2539,7 +2538,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent } finally { - SqlClientEventSource.Log.ScopeLeave(); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -2647,7 +2646,7 @@ private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) { if (asmRef.Version != TypeSystemAssemblyVersion) { - SqlClientEventSource.Log.Trace($" SQL CLR type version change: Server sent {asmRef.Version.ToString()}, client will instantiate {TypeSystemAssemblyVersion.ToString()}"); + SqlClientEventSource._log.Trace($" SQL CLR type version change: Server sent {asmRef.Version.ToString()}, client will instantiate {TypeSystemAssemblyVersion.ToString()}"); } asmRef.Version = TypeSystemAssemblyVersion; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs index e77f025789..fb23107e49 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs @@ -192,7 +192,7 @@ override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions { connectionTimeout *= 10; } - Bid.Trace($"Set connection pool CreateTimeout={connectionTimeout} when AD Interactive is in use.\n"); + SqlClientEventSource._log.Trace($"Set connection pool CreateTimeout={connectionTimeout} when AD Interactive is in use.\n"); } poolingOptions = new DbConnectionPoolGroupOptions( diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs index 2e302fab60..55ee60a23e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs @@ -55,7 +55,7 @@ internal void AliasCheck(string server) } else if (_alias != server) { - Bid.Trace(" alias change detected. Clearing PoolGroup\n"); + SqlClientEventSource._log.Trace($" alias change detected. Clearing PoolGroup\n"); base.PoolGroup.Clear(); _alias = server; } @@ -99,7 +99,7 @@ internal void FailoverCheck(SqlInternalConnection connection, bool actualUseFail if (UseFailoverPartner != actualUseFailoverPartner) { // TODO: will connections in progress somehow be active for two different datasources? - Bid.Trace(" Failover detected. failover partner='%ls'. Clearing PoolGroup\n", actualFailoverPartner); + SqlClientEventSource._log.Trace($" Failover detected. failover partner='{actualFailoverPartner}'. Clearing PoolGroup\n"); base.PoolGroup.Clear(); _useFailoverPartner = actualUseFailoverPartner; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index b8f33b6d94..a89af98830 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -142,7 +142,7 @@ override public int UpdateBatchSize throw ADP.ArgumentOutOfRange("UpdateBatchSize"); } _updateBatchSize = value; - Bid.Trace(" %d#, %d\n", ObjectID, value); + SqlClientEventSource._log.Trace($" {ObjectID}#, {value}\n"); } } @@ -249,7 +249,7 @@ override protected RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, override protected int ExecuteBatch() { Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); return _commandSet.ExecuteNonQuery(); } @@ -272,7 +272,7 @@ override protected bool GetBatchedRecordsAffected(int commandIdentifier, out int /// override protected void InitializeBatching() { - Bid.Trace(" %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#\n"); _commandSet = new SqlCommandSet(); SqlCommand command = SelectCommand; if (null == command) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs index c74195b8bc..92a3bdc43f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -272,7 +272,8 @@ internal _SqlMetaDataSet MetaData TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -285,7 +286,8 @@ internal _SqlMetaDataSet MetaData } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -859,15 +861,17 @@ private bool TryCleanPartialRead() } #if DEBUG - if (_stateObj._pendingData) { - byte token; - if (!_stateObj.TryPeekByte(out token)) { - return false; - } - - Debug.Assert(TdsParser.IsValidTdsToken(token), string.Format("Invalid token after performing CleanPartialRead: {0,-2:X2}", token)); - + if (_stateObj._pendingData) + { + byte token; + if (!_stateObj.TryPeekByte(out token)) + { + return false; } + + Debug.Assert(TdsParser.IsValidTdsToken(token), string.Format("Invalid token after performing CleanPartialRead: {0,-2:X2}", token)); + + } #endif _sharedState._dataReady = false; @@ -885,7 +889,8 @@ private void CleanPartialReadReliable() TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -895,7 +900,8 @@ private void CleanPartialReadReliable() Debug.Assert(!_sharedState._dataReady, "_dataReady should be cleared"); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -933,8 +939,7 @@ private void CleanPartialReadReliable() override public void Close() { SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1020,7 +1025,7 @@ override public void Close() finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1039,7 +1044,8 @@ private bool TryCloseInternal(bool closeReader) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -1074,9 +1080,11 @@ private bool TryCloseInternal(bool closeReader) } } #if DEBUG - else { + else + { byte token; - if (!_stateObj.TryPeekByte(out token)) { + if (!_stateObj.TryPeekByte(out token)) + { return false; } @@ -1097,7 +1105,8 @@ private bool TryCloseInternal(bool closeReader) return true; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -1178,7 +1187,8 @@ private bool TryCloseInternal(bool closeReader) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -1204,7 +1214,8 @@ private bool TryCloseInternal(bool closeReader) // DO NOT USE stateObj after this point - it has been returned to the TdsParser's session pool and potentially handed out to another thread } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -1658,8 +1669,7 @@ override public int GetProviderSpecificValues(object[] values) override public DataTable GetSchemaTable() { SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1682,7 +1692,7 @@ override public DataTable GetSchemaTable() finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1844,7 +1854,8 @@ private bool TryGetBytesInternal(int i, long dataIndex, byte[] buffer, int buffe TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -2053,7 +2064,8 @@ private bool TryGetBytesInternal(int i, long dataIndex, byte[] buffer, int buffe return true; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -2139,51 +2151,53 @@ internal bool TryGetBytesInternalSequential(int i, byte[] buffer, int index, int TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #endif //DEBUG - if ((_sharedState._columnDataBytesRemaining == 0) || (length == 0)) - { - // No data left or nothing requested, return 0 - bytesRead = 0; - return true; - } - else - { - // if plp columns, do partial reads. Don't read the entire value in one shot. - if (_metaData[i].metaType.IsPlp) + if ((_sharedState._columnDataBytesRemaining == 0) || (length == 0)) { - // Read in data - bool result = _stateObj.TryReadPlpBytes(ref buffer, index, length, out bytesRead); - _columnDataBytesRead += bytesRead; - if (!result) - { - return false; - } - - // Query for number of bytes left - ulong left; - if (!_parser.TryPlpBytesLeft(_stateObj, out left)) - { - _sharedState._columnDataBytesRemaining = -1; - return false; - } - _sharedState._columnDataBytesRemaining = (long)left; + // No data left or nothing requested, return 0 + bytesRead = 0; return true; } else { - // Read data (not exceeding the total amount of data available) - int bytesToRead = (int)Math.Min((long)length, _sharedState._columnDataBytesRemaining); - bool result = _stateObj.TryReadByteArray(buffer, index, bytesToRead, out bytesRead); - _columnDataBytesRead += bytesRead; - _sharedState._columnDataBytesRemaining -= bytesRead; - return result; + // if plp columns, do partial reads. Don't read the entire value in one shot. + if (_metaData[i].metaType.IsPlp) + { + // Read in data + bool result = _stateObj.TryReadPlpBytes(ref buffer, index, length, out bytesRead); + _columnDataBytesRead += bytesRead; + if (!result) + { + return false; + } + + // Query for number of bytes left + ulong left; + if (!_parser.TryPlpBytesLeft(_stateObj, out left)) + { + _sharedState._columnDataBytesRemaining = -1; + return false; + } + _sharedState._columnDataBytesRemaining = (long)left; + return true; + } + else + { + // Read data (not exceeding the total amount of data available) + int bytesToRead = (int)Math.Min((long)length, _sharedState._columnDataBytesRemaining); + bool result = _stateObj.TryReadByteArray(buffer, index, bytesToRead, out bytesRead); + _columnDataBytesRead += bytesRead; + _sharedState._columnDataBytesRemaining -= bytesRead; + return result; + } } - } #if DEBUG } - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -2478,7 +2492,8 @@ private long GetCharsFromPlpData(int i, long dataIndex, char[] buffer, int buffe TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -2574,7 +2589,8 @@ private long GetCharsFromPlpData(int i, long dataIndex, char[] buffer, int buffe return cch; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -3584,8 +3600,7 @@ override public bool NextResult() private bool TryNextResult(out bool more) { SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -3594,7 +3609,8 @@ private bool TryNextResult(out bool more) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -3726,7 +3742,8 @@ private bool TryNextResult(out bool more) return true; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -3761,7 +3778,7 @@ private bool TryNextResult(out bool more) finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -3789,8 +3806,7 @@ override public bool Read() private bool TryReadInternal(bool setTimeout, out bool more) { SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -3799,7 +3815,8 @@ private bool TryReadInternal(bool setTimeout, out bool more) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -3937,9 +3954,11 @@ private bool TryReadInternal(bool setTimeout, out bool more) more = false; #if DEBUG - if ((!_sharedState._dataReady) && (_stateObj._pendingData)) { + if ((!_sharedState._dataReady) && (_stateObj._pendingData)) + { byte token; - if (!_stateObj.TryPeekByte(out token)) { + if (!_stateObj.TryPeekByte(out token)) + { return false; } @@ -3950,7 +3969,8 @@ private bool TryReadInternal(bool setTimeout, out bool more) return true; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -3988,7 +4008,7 @@ private bool TryReadInternal(bool setTimeout, out bool more) finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -4016,7 +4036,8 @@ private bool TryReadColumn(int i, bool setTimeout, bool allowPartiallyReadColumn TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -4037,7 +4058,8 @@ private bool TryReadColumn(int i, bool setTimeout, bool allowPartiallyReadColumn Debug.Assert(null != _data[i], " data buffer is null?"); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -4114,13 +4136,15 @@ private bool TryReadColumnHeader(int i) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #endif //DEBUG - return TryReadColumnInternal(i, readHeaderOnly: true); + return TryReadColumnInternal(i, readHeaderOnly: true); #if DEBUG } - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -4410,7 +4434,8 @@ private bool TryResetBlobState() } } #if DEBUG - else { + else + { Debug.Assert((_sharedState._columnDataBytesRemaining == 0 || _sharedState._columnDataBytesRemaining == -1) && _stateObj._longlen == 0, "Haven't read header yet, but column is partially read?"); } #endif @@ -4448,7 +4473,7 @@ private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateO // broken connection, so check state first. if (parser.State == TdsParserState.OpenLoggedIn) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); Task executeTask = parser.TdsExecuteSQLBatch(_resetOptionsString, (_command != null) ? _command.CommandTimeout : 0, null, stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -4760,8 +4785,7 @@ private void AssertReaderState(bool requireData, bool permitAsync, int? columnIn /// public override Task NextResultAsync(CancellationToken cancellationToken) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); try { @@ -4807,7 +4831,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) { if (t != null) { - Bid.Trace(" attempt retry %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" attempt retry {ObjectID}#\n"); PrepareForAsyncContinuation(); } @@ -4825,7 +4849,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -4889,7 +4913,7 @@ internal Task GetBytesAsync(int i, byte[] buffer, int index, int length, in { if (t != null) { - Bid.Trace(" attempt retry %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" attempt retry {ObjectID}#\n"); PrepareForAsyncContinuation(); } @@ -5060,8 +5084,7 @@ private Task GetBytesAsyncReadDataStage(int i, byte[] buffer, int index, in /// public override Task ReadAsync(CancellationToken cancellationToken) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); try { @@ -5095,48 +5118,50 @@ public override Task ReadAsync(CancellationToken cancellationToken) { #if DEBUG - try { + try + { _stateObj._shouldHaveEnoughData = true; #endif - if (_sharedState._dataReady) - { - // Clean off current row - CleanPartialReadReliable(); - } - - // If there a ROW token ready (as well as any metadata for the row) - if (_stateObj.IsRowTokenReady()) - { - // Read the ROW token - bool result = TryReadInternal(true, out more); - Debug.Assert(result, "Should not have run out of data"); + if (_sharedState._dataReady) + { + // Clean off current row + CleanPartialReadReliable(); + } - rowTokenRead = true; - if (more) + // If there a ROW token ready (as well as any metadata for the row) + if (_stateObj.IsRowTokenReady()) { - // Sequential mode, nothing left to do - if (IsCommandBehavior(CommandBehavior.SequentialAccess)) + // Read the ROW token + bool result = TryReadInternal(true, out more); + Debug.Assert(result, "Should not have run out of data"); + + rowTokenRead = true; + if (more) { - return ADP.TrueTask; + // Sequential mode, nothing left to do + if (IsCommandBehavior(CommandBehavior.SequentialAccess)) + { + return ADP.TrueTask; + } + // For non-sequential, check if we can read the row data now + else if (WillHaveEnoughData(_metaData.Length - 1)) + { + // Read row data + result = TryReadColumn(_metaData.Length - 1, setTimeout: true); + Debug.Assert(result, "Should not have run out of data"); + return ADP.TrueTask; + } } - // For non-sequential, check if we can read the row data now - else if (WillHaveEnoughData(_metaData.Length - 1)) + else { - // Read row data - result = TryReadColumn(_metaData.Length - 1, setTimeout: true); - Debug.Assert(result, "Should not have run out of data"); - return ADP.TrueTask; + // No data left, return + return ADP.FalseTask; } } - else - { - // No data left, return - return ADP.FalseTask; - } - } #if DEBUG } - finally { + finally + { _stateObj._shouldHaveEnoughData = false; } #endif @@ -5180,7 +5205,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) { if (t != null) { - Bid.Trace(" attempt retry %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" attempt retry {ObjectID}#\n"); PrepareForAsyncContinuation(); } @@ -5219,7 +5244,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -5274,16 +5299,18 @@ override public Task IsDBNullAsync(int i, CancellationToken cancellationTo if (WillHaveEnoughData(i, headerOnly: true)) { #if DEBUG - try { - _stateObj._shouldHaveEnoughData = true; + try + { + _stateObj._shouldHaveEnoughData = true; #endif - ReadColumnHeader(i); - return _data[i].IsNull ? ADP.TrueTask : ADP.FalseTask; + ReadColumnHeader(i); + return _data[i].IsNull ? ADP.TrueTask : ADP.FalseTask; #if DEBUG - } - finally { - _stateObj._shouldHaveEnoughData = false; - } + } + finally + { + _stateObj._shouldHaveEnoughData = false; + } #endif } } @@ -5398,13 +5425,15 @@ override public Task GetFieldValueAsync(int i, CancellationToken cancellat if (WillHaveEnoughData(i)) { #if DEBUG - try { + try + { _stateObj._shouldHaveEnoughData = true; #endif - return Task.FromResult(GetFieldValueInternal(i)); + return Task.FromResult(GetFieldValueInternal(i)); #if DEBUG } - finally { + finally + { _stateObj._shouldHaveEnoughData = false; } #endif @@ -5471,16 +5500,20 @@ override public Task GetFieldValueAsync(int i, CancellationToken cancellat #if DEBUG - internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait) { + internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait) + { var stateObj = _stateObj; - if (stateObj != null) { + if (stateObj != null) + { stateObj.CompletePendingReadWithSuccess(resetForcePendingReadsToWait); } } - internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait) { + internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait) + { var stateObj = _stateObj; - if (stateObj != null) { + if (stateObj != null) + { stateObj.CompletePendingReadWithFailure(errorCode, resetForcePendingReadsToWait); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs index 47736e43f7..7d892d544c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs @@ -374,8 +374,7 @@ public override void Close() private void CloseInternal(bool closeConnection) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); bool processFinallyBlock = true; try { @@ -411,7 +410,7 @@ private void CloseInternal(bool closeConnection) Connection.Close(); } - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } } @@ -434,11 +433,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) { - IntPtr hscp = IntPtr.Zero; - if (Bid.AdvancedOn) - { - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - } + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); try { _hasRows = false; @@ -471,10 +466,7 @@ internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) } finally { - if (Bid.AdvancedOn) - { - Bid.ScopeLeave(ref hscp); - } + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -494,11 +486,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) internal unsafe bool InternalRead(bool ignoreNonFatalErrors) { - IntPtr hscp = IntPtr.Zero; - if (Bid.AdvancedOn) - { - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - } + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); try { // Don't move unless currently in results. @@ -537,10 +525,7 @@ internal unsafe bool InternalRead(bool ignoreNonFatalErrors) } finally { - if (Bid.AdvancedOn) - { - Bid.ScopeLeave(ref hscp); - } + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1144,10 +1129,12 @@ internal override SmiExtendedMetaData[] GetInternalSmiMetaData() for (int i = 0; i < _visibleColumnCount; i++) { #if DEBUG - if (_currentMetaData[_indexMap[i]].IsHidden.IsTrue) { + if (_currentMetaData[_indexMap[i]].IsHidden.IsTrue) + { sawHiddenColumn = true; } - else { + else + { Debug.Assert(!sawHiddenColumn); } #endif @@ -1328,17 +1315,14 @@ internal ReaderEventSink(SqlDataReaderSmi reader, SmiEventSink parent) internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIsRow) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, md.Length=%d nextEventIsRow=%d.\n", reader.ObjectID, (null != md) ? md.Length : -1, nextEventIsRow); + var mdLength = (null != md) ? md.Length : -1; + SqlClientEventSource._log.Trace($" {reader.ObjectID}#, md.Length={mdLength} nextEventIsRow={nextEventIsRow}.\n"); - if (null != md) + if (null != md) + { + for (int i = 0; i < md.Length; i++) { - for (int i = 0; i < md.Length; i++) - { - Bid.Trace(" %d#, metaData[%d] is %ls%ls\n", - reader.ObjectID, i, md[i].GetType().ToString(), md[i].TraceString()); - } + SqlClientEventSource._log.Trace($" {reader.ObjectID}#, metaData[{i}] is {md[i].GetType().ToString()}{md[i].TraceString()}\n"); } } this.reader.MetaDataAvailable(md, nextEventIsRow); @@ -1347,37 +1331,25 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs // Obsolete V2- method internal override void RowAvailable(ITypedGetters row) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# (v2).\n", reader.ObjectID); - } + SqlClientEventSource._log.Trace($" {reader.ObjectID}# (v2).\n"); this.reader.RowAvailable(row); } internal override void RowAvailable(ITypedGettersV3 row) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# (ITypedGettersV3).\n", reader.ObjectID); - } + SqlClientEventSource._log.Trace($" {reader.ObjectID}# (ITypedGettersV3).\n"); this.reader.RowAvailable(row); } internal override void RowAvailable(SmiTypedGetterSetter rowData) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# (SmiTypedGetterSetter).\n", reader.ObjectID); - } + SqlClientEventSource._log.Trace($" {reader.ObjectID}# (SmiTypedGetterSetter).\n"); this.reader.RowAvailable(rowData); } internal override void StatementCompleted(int recordsAffected) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# recordsAffected=%d.\n", reader.ObjectID, recordsAffected); - } + SqlClientEventSource._log.Trace($" {reader.ObjectID}# recordsAffected= {recordsAffected}.\n"); // devnote: relies on SmiEventSink_Default to pass event to parent // Both command and reader care about StatementCompleted, but for different reasons. @@ -1388,10 +1360,7 @@ internal override void StatementCompleted(int recordsAffected) internal override void BatchCompleted() { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#.\n", reader.ObjectID); - } + SqlClientEventSource._log.Trace($" {reader.ObjectID}#.\n"); // devnote: relies on SmiEventSink_Default to pass event to parent // parent's callback *MUST* come before reader's BatchCompleted, since diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs index 6e67948cea..3978939845 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs @@ -89,7 +89,7 @@ public void Initialize() SqlInternalConnection connection = _connection; SqlConnection usersConnection = connection.Connection; - Bid.Trace(" %d#, Connection %d#, delegating transaction.\n", ObjectID, connection.ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, delegating transaction.\n"); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -105,7 +105,7 @@ public void Initialize() #endif //DEBUG if (connection.IsEnlistedInTransaction) { // defect first - Bid.Trace(" %d#, Connection %d#, was enlisted, now defecting.\n", ObjectID, connection.ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, was enlisted, now defecting.\n"); connection.EnlistNull(); } @@ -165,7 +165,7 @@ public Byte[] Promote() byte[] returnValue = null; SqlConnection usersConnection = connection.Connection; - Bid.Trace(" %d#, Connection %d#, promoting transaction.\n", ObjectID, connection.ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, promoting transaction.\n"); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -264,7 +264,7 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) SqlInternalConnection connection = GetValidConnection(); SqlConnection usersConnection = connection.Connection; - Bid.Trace(" %d#, Connection %d#, aborting transaction.\n", ObjectID, connection.ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, aborting transaction.\n"); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -357,7 +357,7 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) SqlInternalConnection connection = GetValidConnection(); SqlConnection usersConnection = connection.Connection; - Bid.Trace(" %d#, Connection %d#, committing transaction.\n", ObjectID, connection.ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, committing transaction.\n"); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -487,7 +487,7 @@ internal void TransactionEnded(SysTx.Transaction transaction) if (connection != null) { - Bid.Trace(" %d#, Connection %d#, transaction completed externally.\n", ObjectID, connection.ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, transaction completed externally.\n"); lock (connection) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs index 77a79630b1..a9765f975a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -286,7 +286,6 @@ private static void InvokeCallback(object eventContextPair) // BID members // ----------- - internal const Bid.ApiGroup NotificationsTracePoints = (Bid.ApiGroup)0x2000; private readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount); private static int _objectTypeCount; // Bid counter @@ -317,8 +316,7 @@ public SqlDependency(SqlCommand command) : this(command, null, SQL.SqlDependency [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public SqlDependency(SqlCommand command, string options, int timeout) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, options: '%ls', timeout: '%d'", ObjectID, options, timeout); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, options: '{options}', timeout: '{timeout}'"); try { if (InOutOfProcHelper.InProc) @@ -341,7 +339,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -438,8 +436,7 @@ public event OnChangeEventHandler OnChange // EventHandlers to be fired when dependency is notified. add { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { if (null != value) @@ -450,12 +447,12 @@ public event OnChangeEventHandler OnChange { if (_dependencyFired) { // If fired, fire the new event immediately. - Bid.NotificationsTrace(" Dependency already fired, firing new event.\n"); + SqlClientEventSource._log.NotificationsTrace($" Dependency already fired, firing new event.\n"); sqlNotificationEvent = new SqlNotificationEventArgs(SqlNotificationType.Subscribe, SqlNotificationInfo.AlreadyChanged, SqlNotificationSource.Client); } else { - Bid.NotificationsTrace(" Dependency has not fired, adding new event.\n"); + SqlClientEventSource._log.NotificationsTrace($" Dependency has not fired, adding new event.\n"); EventContextPair pair = new EventContextPair(value, this); if (!_eventList.Contains(pair)) { @@ -476,13 +473,12 @@ public event OnChangeEventHandler OnChange } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } remove { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { if (null != value) @@ -500,7 +496,7 @@ public event OnChangeEventHandler OnChange } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } } @@ -517,8 +513,7 @@ public void AddCommandDependency(SqlCommand command) { // Adds command to dependency collection so we automatically create the SqlNotificationsRequest object // and listen for a notification for the added commands. - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { if (command == null) @@ -530,7 +525,7 @@ public void AddCommandDependency(SqlCommand command) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -556,9 +551,9 @@ private static void ObtainProcessDispatcher() if (nativeStorage == null) { - Bid.NotificationsTrace(" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher.\n"); + SqlClientEventSource._log.NotificationsTrace($" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher.\n"); #if DEBUG // Possibly expensive, limit to debug. - Bid.NotificationsTrace(" AppDomain.CurrentDomain.FriendlyName: %ls\n", AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource._log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}\n"); #endif _AppDomain masterDomain = SNINativeMethodWrapper.GetDefaultAppDomain(); @@ -583,32 +578,32 @@ private static void ObtainProcessDispatcher() } else { - Bid.NotificationsTrace(" ERROR - ObjectHandle.Unwrap returned null!\n"); + SqlClientEventSource._log.NotificationsTrace($" ERROR - ObjectHandle.Unwrap returned null!\n"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyObtainProcessDispatcherFailureObjectHandle); } } else { - Bid.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!\n"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!\n"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureCreateInstance); } } else { - Bid.NotificationsTrace(" ERROR - unable to obtain default AppDomain!\n"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - unable to obtain default AppDomain!\n"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureAppDomain); } } else { - Bid.NotificationsTrace(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher.\n"); + SqlClientEventSource._log.NotificationsTrace(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher.\n"); #if DEBUG // Possibly expensive, limit to debug. - Bid.NotificationsTrace(" AppDomain.CurrentDomain.FriendlyName: %ls\n", AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource._log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}\n"); #endif BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(nativeStorage); _processDispatcher = GetDeserializedObject(formatter, stream); // Deserialize and set for appdomain. - Bid.NotificationsTrace(" processDispatcher obtained, ID: %d\n", _processDispatcher.ObjectID); + SqlClientEventSource._log.NotificationsTrace($" processDispatcher obtained, ID: {_processDispatcher.ObjectID}\n"); } } @@ -655,8 +650,7 @@ public static bool Start(string connectionString, string queue) internal static bool Start(string connectionString, string queue, bool useDefaults) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " AppDomainKey: '%ls', queue: '%ls'", AppDomainKey, queue); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -729,7 +723,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul SqlDependencyPerAppDomainDispatcher.SingletonInstance, out errorOccurred, out appDomainStart); - Bid.NotificationsTrace(" Start (defaults) returned: '%d', with service: '%ls', server: '%ls', database: '%ls'\n", result, service, server, database); + SqlClientEventSource._log.NotificationsTrace($" Start (defaults) returned: '{result}', with service: '{service}', server: '{server}', database: '{database}'\n"); } finally { @@ -751,7 +745,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - Bid.NotificationsTrace(" Exception occurred from Stop() after duplicate was found on Start().\n"); + SqlClientEventSource._log.NotificationsTrace(" Exception occurred from Stop() after duplicate was found on Start().\n"); } throw SQL.SqlDependencyDuplicateStart(); } @@ -764,7 +758,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul queue, _appDomainKey, SqlDependencyPerAppDomainDispatcher.SingletonInstance); - Bid.NotificationsTrace(" Start (user provided queue) returned: '%d'\n", result); + SqlClientEventSource._log.NotificationsTrace($" Start (user provided queue) returned: '{result}'\n"); // No need to call AddToServerDatabaseHash since if not using default queue user is required // to provide options themselves. } @@ -778,7 +772,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - Bid.NotificationsTrace(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...).\n"); + SqlClientEventSource._log.NotificationsTrace($" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...).\n"); throw; } } @@ -787,7 +781,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -807,8 +801,7 @@ public static bool Stop(string connectionString, string queue) internal static bool Stop(string connectionString, string queue, bool useDefaults, bool startFailed) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " AppDomainKey: '%ls', queue: '%ls'", AppDomainKey, queue); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -918,7 +911,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -928,8 +921,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault private static bool AddToServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " server: '%ls', database: '%ls', service: '%ls'", server, databaseService.Database, databaseService.Service); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); try { bool result = false; @@ -940,7 +932,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!_serverUserHash.ContainsKey(server)) { - Bid.NotificationsTrace(" Hash did not contain server, adding.\n"); + SqlClientEventSource._log.NotificationsTrace(" Hash did not contain server, adding.\n"); identityDatabaseHash = new Dictionary>(); _serverUserHash.Add(server, identityDatabaseHash); } @@ -953,7 +945,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!identityDatabaseHash.ContainsKey(identityUser)) { - Bid.NotificationsTrace(" Hash contained server but not user, adding user.\n"); + SqlClientEventSource._log.NotificationsTrace(" Hash contained server but not user, adding user.\n"); databaseServiceList = new List(); identityDatabaseHash.Add(identityUser, databaseServiceList); } @@ -964,13 +956,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!databaseServiceList.Contains(databaseService)) { - Bid.NotificationsTrace(" Adding database.\n"); + SqlClientEventSource._log.NotificationsTrace(" Adding database.\n"); databaseServiceList.Add(databaseService); result = true; } else { - Bid.NotificationsTrace(" ERROR - hash already contained server, user, and database - we will throw!.\n"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - hash already contained server, user, and database - we will throw!.\n"); } } @@ -978,14 +970,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } private static void RemoveFromServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " server: '%ls', database: '%ls', service: '%ls'", server, databaseService.Database, databaseService.Service); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); try { lock (_serverUserHash) @@ -1005,43 +996,43 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair int index = databaseServiceList.IndexOf(databaseService); if (index >= 0) { - Bid.NotificationsTrace(" Hash contained server, user, and database - removing database.\n"); + SqlClientEventSource._log.NotificationsTrace(" Hash contained server, user, and database - removing database.\n"); databaseServiceList.RemoveAt(index); if (databaseServiceList.Count == 0) { - Bid.NotificationsTrace(" databaseServiceList count 0, removing the list for this server and user.\n"); + SqlClientEventSource._log.NotificationsTrace(" databaseServiceList count 0, removing the list for this server and user.\n"); identityDatabaseHash.Remove(identityUser); if (identityDatabaseHash.Count == 0) { - Bid.NotificationsTrace(" identityDatabaseHash count 0, removing the hash for this server.\n"); + SqlClientEventSource._log.NotificationsTrace(" identityDatabaseHash count 0, removing the hash for this server.\n"); _serverUserHash.Remove(server); } } } else { - Bid.NotificationsTrace(" ERROR - hash contained server and user but not database!\n"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - hash contained server and user but not database!\n"); Debug.Assert(false, "Unexpected state - hash did not contain database!"); } } else { - Bid.NotificationsTrace(" ERROR - hash contained server but not user!\n"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - hash contained server but not user!\n"); Debug.Assert(false, "Unexpected state - hash did not contain user!"); } } else { - Bid.NotificationsTrace(" ERROR - hash did not contain server!\n"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - hash did not contain server!\n"); Debug.Assert(false, "Unexpected state - hash did not contain server!"); } } } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1049,8 +1040,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { // Server must be an exact match, but user and database only needs to match exactly if there is more than one // for the given user or database passed. That is ambiguious and we must fail. - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " server: '%ls', failoverServer: '%ls', database: '%ls'", server, failoverServer, database); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" server: '{server}', failoverServer: '{failoverServer}', database: '{database}'"); try { string result; @@ -1061,17 +1051,17 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { if (0 == _serverUserHash.Count) { // Special error for no calls to start. - Bid.NotificationsTrace(" ERROR - no start calls have been made, about to throw.\n"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - no start calls have been made, about to throw.\n"); throw SQL.SqlDepDefaultOptionsButNoStart(); } else if (!ADP.IsEmpty(failoverServer) && _serverUserHash.ContainsKey(failoverServer)) { - Bid.NotificationsTrace(" using failover server instead\n"); + SqlClientEventSource._log.NotificationsTrace(" using failover server instead\n"); server = failoverServer; } else { - Bid.NotificationsTrace(" ERROR - not listening to this server, about to throw.\n"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - not listening to this server, about to throw.\n"); throw SQL.SqlDependencyNoMatchingServerStart(); } } @@ -1084,7 +1074,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { if (identityDatabaseHash.Count > 1) { - Bid.NotificationsTrace(" ERROR - not listening for this user, but listening to more than one other user, about to throw.\n"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - not listening for this user, but listening to more than one other user, about to throw.\n"); throw SQL.SqlDependencyNoMatchingServerStart(); } else @@ -1130,19 +1120,19 @@ internal static string GetDefaultComposedOptions(string server, string failoverS } else { // More than one database for given server, ambiguous - fail the default case! - Bid.NotificationsTrace(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database.\n"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database.\n"); throw SQL.SqlDependencyNoMatchingServerDatabaseStart(); } } } Debug.Assert(!ADP.IsEmpty(result), "GetDefaultComposedOptions should never return null or empty string!"); - Bid.NotificationsTrace(" resulting options: '%ls'.\n", result); + SqlClientEventSource._log.NotificationsTrace($" resulting options: '{result}'.\n"); return result; } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1154,8 +1144,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS // use this list for a reverse lookup based on server. internal void AddToServerList(string server) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, server: '%ls'", ObjectID, server); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); try { lock (_serverList) @@ -1163,7 +1152,7 @@ internal void AddToServerList(string server) int index = _serverList.BinarySearch(server, StringComparer.OrdinalIgnoreCase); if (0 > index) { // If less than 0, item was not found in list. - Bid.NotificationsTrace(" Server not present in hashtable, adding server: '%ls'.\n", server); + SqlClientEventSource._log.NotificationsTrace($" Server not present in hashtable, adding server: '{server}'.\n"); index = ~index; // BinarySearch returns the 2's compliment of where the item should be inserted to preserver a sorted list after insertion. _serverList.Insert(index, server); @@ -1172,7 +1161,7 @@ internal void AddToServerList(string server) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1186,8 +1175,7 @@ internal bool ContainsServer(string server) internal string ComputeHashAndAddToDispatcher(SqlCommand command) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, SqlCommand: %d#", ObjectID, command.ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); try { // Create a string representing the concatenation of the connection string, command text and .ToString on all parameter values. @@ -1202,19 +1190,18 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) string commandHash = ComputeCommandHash(command.Connection.ConnectionString, command); // calculate the string representation of command string idString = SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddCommandEntry(commandHash, this); // Add to map. - Bid.NotificationsTrace(" computed id string: '%ls'.\n", idString); + SqlClientEventSource._log.NotificationsTrace($" computed id string: '{idString}'.\n"); return idString; } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { List eventList = null; @@ -1232,12 +1219,12 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql // raises Timeout event but before removing this event from the list. If notification is received from // server in this case, we will hit this code path. // It is safe to ignore this race condition because no event is sent to user and no leak happens. - Bid.NotificationsTrace(" ignore notification received after timeout!"); + SqlClientEventSource._log.NotificationsTrace(" ignore notification received after timeout!"); } else { Debug.Assert(false, "Received notification twice - we should never enter this state!"); - Bid.NotificationsTrace(" ERROR - notification received twice - we should never enter this state!"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - notification received twice - we should never enter this state!"); } } else @@ -1251,7 +1238,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (eventList != null) { - Bid.NotificationsTrace(" Firing events.\n"); + SqlClientEventSource._log.NotificationsTrace(" Firing events.\n"); foreach (EventContextPair pair in eventList) { pair.Invoke(new SqlNotificationEventArgs(type, info, source)); @@ -1260,20 +1247,19 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } // This method is used by SqlCommand. internal void StartTimer(SqlNotificationRequest notificationRequest) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { if (_expirationTime == DateTime.MaxValue) { - Bid.NotificationsTrace(" We've timed out, executing logic.\n"); + SqlClientEventSource._log.NotificationsTrace(" We've timed out, executing logic.\n"); int seconds = SQL.SqlDependencyServerTimeout; if (0 != _timeout) @@ -1292,7 +1278,7 @@ internal void StartTimer(SqlNotificationRequest notificationRequest) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1303,9 +1289,9 @@ internal void StartTimer(SqlNotificationRequest notificationRequest) private void AddCommandInternal(SqlCommand cmd) { if (cmd != null) - { // Don't bother with BID if command null. - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, SqlCommand: %d#", ObjectID, cmd.ObjectID); + { + // Don't bother with BID if command null. + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {cmd.ObjectID}#"); try { SqlConnection connection = cmd.Connection; @@ -1315,7 +1301,7 @@ private void AddCommandInternal(SqlCommand cmd) // Fail if cmd has notification that is not already associated with this dependency. if (cmd._sqlDep == null || cmd._sqlDep != this) { - Bid.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception.\n"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception.\n"); throw SQL.SqlCommandHasExistingSqlNotificationRequest(); } } @@ -1346,7 +1332,7 @@ private void AddCommandInternal(SqlCommand cmd) Debug.Assert(0 == _eventList.Count, "How can we have an event at this point?"); if (0 == _eventList.Count) { // Keep logic just in case. - Bid.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point.\n"); + SqlClientEventSource._log.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point.\n"); needToInvalidate = true; // Delay invalidation until outside of lock. } } @@ -1360,15 +1346,14 @@ private void AddCommandInternal(SqlCommand cmd) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } } private string ComputeCommandHash(string connectionString, SqlCommand command) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, SqlCommand: %d#", ObjectID, command.ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); try { // Create a string representing the concatenation of the connection string, the command text and .ToString on all its parameter values. @@ -1426,12 +1411,12 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) string result = builder.ToString(); - Bid.NotificationsTrace(" ComputeCommandHash result: '%ls'.\n", result); + SqlClientEventSource._log.NotificationsTrace($" ComputeCommandHash result: '{result}'.\n"); return result; } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index 438315608f..0248aa7167 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -79,8 +79,7 @@ internal int ObjectID internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, queue: '%ls'", ObjectID, hashHelper.Queue); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, queue: '{hashHelper.Queue}'"); bool setupCompleted = false; @@ -104,7 +103,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(_hashHelper.ConnectionStringBuilder.ConnectionString); - Bid.NotificationsTrace(" Modified connection string: '%ls'\n", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource._log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'\n"); #endif // Always use ConnectionStringBuilder since in default case it is different from the @@ -219,7 +218,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -279,8 +278,7 @@ internal string Server // SqlDependencyProcessDispatcher.QueueAppDomainUnload on AppDomain.Unload. internal bool AppDomainUnload(string appDomainKey) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, AppDomainKey: '%ls'", ObjectID, appDomainKey); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, AppDomainKey: '{ appDomainKey}'"); try { Debug.Assert(!ADP.IsEmpty(appDomainKey), "Unexpected empty appDomainKey!"); @@ -291,9 +289,9 @@ internal bool AppDomainUnload(string appDomainKey) { if (_appDomainKeyHash.ContainsKey(appDomainKey)) { // Do nothing if AppDomain did not call Start! - Bid.NotificationsTrace(" _appDomainKeyHash contained AppDomainKey: '%ls'.\n", appDomainKey); + SqlClientEventSource._log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}'.\n"); int value = _appDomainKeyHash[appDomainKey]; - Bid.NotificationsTrace(" _appDomainKeyHash for AppDomainKey: '%ls' count: '%d'.\n", appDomainKey, value); + SqlClientEventSource._log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{appDomainKey}' count: '{value}'.\n"); Debug.Assert(value > 0, "Why is value 0 or less?"); bool ignored = false; @@ -310,28 +308,27 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { - Bid.NotificationsTrace(" ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '%ls' entry not removed from hash. Count: %d'\n", appDomainKey, _appDomainKeyHash[appDomainKey]); + SqlClientEventSource._log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{appDomainKey}' entry not removed from hash. Count: {_appDomainKeyHash[appDomainKey]}'\n"); } } else { - Bid.NotificationsTrace(" _appDomainKeyHash did not contain AppDomainKey: '%ls'.\n", appDomainKey); + SqlClientEventSource._log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}'.\n"); } } - Bid.NotificationsTrace(" Exiting, _stopped: '%d'.\n", _stopped); + SqlClientEventSource._log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{_stopped}'.\n"); return _stopped; } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } private void AsynchronouslyQueryServiceBrokerQueue() { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { AsyncCallback callback = new AsyncCallback(AsyncResultCallback); @@ -339,14 +336,13 @@ private void AsynchronouslyQueryServiceBrokerQueue() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } private void AsyncResultCallback(IAsyncResult asyncResult) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { using (SqlDataReader reader = _com.EndExecuteReader(asyncResult)) @@ -373,7 +369,7 @@ private void AsyncResultCallback(IAsyncResult asyncResult) throw; } - Bid.NotificationsTrace(" Exception occurred.\n"); + SqlClientEventSource._log.NotificationsTrace($" Exception occurred.\n"); if (!_stop) { // Only assert if not in cancel path. ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. @@ -392,14 +388,13 @@ private void AsyncResultCallback(IAsyncResult asyncResult) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } private void CreateQueueAndService(bool restart) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { SqlCommand com = new SqlCommand(); @@ -529,19 +524,18 @@ private void CreateQueueAndService(bool restart) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { appDomainStart = false; // Reset out param. int result = Interlocked.Increment(ref _startCount); // Add to refCount. - Bid.NotificationsTrace(" %d#, incremented _startCount: %d\n", _staticInstance.ObjectID, result); + SqlClientEventSource._log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> {_staticInstance.ObjectID}#, incremented _startCount: {result}\n"); // Dictionary used to track how many times start has been called per app domain. // For each increment, add to count, and create entry if not present. @@ -550,26 +544,25 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { _appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1; - Bid.NotificationsTrace(" _appDomainKeyHash contained AppDomainKey: '%ls', incremented count: '%d'.\n", appDomainKey, _appDomainKeyHash[appDomainKey]); + SqlClientEventSource._log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', incremented count: '{_appDomainKeyHash[appDomainKey]}'.\n"); } else { _appDomainKeyHash[appDomainKey] = 1; appDomainStart = true; - Bid.NotificationsTrace(" _appDomainKeyHash did not contain AppDomainKey: '%ls', added to hashtable and value set to 1.\n", appDomainKey); + SqlClientEventSource._log.NotificationsTrace($" _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}', added to hashtable and value set to 1.\n"); } } } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } private void ProcessNotificationResults(SqlDataReader reader) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { Guid handle = Guid.Empty; // Conversation_handle. Always close this! @@ -579,16 +572,17 @@ private void ProcessNotificationResults(SqlDataReader reader) { while (reader.Read()) { - Bid.NotificationsTrace(" Row read.\n"); + SqlClientEventSource._log.NotificationsTrace($" Row read.\n"); #if DEBUG - for (int i=0; i column: %ls, value: %ls\n", reader.GetName(i), reader.GetValue(i).ToString()); + for (int i = 0; i < reader.FieldCount; i++) + { + SqlClientEventSource._log.NotificationsTrace($" column: {reader.GetName(i)}, value: {reader.GetValue(i).ToString()}\n"); } #endif string msgType = reader.GetString(0); - Bid.NotificationsTrace(" msgType: '%ls'\n", msgType); + SqlClientEventSource._log.NotificationsTrace($" msgType: '{ msgType}'\n"); handle = reader.GetGuid(1); - // Bid.NotificationsTrace(" conversationHandle: '%p(GUID)'\n", conversationHandle); + // SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.ProcessNotificationResults(SqlDataReader)|DEP> conversationHandle: '%p(GUID)'\n", conversationHandle); // Only process QueryNotification messages. if (0 == String.Compare(msgType, "http://schemas.microsoft.com/SQL/Notifications/QueryNotification", StringComparison.OrdinalIgnoreCase)) @@ -600,7 +594,7 @@ private void ProcessNotificationResults(SqlDataReader reader) if (null != notification) { string key = notification.Key; - Bid.NotificationsTrace(" Key: '%ls'\n", key); + SqlClientEventSource._log.NotificationsTrace($" Key: '{key}'\n"); int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash" if (index >= 0) @@ -629,25 +623,25 @@ private void ProcessNotificationResults(SqlDataReader reader) else { Debug.Assert(false, "Received notification but do not have an associated PerAppDomainDispatcher!"); - Bid.NotificationsTrace(" Received notification but do not have an associated PerAppDomainDispatcher!\n"); + SqlClientEventSource._log.NotificationsTrace($" Received notification but do not have an associated PerAppDomainDispatcher!\n"); } } else { Debug.Assert(false, "Unexpected ID format received!"); - Bid.NotificationsTrace(" Unexpected ID format received!\n"); + SqlClientEventSource._log.NotificationsTrace($" Unexpected ID format received!\n"); } } else { Debug.Assert(false, "Null notification returned from ProcessMessage!"); - Bid.NotificationsTrace(" Null notification returned from ProcessMessage!\n"); + SqlClientEventSource._log.NotificationsTrace($" Null notification returned from ProcessMessage!\n"); } } else { Debug.Assert(false, "Null payload for QN notification type!"); - Bid.NotificationsTrace(" Null payload for QN notification type!\n"); + SqlClientEventSource._log.NotificationsTrace($" Null payload for QN notification type!\n"); } } else @@ -655,7 +649,7 @@ private void ProcessNotificationResults(SqlDataReader reader) handle = Guid.Empty; // VSDD 546707: this assert was hit by SQL Notification fuzzing tests, disable it to let these tests run on Debug bits // Debug.Assert(false, "Unexpected message format received!"); - Bid.NotificationsTrace(" Unexpected message format received!\n"); + SqlClientEventSource._log.NotificationsTrace($" Unexpected message format received!\n"); } } } @@ -687,7 +681,7 @@ private void ProcessNotificationResults(SqlDataReader reader) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -696,9 +690,9 @@ private void ProcessNotificationResults(SqlDataReader reader) [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] private void Restart(object unused) - { // Unused arg required by TimerCallback. - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + { + // Unused arg required by TimerCallback. + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { try @@ -860,14 +854,13 @@ private void Restart(object unused) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } internal bool Stop(string appDomainKey, out bool appDomainStop) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { appDomainStop = false; @@ -888,14 +881,14 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) Debug.Assert(value > 0, "Unexpected count for appDomainKey"); - Bid.NotificationsTrace(" _appDomainKeyHash contained AppDomainKey: '%ls', pre-decrement Count: '%d'.\n", appDomainKey, value); + SqlClientEventSource._log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', pre-decrement Count: '{value}'.\n"); if (value > 0) { _appDomainKeyHash[appDomainKey] = value - 1; } else { - Bid.NotificationsTrace(" ERROR pre-decremented count <= 0!\n"); + SqlClientEventSource._log.NotificationsTrace($" ERROR pre-decremented count <= 0!\n"); Debug.Assert(false, "Unexpected AppDomainKey count in Stop()"); } @@ -907,7 +900,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - Bid.NotificationsTrace(" ERROR appDomainKey not null and not found in hash!\n"); + SqlClientEventSource._log.NotificationsTrace($" ERROR appDomainKey not null and not found in hash!\n"); Debug.Assert(false, "Unexpected state on Stop() - no AppDomainKey entry in hashtable!"); } } @@ -919,7 +912,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) if (0 == result) { // If we've reached refCount 0, destroy. // Lock to ensure Cancel() complete prior to other thread calling TearDown. - Bid.NotificationsTrace(" Reached 0 count, cancelling and waiting.\n"); + SqlClientEventSource._log.NotificationsTrace($" Reached 0 count, cancelling and waiting.\n"); lock (this) { try @@ -962,7 +955,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) // TearDownAndDispose in the maximum retry period case as well as in the _errorState case. if (_errorState || retryStopwatch.Elapsed.Seconds >= 30) { - Bid.NotificationsTrace(" forcing cleanup. elapsedSeconds: '%d', _errorState: '%d'.\n", retryStopwatch.Elapsed.Seconds, _errorState); + SqlClientEventSource._log.NotificationsTrace($" forcing cleanup. elapsedSeconds: '{retryStopwatch.Elapsed.Seconds}', _errorState: '{_errorState}'.\n"); Timer retryTimer = _retryTimer; _retryTimer = null; @@ -982,7 +975,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - Bid.NotificationsTrace(" _startCount not 0 after decrement. _startCount: '%d'.\n", _startCount); + SqlClientEventSource._log.NotificationsTrace($" _startCount not 0 after decrement. _startCount: '{_startCount}'.\n"); } Debug.Assert(0 <= _startCount, "Invalid start count state"); @@ -991,14 +984,13 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } private void SynchronouslyQueryServiceBrokerQueue() { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { using (SqlDataReader reader = _com.ExecuteReader()) @@ -1008,15 +1000,14 @@ private void SynchronouslyQueryServiceBrokerQueue() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } [SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")] private void TearDownAndDispose() { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { lock (this) @@ -1089,7 +1080,7 @@ private void TearDownAndDispose() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } } @@ -1233,42 +1224,42 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) catch (ArgumentException e) { ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace. - Bid.Trace(" Exception thrown - Enum.Parse failed to parse the value '%ls' of the attribute '%ls'.\n", xmlReader.Value, xmlReader.LocalName); + SqlClientEventSource._log.Trace($" Exception thrown - Enum.Parse failed to parse the value '{xmlReader.Value}' of the attribute '{xmlReader.LocalName}'.\n"); return null; } } if (MessageAttributes.All != messageAttributes) { - Bid.Trace(" Not all expected attributes in Message; messageAttributes = '%d'.\n", (int)messageAttributes); + SqlClientEventSource._log.Trace($" Not all expected attributes in Message; messageAttributes = '{(int)messageAttributes}'.\n"); return null; } // Proceed to the "Message" node. if (!xmlReader.Read()) { - Bid.Trace(" unexpected Read failure on xml or unexpected structure of xml.\n"); + SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); return null; } // Verify state after Read(). if ((XmlNodeType.Element != xmlReader.NodeType) || (0 != String.Compare(xmlReader.LocalName, MessageNode, StringComparison.OrdinalIgnoreCase))) { - Bid.Trace(" unexpected Read failure on xml or unexpected structure of xml.\n"); + SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); return null; } // Proceed to the Text Node. if (!xmlReader.Read()) { - Bid.Trace(" unexpected Read failure on xml or unexpected structure of xml.\n"); + SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); return null; } // Verify state after Read(). if (xmlReader.NodeType != XmlNodeType.Text) { - Bid.Trace(" unexpected Read failure on xml or unexpected structure of xml.\n"); + SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); return null; } @@ -1278,7 +1269,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the Text Node. if (!xmlMessageReader.Read()) { - Bid.Trace(" unexpected Read failure on xml or unexpected structure of xml.\n"); + SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); return null; } @@ -1289,7 +1280,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - Bid.Trace(" unexpected Read failure on xml or unexpected structure of xml.\n"); + SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); return null; } } @@ -1298,7 +1289,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - Bid.Trace(" unexpected Read failure on xml or unexpected structure of xml.\n"); + SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); return null; // failure } } @@ -1478,20 +1469,19 @@ internal int ObjectID private SqlDependencyProcessDispatcher(object dummyVariable) { Debug.Assert(null == _staticInstance, "Real constructor called with static instance already created!"); - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { #if DEBUG // Possibly expensive, limit to debug. - Bid.NotificationsTrace(" %d#, AppDomain.CurrentDomain.FriendlyName: %ls\n", ObjectID, AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}\n"); #endif _connectionContainers = new Dictionary(); _sqlDependencyPerAppDomainDispatchers = new Dictionary(); } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1499,19 +1489,18 @@ private SqlDependencyProcessDispatcher(object dummyVariable) // Required to be public, even on internal class, for Remoting infrastructure. public SqlDependencyProcessDispatcher() { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { // Empty constructor and object - dummy to obtain singleton. #if DEBUG // Possibly expensive, limit to debug. - Bid.NotificationsTrace(" %d#, AppDomain.CurrentDomain.FriendlyName: %ls\n", ObjectID, AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}\n"); #endif } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1537,8 +1526,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS out string user, string queue) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, queue: %ls", _staticInstance.ObjectID, queue); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {_staticInstance.ObjectID}#, queue: {queue}"); try { // Force certain connection string properties to be used by SqlDependencyProcessDispatcher. @@ -1571,7 +1559,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1583,8 +1571,7 @@ public override object InitializeLifetimeService() private void Invalidate(string server, SqlNotification sqlNotification) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, server: %ls", ObjectID, server); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, server: {server}"); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1616,7 +1603,7 @@ private void Invalidate(string server, SqlNotification sqlNotification) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1633,8 +1620,7 @@ internal void QueueAppDomainUnloading(string appDomainKey) // This method is only called by queued work-items from the method above. private void AppDomainUnloading(object state) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { string appDomainKey = (string)state; @@ -1666,7 +1652,7 @@ private void AppDomainUnloading(object state) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1733,8 +1719,7 @@ private bool Start(string connectionString, out bool appDomainStart, bool useDefaults) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, queue: '%ls', appDomainKey: '%ls', perAppDomainDispatcher ID: '%d'", ObjectID, queueService, appDomainKey, dispatcher.ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, queue: '{ queueService}', appDomainKey: '{appDomainKey}', perAppDomainDispatcher ID: '{dispatcher.ObjectID}'"); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1761,7 +1746,7 @@ private bool Start(string connectionString, queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - Bid.NotificationsTrace(" Modified connection string: '%ls'\n", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource._log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'\n"); #endif bool started = false; @@ -1771,7 +1756,7 @@ private bool Start(string connectionString, { if (!_connectionContainers.ContainsKey(hashHelper)) { - Bid.NotificationsTrace(" %d#, hashtable miss, creating new container.\n", ObjectID); + SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, hashtable miss, creating new container.\n"); container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults); _connectionContainers.Add(hashHelper, container); started = true; @@ -1780,10 +1765,10 @@ private bool Start(string connectionString, else { container = _connectionContainers[hashHelper]; - Bid.NotificationsTrace(" %d#, hashtable hit, container: %d\n", ObjectID, container.ObjectID); + SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}\n"); if (container.InErrorState) { - Bid.NotificationsTrace(" %d#, container: %d is in error state!\n", ObjectID, container.ObjectID); + SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, container: {container.ObjectID} is in error state!\n"); errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start(). } else @@ -1798,16 +1783,16 @@ private bool Start(string connectionString, server = container.Server; database = container.Database; queueService = container.Queue; - Bid.NotificationsTrace(" %d#, default service: '%ls', server: '%ls', database: '%ls'\n", ObjectID, queueService, server, database); + SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, default service: '{queueService}', server: '{server}', database: '{database}'\n"); } - Bid.NotificationsTrace(" %d#, started: %d\n", ObjectID, started); + SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, started: {started}\n"); return started; } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -1824,8 +1809,7 @@ internal bool Stop(string connectionString, string appDomainKey, out bool appDomainStop) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, queue: '%ls'", ObjectID, queueService); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, queue: '{queueService}'"); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1843,7 +1827,7 @@ internal bool Stop(string connectionString, queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - Bid.NotificationsTrace(" Modified connection string: '%ls'\n", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource._log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'\n"); #endif bool stopped = false; @@ -1853,7 +1837,7 @@ internal bool Stop(string connectionString, if (_connectionContainers.ContainsKey(hashHelper)) { SqlConnectionContainer container = _connectionContainers[hashHelper]; - Bid.NotificationsTrace(" %d#, hashtable hit, container: %d\n", ObjectID, container.ObjectID); + SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}\n"); server = container.Server; // Return server, database, and queue info for use by calling SqlDependency. database = container.Database; queueService = container.Queue; @@ -1865,16 +1849,16 @@ internal bool Stop(string connectionString, } else { - Bid.NotificationsTrace(" %d#, hashtable miss.\n", ObjectID); + SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, hashtable miss.\n"); } } - Bid.NotificationsTrace(" %d#, stopped: %d\n", ObjectID, stopped); + SqlClientEventSource._log.NotificationsTrace($" %d#, stopped: {stopped}\n"); return stopped; } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs index d7d21960d3..c828314245 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs @@ -92,8 +92,7 @@ internal int ObjectID private SqlDependencyPerAppDomainDispatcher() { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { _dependencyIdToDependencyHash = new Dictionary(); @@ -107,7 +106,7 @@ private SqlDependencyPerAppDomainDispatcher() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -125,8 +124,7 @@ public override object InitializeLifetimeService() private void UnloadEventHandler(object sender, EventArgs e) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); try { // Make non-blocking call to ProcessDispatcher to ThreadPool.QueueUserWorkItem to complete @@ -141,7 +139,7 @@ private void UnloadEventHandler(object sender, EventArgs e) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -152,8 +150,7 @@ private void UnloadEventHandler(object sender, EventArgs e) // This method is called upon SqlDependency constructor. internal void AddDependencyEntry(SqlDependency dep) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, SqlDependency: %d#", ObjectID, dep.ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); try { lock (this) @@ -163,24 +160,23 @@ internal void AddDependencyEntry(SqlDependency dep) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } // This method is called upon Execute of a command associated with a SqlDependency object. internal string AddCommandEntry(string commandHash, SqlDependency dep) { - IntPtr hscp; string notificationId = string.Empty; - Bid.NotificationsScopeEnter(out hscp, " %d#, commandHash: '%ls', SqlDependency: %d#", ObjectID, commandHash, dep.ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{commandHash}', SqlDependency: {dep.ObjectID}#"); try { lock (this) { if (!_dependencyIdToDependencyHash.ContainsKey(dep.Id)) { // Determine if depId->dep hashtable contains dependency. If not, it's been invalidated. - Bid.NotificationsTrace(" Dependency not present in depId->dep hash, must have been invalidated.\n"); + SqlClientEventSource._log.NotificationsTrace($" Dependency not present in depId->dep hash, must have been invalidated.\n"); } else { @@ -201,12 +197,12 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // join the new dependency to the list if (!dependencyList.Contains(dep)) { - Bid.NotificationsTrace(" Dependency not present for commandHash, adding.\n"); + SqlClientEventSource._log.NotificationsTrace($" Dependency not present for commandHash, adding.\n"); dependencyList.Add(dep); } else { - Bid.NotificationsTrace(" Dependency already present for commandHash.\n"); + SqlClientEventSource._log.NotificationsTrace($" Dependency already present for commandHash.\n"); } } else @@ -221,7 +217,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) Guid.NewGuid().ToString("D", System.Globalization.CultureInfo.InvariantCulture) ); - Bid.NotificationsTrace(" Creating new Dependencies list for commandHash.\n"); + SqlClientEventSource._log.NotificationsTrace($" Creating new Dependencies list for commandHash.\n"); DependencyList dependencyList = new DependencyList(commandHash); dependencyList.Add(dep); @@ -243,7 +239,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } return notificationId; @@ -252,8 +248,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // This method is called by the ProcessDispatcher upon a notification for this AppDomain. internal void InvalidateCommandID(SqlNotification sqlNotification) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, commandHash: '%ls'", ObjectID, sqlNotification.Key); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{sqlNotification.Key}'"); try { List dependencyList = null; @@ -264,7 +259,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) if (null != dependencyList) { - Bid.NotificationsTrace(" commandHash found in hashtable.\n"); + SqlClientEventSource._log.NotificationsTrace($" commandHash found in hashtable.\n"); foreach (SqlDependency dependency in dependencyList) { @@ -277,7 +272,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } else { - Bid.NotificationsTrace(" commandHash NOT found in hashtable.\n"); + SqlClientEventSource._log.NotificationsTrace($" commandHash NOT found in hashtable.\n"); } } @@ -286,7 +281,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) // After removal from hashtables, invalidate. foreach (SqlDependency dependency in dependencyList) { - Bid.NotificationsTrace(" Dependency found in commandHash dependency ArrayList - calling invalidate.\n"); + SqlClientEventSource._log.NotificationsTrace($" Dependency found in commandHash dependency ArrayList - calling invalidate.\n"); try { @@ -308,15 +303,14 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } // This method is called when a connection goes down or other unknown error occurs in the ProcessDispatcher. internal void InvalidateServer(string server, SqlNotification sqlNotification) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, server: '%ls'", ObjectID, server); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); try { List dependencies = new List(); @@ -363,15 +357,14 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } // This method is called by SqlCommand to enable ASP.NET scenarios - map from ID to Dependency. internal SqlDependency LookupDependencyEntry(string id) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, Key: '%ls'", ObjectID, id); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, Key: '{id}'"); try { if (null == id) @@ -393,7 +386,7 @@ internal SqlDependency LookupDependencyEntry(string id) } else { - Bid.NotificationsTrace(" ERROR - dependency ID mismatch - not throwing.\n"); + SqlClientEventSource._log.NotificationsTrace($" ERROR - dependency ID mismatch - not throwing.\n"); } } @@ -401,22 +394,21 @@ internal SqlDependency LookupDependencyEntry(string id) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } // Remove the dependency from the hashtable with the passed id. private void LookupDependencyEntryWithRemove(string id) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, id: '%ls'", ObjectID, id); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, id: '{id}'"); try { lock (this) { if (_dependencyIdToDependencyHash.ContainsKey(id)) { - Bid.NotificationsTrace(" Entry found in hashtable - removing.\n"); + SqlClientEventSource._log.NotificationsTrace($" Entry found in hashtable - removing.\n"); _dependencyIdToDependencyHash.Remove(id); // if there are no more dependencies then we can dispose the timer. @@ -428,21 +420,20 @@ private void LookupDependencyEntryWithRemove(string id) } else { - Bid.NotificationsTrace(" Entry NOT found in hashtable.\n"); + SqlClientEventSource._log.NotificationsTrace($" Entry NOT found in hashtable.\n"); } } } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } // Find and return arraylist, and remove passed hash value. private List LookupCommandEntryWithRemove(string notificationId) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, commandHash: '%ls'", ObjectID, notificationId); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{notificationId}'"); try { DependencyList entry = null; @@ -451,7 +442,7 @@ private List LookupCommandEntryWithRemove(string notificationId) { if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry)) { - Bid.NotificationsTrace(" Entries found in hashtable - removing.\n"); + SqlClientEventSource._log.NotificationsTrace($" Entries found in hashtable - removing.\n"); // update the tables - do it inside finally block to avoid ThreadAbort exception interrupt this operation try @@ -465,7 +456,7 @@ private List LookupCommandEntryWithRemove(string notificationId) } else { - Bid.NotificationsTrace(" Entries NOT found in hashtable.\n"); + SqlClientEventSource._log.NotificationsTrace($" Entries NOT found in hashtable.\n"); } Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!"); @@ -475,15 +466,14 @@ private List LookupCommandEntryWithRemove(string notificationId) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } // Remove from commandToDependenciesHash all references to the passed dependency. private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency dependency) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, SqlDependency: %d#", ObjectID, dependency.ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dependency.ObjectID}#"); try { lock (this) @@ -496,7 +486,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende DependencyList dependencies = entry.Value; if (dependencies.Remove(dependency)) { - Bid.NotificationsTrace(" Removed SqlDependency: %d#, with ID: '%ls'.\n", dependency.ObjectID, dependency.Id); + SqlClientEventSource._log.NotificationsTrace($" Removed SqlDependency: {dependency.ObjectID}#, with ID: '{dependency.Id}'.\n"); if (dependencies.Count == 0) { // this dependency was the last associated with this notification ID, remove the entry @@ -529,7 +519,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -539,8 +529,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende internal void StartTimer(SqlDependency dep) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, SqlDependency: %d#", ObjectID, dep.ObjectID); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); try { // If this dependency expires sooner than the current next timeout, change @@ -551,7 +540,7 @@ internal void StartTimer(SqlDependency dep) // Enable the timer if needed (disable when empty, enable on the first addition). if (!_SqlDependencyTimeOutTimerStarted) { - Bid.NotificationsTrace(" Timer not yet started, starting.\n"); + SqlClientEventSource._log.NotificationsTrace($" Timer not yet started, starting.\n"); _timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */); @@ -561,7 +550,7 @@ internal void StartTimer(SqlDependency dep) } else if (_nextTimeout > dep.ExpirationTime) { - Bid.NotificationsTrace(" Timer already started, resetting time.\n"); + SqlClientEventSource._log.NotificationsTrace($" Timer already started, resetting time.\n"); // Save this as the earlier timeout to come. _nextTimeout = dep.ExpirationTime; @@ -570,14 +559,13 @@ internal void StartTimer(SqlDependency dep) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } private static void TimeoutTimerCallback(object state) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " AppDomainKey: '%ls'", SqlDependency.AppDomainKey); + var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" AppDomainKey: '{SqlDependency.AppDomainKey}'"); try { SqlDependency[] dependencies; @@ -590,12 +578,12 @@ private static void TimeoutTimerCallback(object state) if (0 == SingletonInstance._dependencyIdToDependencyHash.Count) { // Nothing to check. - Bid.NotificationsTrace(" No dependencies, exiting.\n"); + SqlClientEventSource._log.NotificationsTrace($" No dependencies, exiting.\n"); return; } if (SingletonInstance._nextTimeout > DateTime.UtcNow) { - Bid.NotificationsTrace(" No timeouts expired, exiting.\n"); + SqlClientEventSource._log.NotificationsTrace($" No timeouts expired, exiting.\n"); // No dependency timed-out yet. return; } @@ -665,7 +653,7 @@ private static void TimeoutTimerCallback(object state) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs index 7033d7f5d4..5dd27c71b6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs @@ -41,9 +41,7 @@ internal SqlError(int infoNumber, byte errorState, byte errorClass, string serve this.lineNumber = lineNumber; if (errorClass != 0) { - Bid.Trace(" infoNumber=%d, errorState=%d, errorClass=%d, errorMessage='%ls', procedure='%ls', lineNumber=%d\n", - infoNumber, (int)errorState, (int)errorClass, errorMessage, - procedure == null ? "None" : procedure, (int)lineNumber); + SqlClientEventSource._log.Trace($" infoNumber={infoNumber}, errorState={(int)errorState}, errorClass={(int)errorClass}, errorMessage='{errorMessage}', procedure='{procedure ?? "None"}', lineNumber={(int)lineNumber}\n"); } this.win32ErrorCode = 0; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index 0ac838bab2..bfa9fb9609 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -223,7 +223,8 @@ virtual internal SqlTransaction BeginSqlTransaction(IsolationLevel iso, string t TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -250,7 +251,8 @@ virtual internal SqlTransaction BeginSqlTransaction(IsolationLevel iso, string t return transaction; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -311,10 +313,7 @@ override protected DbReferenceCollection CreateReferenceCollection() override protected void Deactivate() { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# deactivating\n", base.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}# deactivating\n"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -324,7 +323,8 @@ override protected void Deactivate() TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -340,7 +340,8 @@ override protected void Deactivate() InternalDeactivate(); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -435,19 +436,13 @@ private void EnlistNonNull(SysTx.Transaction tx) { Debug.Assert(null != tx, "null transaction?"); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transaction %d#.\n", base.ObjectID, tx.GetHashCode()); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, transaction {tx.GetHashCode()}#.\n"); bool hasDelegatedTransaction = false; if (IsYukonOrNewer) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, attempting to delegate\n", base.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, attempting to delegate\n"); // Promotable transactions are only supported on Yukon // servers or newer. @@ -516,17 +511,14 @@ private void EnlistNonNull(SysTx.Transaction tx) this.DelegatedTransaction = delegatedTransaction; - if (Bid.AdvancedOn) + long transactionId = SqlInternalTransaction.NullTransactionId; + int transactionObjectID = 0; + if (null != CurrentTransaction) { - long transactionId = SqlInternalTransaction.NullTransactionId; - int transactionObjectID = 0; - if (null != CurrentTransaction) - { - transactionId = CurrentTransaction.TransactionId; - transactionObjectID = CurrentTransaction.ObjectID; - } - Bid.Trace(" %d#, delegated to transaction %d# with transactionId=0x%I64x\n", base.ObjectID, transactionObjectID, transactionId); + transactionId = CurrentTransaction.TransactionId; + transactionObjectID = CurrentTransaction.ObjectID; } + SqlClientEventSource._log.Trace($" {ObjectID}#, delegated to transaction {transactionObjectID}# with transactionId=0x{transactionId}\n"); } } catch (SqlException e) @@ -559,10 +551,7 @@ private void EnlistNonNull(SysTx.Transaction tx) if (!hasDelegatedTransaction) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, delegation not possible, enlisting.\n", base.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, delegation not possible, enlisting.\n"); byte[] cookie = null; @@ -595,17 +584,14 @@ private void EnlistNonNull(SysTx.Transaction tx) _isEnlistedInTransaction = true; - if (Bid.AdvancedOn) + long transactionId = SqlInternalTransaction.NullTransactionId; + int transactionObjectID = 0; + if (null != CurrentTransaction) { - long transactionId = SqlInternalTransaction.NullTransactionId; - int transactionObjectID = 0; - if (null != CurrentTransaction) - { - transactionId = CurrentTransaction.TransactionId; - transactionObjectID = CurrentTransaction.ObjectID; - } - Bid.Trace(" %d#, enlisted with transaction %d# with transactionId=0x%I64x\n", base.ObjectID, transactionObjectID, transactionId); + transactionId = CurrentTransaction.TransactionId; + transactionObjectID = CurrentTransaction.ObjectID; } + SqlClientEventSource._log.Trace($" {ObjectID}#, enlisted with transaction {transactionObjectID}# with transactionId=0x{transactionId}\n"); } EnlistedTransaction = tx; // Tell the base class about our enlistment @@ -629,10 +615,7 @@ private void EnlistNonNull(SysTx.Transaction tx) internal void EnlistNull() { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, unenlisting.\n", base.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, unenlisting.\n"); // We were in a transaction, but now we are not - so send // message to server with empty transaction - confirmed proper @@ -651,10 +634,7 @@ internal void EnlistNull() _isEnlistedInTransaction = false; EnlistedTransaction = null; // Tell the base class about our enlistment - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, unenlisted.\n", base.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, unenlisted.\n"); // The EnlistTransaction above will return an TransactionEnded event, // which causes the TdsParser or SmiEventSink should to clear the @@ -704,7 +684,8 @@ override public void EnlistTransaction(SysTx.Transaction transaction) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -713,7 +694,8 @@ override public void EnlistTransaction(SysTx.Transaction transaction) Enlist(transaction); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs index 3e37be43a9..bbb6934911 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs @@ -66,55 +66,37 @@ internal EventSink(SqlInternalConnectionSmi connection) internal override void DefaultDatabaseChanged(string databaseName) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, databaseName='%ls'.\n", _connection.ObjectID, databaseName); - } + SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, databaseName='{databaseName}'.\n"); _connection.CurrentDatabase = databaseName; } internal override void TransactionCommitted(long transactionId) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transactionId=0x%I64x.\n", _connection.ObjectID, transactionId); - } + SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}.\n"); _connection.TransactionEnded(transactionId, TransactionState.Committed); } internal override void TransactionDefected(long transactionId) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transactionId=0x%I64x.\n", _connection.ObjectID, transactionId); - } + SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}.\n"); _connection.TransactionEnded(transactionId, TransactionState.Unknown); } internal override void TransactionEnlisted(long transactionId) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transactionId=0x%I64x.\n", _connection.ObjectID, transactionId); - } + SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}.\n"); _connection.TransactionStarted(transactionId, true); // distributed; } internal override void TransactionEnded(long transactionId) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transactionId=0x%I64x.\n", _connection.ObjectID, transactionId); - } + SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}.\n"); _connection.TransactionEndedByServer(transactionId, TransactionState.Unknown); } internal override void TransactionRolledBack(long transactionId) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transactionId=0x%I64x.\n", _connection.ObjectID, transactionId); - } + SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}.\n"); // Dev11 1066: ensure delegated transaction is rolled back _connection.TransactionEndedByServer(transactionId, TransactionState.Aborted); @@ -122,10 +104,7 @@ internal override void TransactionRolledBack(long transactionId) internal override void TransactionStarted(long transactionId) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transactionId=0x%I64x.\n", _connection.ObjectID, transactionId); - } + SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}.\n"); _connection.TransactionStarted(transactionId, false); // not distributed; } } @@ -142,10 +121,7 @@ internal SqlInternalConnectionSmi(SqlConnectionString connectionOptions, SmiCont _smiEventSink = new EventSink(this); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, constructed new SMI internal connection\n", ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, constructed new SMI internal connection\n"); } internal SmiContext InternalContext @@ -295,15 +271,10 @@ internal void AutomaticEnlistment() SysTx.Transaction currentSystemTransaction = ADP.GetCurrentTransaction(); // NOTE: Must be first to ensure _smiContext.ContextTransaction is set! SysTx.Transaction contextTransaction = _smiContext.ContextTransaction; // returns the transaction that was handed to SysTx that wraps the ContextTransactionId. long contextTransactionId = _smiContext.ContextTransactionId; + var contextTransactionValue = (null != contextTransaction) ? contextTransaction.GetHashCode() : 0; + var currentSystemTransactionValue = (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0; - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, contextTransactionId=0x%I64x, contextTransaction=%d#, currentSystemTransaction=%d#.\n", - base.ObjectID, - contextTransactionId, - (null != contextTransaction) ? contextTransaction.GetHashCode() : 0, - (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, contextTransactionId=0x{contextTransactionId}, contextTransaction={contextTransactionValue}#, currentSystemTransaction={currentSystemTransactionValue}#.\n"); if (SqlInternalTransaction.NullTransactionId != contextTransactionId) { @@ -311,10 +282,7 @@ internal void AutomaticEnlistment() { throw SQL.NestedTransactionScopesNotSupported(); // can't use TransactionScope(RequiresNew) inside a Sql Transaction. } - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, using context transaction with transactionId=0x%I64x\n", base.ObjectID, contextTransactionId); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, using context transaction with transactionId=0x{contextTransactionId}\n"); _currentTransaction = new SqlInternalTransaction(this, TransactionType.Context, null, contextTransactionId); ContextTransaction = contextTransaction; } @@ -322,17 +290,11 @@ internal void AutomaticEnlistment() { _currentTransaction = null; // there really isn't a transaction. - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, no transaction.\n", base.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, no transaction.\n"); } else { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, using current System.Transaction.\n", base.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, using current System.Transaction.\n"); base.Enlist(currentSystemTransaction); } } @@ -345,10 +307,7 @@ override protected void ChangeDatabaseInternal(string database) override protected void InternalDeactivate() { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Deactivating.\n", base.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, Deactivating.\n"); // When we put this to bed, we should not hold on to the transaction // or any activity (commit/rollback) may cause it to stop responding. @@ -378,20 +337,14 @@ override internal void DelegatedTransactionEnded() { base.DelegatedTransactionEnded(); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, cleaning up after Delegated Transaction Completion\n", base.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, cleaning up after Delegated Transaction Completion\n"); _currentTransaction = null; // clean up our current transaction too } override internal void DisconnectTransaction(SqlInternalTransaction internalTransaction) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Disconnecting Transaction %d#.\n", base.ObjectID, internalTransaction.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, Disconnecting Transaction {internalTransaction.ObjectID}#.\n"); // VSTS 215465/15029: allow _currentTransaction to be null - it can be cleared before by server's callback Debug.Assert(_currentTransaction == null || _currentTransaction == internalTransaction, "disconnecting different transaction"); @@ -415,17 +368,12 @@ override internal void ExecuteTransaction( SqlInternalTransaction internalTransaction, bool isDelegateControlRequest) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transactionRequest=%ls, transactionName='%ls', isolationLevel=%ls, internalTransaction=#%d transactionId=0x%I64x.\n", - base.ObjectID, - transactionRequest.ToString(), - (null != transactionName) ? transactionName : "null", - iso.ToString(), - (null != internalTransaction) ? internalTransaction.ObjectID : 0, - (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId - ); - } + var transactionNameValue = (null != transactionName) ? transactionName : "null"; + var internalTransactionValue = (null != internalTransaction) ? internalTransaction.ObjectID : 0; + var internalTransactionIdValue = (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId; + + SqlClientEventSource._log.Trace($" {ObjectID}#, transactionRequest={transactionRequest.ToString()}, transactionName='{transactionNameValue}', isolationLevel={iso.ToString()}, internalTransaction=#{internalTransactionIdValue} transactionId=0x{internalTransactionIdValue}.\n"); + switch (transactionRequest) { case TransactionRequest.Begin: @@ -479,16 +427,13 @@ override protected byte[] GetDTCAddress() _smiEventSink.ProcessMessagesAndThrow(); - if (Bid.AdvancedOn) + if (null != whereAbouts) { - if (null != whereAbouts) - { - Bid.TraceBin(" whereAbouts", whereAbouts, (UInt16)whereAbouts.Length); - } - else - { - Bid.Trace(" whereAbouts=null\n"); - } + SqlClientEventSource._log.TraceBin($" whereAbouts", whereAbouts, (UInt16)whereAbouts.Length); + } + else + { + SqlClientEventSource._log.Trace($" whereAbouts=null\n"); } return whereAbouts; } @@ -513,10 +458,7 @@ private void OnOutOfScope(object s, EventArgs e) // Called whenever the context goes out of scope, we need to make // sure that we close the connection, or the next person that uses // the context may appear to have the connection in use. - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# context is out of scope\n", base.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}# context is out of scope\n"); // TODO: This is suspect to me -- if I go out of scope, who will commit the transaction? DelegatedTransaction = null; // we don't want to hold this over to the next usage; it will automatically be reused as the context transaction... @@ -544,16 +486,13 @@ private void OnOutOfScope(object s, EventArgs e) override protected void PropagateTransactionCookie(byte[] transactionCookie) { - if (Bid.AdvancedOn) + if (null != transactionCookie) { - if (null != transactionCookie) - { - Bid.TraceBin(" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); - } - else - { - Bid.Trace(" null\n"); - } + SqlClientEventSource._log.TraceBin($" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); + } + else + { + SqlClientEventSource._log.Trace($" null\n"); } // Propagate the transaction cookie to the server @@ -587,7 +526,8 @@ private void TransactionEnded(long transactionId, TransactionState transactionSt { #if DEBUG // Check null for case where Begin and Rollback obtained in the same message. - if (0 != _currentTransaction.TransactionId) { + if (0 != _currentTransaction.TransactionId) + { Debug.Assert(_currentTransaction.TransactionId == transactionId, "transaction id's are not equal!"); } #endif diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs index f6f5775955..bead8c2950 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs @@ -368,19 +368,24 @@ internal SqlInternalConnectionTds( { #if DEBUG - if (reconnectSessionData != null) { + if (reconnectSessionData != null) + { reconnectSessionData._debugReconnectDataApplied = true; } - try { // use this to help validate this object is only created after the following permission has been previously demanded in the current codepath - if (userConnectionOptions != null) { + try + { // use this to help validate this object is only created after the following permission has been previously demanded in the current codepath + if (userConnectionOptions != null) + { // As mentioned above, userConnectionOptions may be different to connectionOptions, so we need to demand on the correct connection string userConnectionOptions.DemandPermission(); } - else { + else + { connectionOptions.DemandPermission(); } } - catch(System.Security.SecurityException) { + catch (System.Security.SecurityException) + { System.Diagnostics.Debug.Assert(false, "unexpected SecurityException for current codepath"); throw; } @@ -448,7 +453,8 @@ internal SqlInternalConnectionTds( TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -483,7 +489,8 @@ internal SqlInternalConnectionTds( } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -508,10 +515,8 @@ internal SqlInternalConnectionTds( ThreadHasParserLockForClose = false; _parserLock.Release(); } - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, constructed new TDS internal connection\n", ObjectID); - } + + SqlClientEventSource._log.Trace($" {ObjectID}#, constructed new TDS internal connection\n"); } // The erros in the transient error set are contained in @@ -766,10 +771,7 @@ override protected void ChangeDatabaseInternal(string database) override public void Dispose() { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# disposing\n", base.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}# disposing\n"); try { TdsParser parser = Interlocked.Exchange(ref _parser, null); // guard against multiple concurrent dispose calls -- Delegated Transactions might cause this. @@ -903,7 +905,7 @@ internal override bool IsConnectionAlive(bool throwOnException) tdsReliabilitySection.Start(); #endif //DEBUG - isAlive = _parser._physicalStateObj.IsConnectionAlive(throwOnException); + isAlive = _parser._physicalStateObj.IsConnectionAlive(throwOnException); #if DEBUG } @@ -1360,12 +1362,12 @@ private void CompleteLogin(bool enlistOK) { // ROR should not affect state of connection recovery if (_federatedAuthenticationRequested && !_federatedAuthenticationAcknowledged) { - Bid.Trace(" %d#, Server did not acknowledge the federated authentication request\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Server did not acknowledge the federated authentication request\n"); throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged); } if (_federatedAuthenticationInfoRequested && !_federatedAuthenticationInfoReceived) { - Bid.Trace(" %d#, Server never sent the requested federated authentication info\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Server never sent the requested federated authentication info\n"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoNotReceived); } @@ -1404,10 +1406,7 @@ private void CompleteLogin(bool enlistOK) _fConnectionOpen = true; // mark connection as open - if (Bid.AdvancedOn) - { - Bid.Trace(" Post-Login Phase: Server connection obtained.\n"); - } + SqlClientEventSource._log.Trace($" Post-Login Phase: Server connection obtained.\n"); // for non-pooled connections, enlist in a distributed transaction // if present - and user specified to enlist @@ -1536,7 +1535,7 @@ private void Login(ServerInfo server, TimeoutTimer timeout, string newPassword, private void LoginFailure() { - Bid.Trace(" %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#\n"); // If the parser was allocated and we failed, then we must have failed on // either the Connect or Login, either way we should call Disconnect. @@ -1662,10 +1661,8 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt int routingAttempts = 0; ServerInfo originalServerInfo = serverInfo; // serverInfo may end up pointing to new object due to routing, original object is used to set CurrentDatasource - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, host=%ls\n", ObjectID, serverInfo.UserServerName); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, host={serverInfo.UserServerName}\n"); + int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. ResolveExtendedServerName(serverInfo, !redirectedUserInstance, connectionOptions); @@ -1770,7 +1767,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt if (_routingInfo != null) { - Bid.Trace(" Routed to %ls", serverInfo.ExtendedServerName); + SqlClientEventSource._log.Trace($" Routed to {serverInfo.ExtendedServerName}"); if (routingAttempts > _maxNumberOfRedirectRoute) { @@ -1859,10 +1856,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt // Sleep for a bit to prevent clogging the network with requests, // then update sleep interval for next iteration (max 1 second interval) - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, sleeping %d{milisec}\n", ObjectID, sleepInterval); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]\n"); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } @@ -1944,14 +1938,12 @@ TimeoutTimer timeout Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used"); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, useFailover=%d{bool}, primary=", ObjectID, useFailoverHost); - Bid.PutStr(primaryServerInfo.UserServerName); - Bid.PutStr(", failover="); - Bid.PutStr(failoverHost); - Bid.PutStr("\n"); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, useFailover={useFailoverHost}[bool], primary="); + SqlClientEventSource._log.PutStr(primaryServerInfo.UserServerName); + SqlClientEventSource._log.PutStr(", failover="); + SqlClientEventSource._log.PutStr(failoverHost); + SqlClientEventSource._log.PutStr("\n"); + int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. long timeoutUnitInterval; @@ -2018,10 +2010,7 @@ TimeoutTimer timeout // Primary server may give us a different failover partner than the connection string indicates. Update it if (null != ServerProvidedFailOverPartner && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, new failover partner=%ls\n", ObjectID, ServerProvidedFailOverPartner); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, new failover partner={ServerProvidedFailOverPartner}\n"); failoverServerInfo.SetDerivedNames(protocol, ServerProvidedFailOverPartner); } currentServerInfo = failoverServerInfo; @@ -2054,7 +2043,7 @@ TimeoutTimer timeout } routingAttempts++; - Bid.Trace(" Routed to %ls", _routingInfo.ServerName); + SqlClientEventSource._log.Trace($" Routed to {_routingInfo.ServerName}"); if (_parser != null) _parser.Disconnect(); @@ -2123,10 +2112,8 @@ TimeoutTimer timeout // the network with requests, then update sleep interval for next iteration (max 1 second interval) if (1 == attemptNumber % 2) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, sleeping %d{milisec}\n", ObjectID, sleepInterval); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]\n"); + Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } @@ -2201,12 +2188,9 @@ private void ResolveExtendedServerName(ServerInfo serverInfo, bool aliasLookup, // Common code path for making one attempt to establish a connection and log in to server. private void AttemptOneLogin(ServerInfo serverInfo, string newPassword, SecureString newSecurePassword, bool ignoreSniOpenTimeout, TimeoutTimer timeout, bool withFailover = false, bool isFirstTransparentAttempt = true, bool disableTnir = false) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, timout=%I64d{msec}, server=", ObjectID, timeout.MillisecondsRemaining); - Bid.PutStr(serverInfo.ExtendedServerName); - Bid.Trace("\n"); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, timout={timeout.MillisecondsRemaining}[msec], server="); + SqlClientEventSource._log.PutStr(serverInfo.ExtendedServerName); + SqlClientEventSource._log.Trace("\n"); _routingInfo = null; // forget routing information @@ -2301,24 +2285,26 @@ internal bool GetSessionAndReconnectIfNeeded(SqlConnection parent, int timeout = #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #endif //DEBUG - Task reconnectTask = parent.ValidateAndReconnect(() => - { - ThreadHasParserLockForClose = false; - _parserLock.Release(); - releaseConnectionLock = false; - }, timeout); - if (reconnectTask != null) - { - AsyncHelper.WaitForCompletion(reconnectTask, timeout); - return true; - } - return false; + Task reconnectTask = parent.ValidateAndReconnect(() => + { + ThreadHasParserLockForClose = false; + _parserLock.Release(); + releaseConnectionLock = false; + }, timeout); + if (reconnectTask != null) + { + AsyncHelper.WaitForCompletion(reconnectTask, timeout); + return true; + } + return false; #if DEBUG } - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -2356,7 +2342,7 @@ internal bool GetSessionAndReconnectIfNeeded(SqlConnection parent, int timeout = internal void BreakConnection() { var connection = Connection; - Bid.Trace(" %d#, Breaking connection.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Breaking connection.\n"); DoomThisConnection(); // Mark connection as unusable, so it will be destroyed if (null != connection) { @@ -2447,10 +2433,9 @@ internal void OnEnvChange(SqlEnvChange rec) break; case TdsEnums.ENV_ROUTING: - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Received routing info\n", ObjectID); - } + + SqlClientEventSource._log.Trace($" {ObjectID}#, Received routing info\n"); + if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0) { throw SQL.ROR_InvalidRoutingInfo(this); @@ -2495,7 +2480,7 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) Debug.Assert(fedAuthInfo != null, "info should not be null."); Debug.Assert(_dbConnectionPoolAuthenticationContextKey == null, "_dbConnectionPoolAuthenticationContextKey should be null."); - Bid.Trace(" %d#, Generating federated authentication token\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Generating federated authentication token\n"); DbConnectionPoolAuthenticationContext dbConnectionPoolAuthenticationContext = null; @@ -2527,17 +2512,19 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // And on successful login, try to update the cache with the new token. if (contextValidity <= _dbAuthenticationContextUnLockedRefreshTimeSpan) { - Bid.Trace(" %d#, The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it.The expiration time is %s. Current Time is %s.\n", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + SqlClientEventSource._log.Trace($" {ObjectID}#, The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. Current Time is {DateTime.UtcNow.ToLongTimeString()}.\n"); attemptRefreshTokenUnLocked = true; } #if DEBUG // Checking if any failpoints are enabled. - else if (_forceExpiryUnLocked) { + else if (_forceExpiryUnLocked) + { attemptRefreshTokenUnLocked = true; } - else if (_forceExpiryLocked) { + else if (_forceExpiryLocked) + { attemptRefreshTokenLocked = TryGetFedAuthTokenLocked(fedAuthInfo, dbConnectionPoolAuthenticationContext, out fedAuthToken); } #endif @@ -2546,10 +2533,7 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // If a thread is already doing the refresh, just use the existing token in the cache and proceed. else if (contextValidity <= _dbAuthenticationContextLockedRefreshTimeSpan) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, The authentication context needs a refresh.The expiration time is %s. Current Time is %s.\n", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, The authentication context needs a refresh.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. Current Time is {DateTime.UtcNow.ToLongTimeString()}.\n"); // Call the function which tries to acquire a lock over the authentication context before trying to update. // If the lock could not be obtained, it will return false, without attempting to fetch a new token. @@ -2563,14 +2547,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // Indicate in Bid Trace that we are successful with the update. if (attemptRefreshTokenLocked) { - Bid.Trace(" %d#, The attempt to get a new access token succeeded under the locked mode."); + SqlClientEventSource._log.Trace($" %d#, The attempt to get a new access token succeeded under the locked mode."); } } - else if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.\n", ObjectID); - } + + SqlClientEventSource._log.Trace($" {ObjectID}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.\n"); } } @@ -2630,13 +2612,13 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP // Else some other thread is already updating it, so just proceed forward with the existing token in the cache. if (dbConnectionPoolAuthenticationContext.LockToUpdate()) { - Bid.Trace(" %d#, Acquired the lock to update the authentication context.The expiration time is %s. Current Time is %s.\n", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + SqlClientEventSource._log.Trace($" {ObjectID}#, Acquired the lock to update the authentication context.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. Current Time is {DateTime.UtcNow.ToLongTimeString()}.\n"); authenticationContextLocked = true; } else { - Bid.Trace(" %d#, Refreshing the context is already in progress by another thread.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Refreshing the context is already in progress by another thread.\n"); } if (authenticationContextLocked) @@ -2795,7 +2777,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) || _timeout.MillisecondsRemaining <= sleepInterval) { - Bid.Trace(" %s#\n", msalException.ErrorCode); + SqlClientEventSource._log.Trace($" {msalException.ErrorCode}#\n"); // Error[0] SqlErrorCollection sqlErs = new SqlErrorCollection(); @@ -2814,8 +2796,8 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) throw exc; } - Bid.Trace(" %d#, sleeping %d{Milliseconds}\n", ObjectID, sleepInterval); - Bid.Trace(" %d#, remaining %d{Milliseconds}\n", ObjectID, _timeout.MillisecondsRemaining); + SqlClientEventSource._log.Trace($" {ObjectID}#, sleeping {sleepInterval}[Milliseconds]\n"); + SqlClientEventSource._log.Trace($" {ObjectID}#, remaining {_timeout.MillisecondsRemaining}[Milliseconds]\n"); Thread.Sleep(sleepInterval); sleepInterval *= 2; @@ -2832,7 +2814,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) _newDbConnectionPoolAuthenticationContext = new DbConnectionPoolAuthenticationContext(fedAuthToken.accessToken, expirationTime); } - Bid.Trace(" %d#, Finished generating federated authentication token.\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Finished generating federated authentication token.\n"); return fedAuthToken; } @@ -2855,8 +2837,9 @@ internal void OnFeatureExtAck(int featureId, byte[] data) _sessionRecoveryAcknowledged = true; #if DEBUG - foreach (var s in _currentSessionData._delta) { - Debug.Assert(s==null, "Delta should be null at this point"); + foreach (var s in _currentSessionData._delta) + { + Debug.Assert(s == null, "Delta should be null at this point"); } #endif Debug.Assert(_currentSessionData._unrecoverableStatesCount == 0, "Unrecoverable states count should be 0"); @@ -2895,13 +2878,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_FEDAUTH: { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Received feature extension acknowledgement for federated authentication\n", ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, Received feature extension acknowledgement for federated authentication\n"); + if (!_federatedAuthenticationRequested) { - Bid.Trace(" %d#, Did not request federated authentication\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Did not request federated authentication\n"); throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); } @@ -2914,14 +2895,14 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // The server shouldn't have sent any additional data with the ack (like a nonce) if (data.Length != 0) { - Bid.Trace(" %d#, Federated authentication feature extension ack for MSAL and Security Token includes extra data\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Federated authentication feature extension ack for MSAL and Security Token includes extra data\n"); throw SQL.ParsingError(ParsingErrorState.FedAuthFeatureAckContainsExtraData); } break; default: Debug.Fail("Unknown _fedAuthLibrary type"); - Bid.Trace(" %d#, Attempting to use unknown federated authentication library\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Attempting to use unknown federated authentication library\n"); throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType); } _federatedAuthenticationAcknowledged = true; @@ -2938,11 +2919,13 @@ internal void OnFeatureExtAck(int featureId, byte[] data) Debug.Assert(newAuthenticationContextInCacheAfterAddOrUpdate != null, "newAuthenticationContextInCacheAfterAddOrUpdate should not be null."); #if DEBUG // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. - if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) { - Bid.Trace(" %d#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts. \n", ObjectID); + if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) + { + SqlClientEventSource._log.Trace($" {ObjectID}#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts. \n"); } - else { - Bid.Trace(" %d#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value. \n", ObjectID); + else + { + SqlClientEventSource._log.Trace($" {ObjectID}#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value. \n"); } #endif } @@ -2951,21 +2934,19 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_TCE: { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Received feature extension acknowledgement for TCE\n", ObjectID); - } + + SqlClientEventSource._log.Trace($" {ObjectID}#, Received feature extension acknowledgement for TCE\n"); if (data.Length < 1) { - Bid.Trace(" %d#, Unknown version number for TCE\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Unknown version number for TCE\n"); throw SQL.ParsingError(ParsingErrorState.TceUnknownVersion); } byte supportedTceVersion = data[0]; if (0 == supportedTceVersion || supportedTceVersion > TdsEnums.MAX_SUPPORTED_TCE_VERSION) { - Bid.Trace(" %d#, Invalid version number for TCE\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Invalid version number for TCE\n"); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidVersion, supportedTceVersion); } @@ -2984,14 +2965,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS: { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Received feature extension acknowledgement for GlobalTransactions\n", ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, Received feature extension acknowledgement for GlobalTransactions\n"); if (data.Length < 1) { - Bid.Trace(" %d#, Unknown version number for GlobalTransactions\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Unknown version number for GlobalTransactions\n"); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } @@ -3005,14 +2983,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_AZURESQLSUPPORT: { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Received feature extension acknowledgement for AzureSQLSupport\n", ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, Received feature extension acknowledgement for AzureSQLSupport\n"); if (data.Length < 1) { - Bid.Trace(" %d#, Unknown token for AzureSQLSupport\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Unknown token for AzureSQLSupport\n"); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } @@ -3021,36 +2996,31 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // Bit 0 for RO/FP support if ((data[0] & 1) == 1) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, FailoverPartner enabled with Readonly intent for AzureSQL DB\n", ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, FailoverPartner enabled with Readonly intent for AzureSQL DB\n"); } break; } case TdsEnums.FEATUREEXT_DATACLASSIFICATION: { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Received feature extension acknowledgement for DATACLASSIFICATION\n", ObjectID); - } + + SqlClientEventSource._log.Trace($" {ObjectID}#, Received feature extension acknowledgement for DATACLASSIFICATION\n"); if (data.Length < 1) { - Bid.Trace(" %d#, Unknown token for DATACLASSIFICATION\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION\n"); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte supportedDataClassificationVersion = data[0]; if ((0 == supportedDataClassificationVersion) || (supportedDataClassificationVersion > TdsEnums.MAX_SUPPORTED_DATA_CLASSIFICATION_VERSION)) { - Bid.Trace(" %d#, Invalid version number for DATACLASSIFICATION\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Invalid version number for DATACLASSIFICATION\n"); throw SQL.ParsingErrorValue(ParsingErrorState.DataClassificationInvalidVersion, supportedDataClassificationVersion); } if (data.Length != 2) { - Bid.Trace(" %d#, Unknown token for DATACLASSIFICATION\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION\n"); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte enabled = data[1]; @@ -3060,14 +3030,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_UTF8SUPPORT: { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Received feature extension acknowledgement for UTF8 support\n", ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, Received feature extension acknowledgement for UTF8 support\n"); if (data.Length < 1) { - Bid.Trace(" %d#, Unknown value for UTF8 support\n", ObjectID); + SqlClientEventSource._log.Trace($" {ObjectID}#, Unknown value for UTF8 support\n"); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } break; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlParameter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlParameter.cs index 1648e9f24d..ca62191fb3 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlParameter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlParameter.cs @@ -1615,7 +1615,8 @@ private void GetActualFieldsAndProperties(out List fields, // 2) no ordinals outside continuous range from 0 to fieldcount - 1 are allowed // 3) no duplicate ordinals are allowed // But assert no holes to be sure. - foreach (SmiExtendedMetaData md in fields) { + foreach (SmiExtendedMetaData md in fields) + { Debug.Assert(null != md, "Shouldn't be able to have holes, since original loop algorithm prevents such."); } #endif diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlQueryMetadataCache.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlQueryMetadataCache.cs index 0648ecc1b3..6ff0c975b4 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlQueryMetadataCache.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlQueryMetadataCache.cs @@ -216,7 +216,8 @@ internal void AddQueryMetadata(SqlCommand sqlCommand, bool ignoreQueriesWithRetu try { #if DEBUG - if (_sleepOnTrim) { + if (_sleepOnTrim) + { Thread.Sleep(TimeSpan.FromSeconds(10)); } #endif diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs index 53e195ad77..73abe5368e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -142,10 +142,9 @@ override public void Commit() ZombieCheck(); SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -155,7 +154,8 @@ override public void Commit() TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -168,7 +168,8 @@ override public void Commit() _internalTransaction.Commit(); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -206,7 +207,7 @@ override public void Commit() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -223,7 +224,8 @@ protected override void Dispose(bool disposing) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -235,7 +237,8 @@ protected override void Dispose(bool disposing) } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -266,10 +269,7 @@ override public void Rollback() if (IsYukonPartialZombie) { // Put something in the trace in case a customer has an issue - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# partial zombie no rollback required\n", ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}# partial zombie no rollback required\n"); _internalTransaction = null; // yukon zombification } else @@ -277,9 +277,8 @@ override public void Rollback() ZombieCheck(); SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -289,7 +288,8 @@ override public void Rollback() TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -302,7 +302,8 @@ override public void Rollback() _internalTransaction.Rollback(); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -328,7 +329,7 @@ override public void Rollback() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } } @@ -341,8 +342,8 @@ public void Rollback(string transactionName) ZombieCheck(); SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d# transactionName='%ls'", ObjectID, transactionName); + + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}# transactionName='{transactionName}'"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -352,7 +353,8 @@ public void Rollback(string transactionName) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -365,7 +367,8 @@ public void Rollback(string transactionName) _internalTransaction.Rollback(transactionName); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -391,7 +394,7 @@ public void Rollback(string transactionName) _isFromAPI = false; SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -403,8 +406,8 @@ public void Save(string savePointName) ZombieCheck(); SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d# savePointName='%ls'", ObjectID, savePointName); + + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}# savePointName='{savePointName}'"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -414,7 +417,8 @@ public void Save(string savePointName) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -425,7 +429,8 @@ public void Save(string savePointName) _internalTransaction.Save(savePointName); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -449,7 +454,7 @@ public void Save(string savePointName) finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -465,12 +470,10 @@ internal void Zombie() // Of course, if the connection is aready closed, // then we're free to zombify... SqlInternalConnection internalConnection = (_connection.InnerConnection as SqlInternalConnection); + if (null != internalConnection && internalConnection.IsYukonOrNewer && !_isFromAPI) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# yukon deferred zombie\n", ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}# yukon deferred zombie\n"); } else { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index 1c906042f1..620653c481 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -92,9 +92,11 @@ internal void Start() Debug.Assert(!m_started); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { } - finally { + finally + { ++s_reliabilityCount; m_started = true; } @@ -107,13 +109,16 @@ internal void Stop() #if DEBUG // cannot assert m_started - ThreadAbortException can be raised before Start is called - if (m_started) { + if (m_started) + { Debug.Assert(s_reliabilityCount > 0); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { } - finally { + finally + { --s_reliabilityCount; m_started = false; } @@ -422,12 +427,10 @@ private bool IncludeTraceHeader { get { - return (_isDenali && Bid.TraceOn && Bid.IsOn(ActivityCorrelator.CorrelationTracePoints)); + return (_isDenali); } - } - internal int IncrementNonTransactedOpenResultCount() { // IMPORTANT - this increments the connection wide open result count for all @@ -499,26 +502,26 @@ internal void Connect(ServerInfo serverInfo, LoadSSPILibrary(); // now allocate proper length of buffer _sniSpnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength]; - Bid.Trace(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication\n"); + SqlClientEventSource._log.Trace($" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication\n"); } else { _sniSpnBuffer = null; if (authType == SqlAuthenticationMethod.ActiveDirectoryPassword) { - Bid.Trace(" Active Directory Password authentication\n"); + SqlClientEventSource._log.Trace($" Active Directory Password authentication\n"); } else if (authType == SqlAuthenticationMethod.SqlPassword) { - Bid.Trace(" SQL Password authentication\n"); + SqlClientEventSource._log.Trace($" SQL Password authentication\n"); } else if (authType == SqlAuthenticationMethod.ActiveDirectoryInteractive) { - Bid.Trace(" Active Directory Interactive authentication\n"); + SqlClientEventSource._log.Trace($" Active Directory Interactive authentication\n"); } else { - Bid.Trace(" SQL authentication\n"); + SqlClientEventSource._log.Trace($" SQL authentication\n"); } } @@ -555,7 +558,7 @@ internal void Connect(ServerInfo serverInfo, // don't, the memory for the connection object might not be accurate and thus // a bad error could be returned (as it was when it was freed to early for me). _physicalStateObj.Dispose(); - Bid.Trace(" Login failure\n"); + SqlClientEventSource._log.Trace($" Login failure\n"); ThrowExceptionAndWarning(_physicalStateObj); Debug.Fail("SNI returned status != success, but no error thrown?"); } @@ -585,7 +588,7 @@ internal void Connect(ServerInfo serverInfo, Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); // UNDONE - send "" for instance now, need to fix later - Bid.Trace(" Sending prelogin handshake\n"); + SqlClientEventSource._log.Trace($" Sending prelogin handshake\n"); SendPreLoginHandshake(instanceName, encrypt, !string.IsNullOrEmpty(certificate), useOriginalAddressInfo); _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake); @@ -593,13 +596,13 @@ internal void Connect(ServerInfo serverInfo, _physicalStateObj.SniContext = SniContext.Snix_PreLogin; - Bid.Trace(" Consuming prelogin handshake\n"); + SqlClientEventSource._log.Trace($" Consuming prelogin handshake\n"); PreLoginHandshakeStatus status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, out marsCapable, out _connHandler._fedAuthRequired); if (status == PreLoginHandshakeStatus.InstanceFailure) { - Bid.Trace(" Prelogin handshake unsuccessful. Reattempting prelogin handshake\n"); + SqlClientEventSource._log.Trace($" Prelogin handshake unsuccessful. Reattempting prelogin handshake\n"); _physicalStateObj.Dispose(); // Close previous connection // On Instance failure re-connect and flush SNI named instance cache. @@ -609,14 +612,14 @@ internal void Connect(ServerInfo serverInfo, if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); - Bid.Trace(" Login failure\n"); + SqlClientEventSource._log.Trace($" Login failure\n"); ThrowExceptionAndWarning(_physicalStateObj); } UInt32 retCode = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId); Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); - Bid.Trace(" Sending prelogin handshake\n"); + SqlClientEventSource._log.Trace($" Sending prelogin handshake\n"); SendPreLoginHandshake(instanceName, encrypt, !string.IsNullOrEmpty(certificate), useOriginalAddressInfo); status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, out marsCapable, out _connHandler._fedAuthRequired); @@ -625,11 +628,11 @@ internal void Connect(ServerInfo serverInfo, // one pre-login packet and know we are connecting to Shiloh. if (status == PreLoginHandshakeStatus.InstanceFailure) { - Bid.Trace(" Prelogin handshake unsuccessful. Login failure\n"); + SqlClientEventSource._log.Trace($" Prelogin handshake unsuccessful. Login failure\n"); throw SQL.InstanceFailure(); } } - Bid.Trace(" Prelogin handshake successful\n"); + SqlClientEventSource._log.Trace($" Prelogin handshake successful\n"); if (_fMARS && marsCapable) { @@ -721,10 +724,9 @@ internal void EnableMars() internal TdsParserStateObject CreateSession() { TdsParserStateObject session = new TdsParserStateObject(this, (SNIHandle)_pMarsPhysicalConObj.Handle, true); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# created session %d\n", ObjectID, session.ObjectID); - } + + SqlClientEventSource._log.Trace($" {ObjectID}# created session {session.ObjectID}\n"); + return session; } @@ -739,18 +741,14 @@ internal TdsParserStateObject GetSession(object owner) session = _sessionPool.GetSession(owner); Debug.Assert(!session._pendingData, "pending data on a pooled MARS session"); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# getting session %d from pool\n", ObjectID, session.ObjectID); - } + + SqlClientEventSource._log.Trace($" {ObjectID}# getting session {session.ObjectID} from pool\n"); } else { session = _physicalStateObj; - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# getting physical session %d\n", ObjectID, session.ObjectID); - } + + SqlClientEventSource._log.Trace($" {ObjectID}# getting physical session {session.ObjectID}\n"); } Debug.Assert(session._outputPacketNumber == 1, "The packet number is expected to be 1"); return session; @@ -964,7 +962,7 @@ private void SendPreLoginHandshake(byte[] instanceName, bool encrypt, bool clien int actIdSize = GUID_SIZE + sizeof(UInt32); offset += actIdSize; optionDataSize += actIdSize; - Bid.Trace(" ClientConnectionID %ls, ActivityID %ls\n", _connHandler._clientConnectionId.ToString(), actId.ToString()); + SqlClientEventSource._log.Trace($" ClientConnectionID {_connHandler._clientConnectionId.ToString()}, ActivityID {actId.ToString()}\n"); break; case (int)PreLoginOptions.FEDAUTHREQUIRED: @@ -1275,7 +1273,7 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod // Only 0x00 and 0x01 are accepted values from the server. if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01) { - Bid.Trace(" %d#, Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was %d.\n", ObjectID, (int)payload[payloadOffset]); + SqlClientEventSource._log.Trace($" {ObjectID}#, Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {(int)payload[payloadOffset]}.\n"); throw SQL.ParsingErrorValue(ParsingErrorState.FedAuthRequiredPreLoginResponseInvalidValue, (int)payload[payloadOffset]); } @@ -1316,15 +1314,9 @@ internal void Deactivate(bool connectionIsDoomed) { // Called when the connection that owns us is deactivated. - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# deactivating\n", ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}# deactivating\n"); - if (Bid.IsOn(Bid.ApiGroup.StateDump)) - { - Bid.Trace(" %d#, %ls\n", ObjectID, TraceString()); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, {TraceString()}\n"); if (MARSOn) { @@ -1480,7 +1472,7 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle Debug.Assert(temp.Count > 0, "TdsParser::ThrowExceptionAndWarning called with no exceptions or warnings!"); if (temp.Count == 0) { - Bid.Trace(" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {ObjectID}#\n"); } Debug.Assert(_connHandler != null, "TdsParser::ThrowExceptionAndWarning called with null connectionHandler!"); @@ -1586,7 +1578,7 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) { #if DEBUG // There is an exception here for MARS as its possible that another thread has closed the connection just as we see an error - Debug.Assert(SniContext.Undefined!=stateObj.DebugOnlyCopyOfSniContext || ((_fMARS) && ((_state == TdsParserState.Closed) || (_state == TdsParserState.Broken))), "SniContext must not be None"); + Debug.Assert(SniContext.Undefined != stateObj.DebugOnlyCopyOfSniContext || ((_fMARS) && ((_state == TdsParserState.Closed) || (_state == TdsParserState.Broken))), "SniContext must not be None"); #endif SNINativeMethodWrapper.SNI_Error sniError = new SNINativeMethodWrapper.SNI_Error(); SNINativeMethodWrapper.SNIGetLastError(out sniError); @@ -1774,7 +1766,8 @@ internal void CheckResetConnection(TdsParserStateObject stateObj) } } #if DEBUG - else { + else + { Debug.Assert(!_fResetConnection || (_fResetConnection && stateObj._fResetConnectionSent && stateObj._fResetEventOwned), "Unexpected state on else ResetConnection block in WritePacket"); @@ -2048,13 +2041,15 @@ internal bool RunReliably(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDat #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #endif //DEBUG - return Run(runBehavior, cmdHandler, dataStream, bulkCopyHandler, stateObj); + return Run(runBehavior, cmdHandler, dataStream, bulkCopyHandler, stateObj); #if DEBUG } - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -2197,7 +2192,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead Debug.Fail($"unexpected token; token = {token,-2:X2}"); _state = TdsParserState.Broken; _connHandler.BreakConnection(); - Bid.Trace(" Potential multi-threaded misuse of connection, unexpected TDS token found %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" Potential multi-threaded misuse of connection, unexpected TDS token found {ObjectID}#\n"); throw SQL.ParsingErrorToken(ParsingErrorState.InvalidTdsTokenReceived, token); // MDAC 82443 } @@ -2478,10 +2473,11 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead if (null != _currentTransaction) { #if DEBUG - // Check null for case where Begin and Rollback obtained in the same message. - if (SqlInternalTransaction.NullTransactionId != _currentTransaction.TransactionId) { - Debug.Assert(_currentTransaction.TransactionId != env[ii].newLongValue, "transaction id's are not equal!"); - } + // Check null for case where Begin and Rollback obtained in the same message. + if (SqlInternalTransaction.NullTransactionId != _currentTransaction.TransactionId) + { + Debug.Assert(_currentTransaction.TransactionId != env[ii].newLongValue, "transaction id's are not equal!"); + } #endif if (TdsEnums.ENV_COMMITTRAN == env[ii].type) @@ -2518,7 +2514,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead } case TdsEnums.SQLLOGINACK: { - Bid.Trace(" Received login acknowledgement token\n"); + SqlClientEventSource._log.Trace($" Received login acknowledgement token\n"); SqlLoginAck ack; if (!TryProcessLoginAck(stateObj, out ack)) { @@ -2540,7 +2536,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead { _connHandler._federatedAuthenticationInfoReceived = true; SqlFedAuthInfo info; - Bid.Trace(" Received federated authentication info token\n"); + SqlClientEventSource._log.Trace($" Received federated authentication info token\n"); if (!TryProcessFedAuthInfo(stateObj, tokenLength, out info)) { return false; @@ -2747,9 +2743,11 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead (!stateObj._pendingData && stateObj._attentionSent && !stateObj._attentionReceived)); #if DEBUG - if ((stateObj._pendingData) && (!dataReady)) { + if ((stateObj._pendingData) && (!dataReady)) + { byte token; - if (!stateObj.TryPeekByte(out token)) { + if (!stateObj.TryPeekByte(out token)) + { return false; } Debug.Assert(IsValidTdsToken(token), $"DataReady is false, but next token is not valid: {token,-2:X2}"); @@ -3951,15 +3949,12 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, // Skip reading token length, since it has already been read in caller - if (Bid.AdvancedOn) - { - Bid.Trace(" FEDAUTHINFO token stream length = {0}\n", tokenLen); - } + SqlClientEventSource._log.Trace($" FEDAUTHINFO token stream length = {tokenLen}\n"); if (tokenLen < sizeof(uint)) { // the token must at least contain a DWORD indicating the number of info IDs - Bid.Trace(" FEDAUTHINFO token stream length too short for CountOfInfoIDs.\n"); + SqlClientEventSource._log.Trace($" FEDAUTHINFO token stream length too short for CountOfInfoIDs.\n"); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen); } @@ -3967,15 +3962,12 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, uint optionsCount; if (!stateObj.TryReadUInt32(out optionsCount)) { - Bid.Trace(" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream.\n"); + SqlClientEventSource._log.Trace($" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream.\n"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadCountOfInfoIds); } tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount - if (Bid.AdvancedOn) - { - Bid.Trace(" CountOfInfoIDs = {0}\n", optionsCount.ToString(CultureInfo.InvariantCulture)); - } + SqlClientEventSource._log.Trace($" CountOfInfoIDs = {optionsCount.ToString(CultureInfo.InvariantCulture)}\n"); if (tokenLen > 0) { @@ -3984,14 +3976,11 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, int totalRead = 0; bool successfulRead = stateObj.TryReadByteArray(tokenData, 0, tokenLen, out totalRead); - if (Bid.AdvancedOn) - { - Bid.Trace(" Read rest of FEDAUTHINFO token stream: {0}\n", BitConverter.ToString(tokenData, 0, totalRead)); - } + SqlClientEventSource._log.Trace($" Read rest of FEDAUTHINFO token stream: {BitConverter.ToString(tokenData, 0, totalRead)}\n"); if (!successfulRead || totalRead != tokenLen) { - Bid.Trace(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}\n", tokenLen, totalRead); + SqlClientEventSource._log.Trace($" Failed to read FEDAUTHINFO token stream. Attempted to read {tokenLen} bytes, actually read {totalRead}\n"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadTokenStream); } @@ -4013,10 +4002,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, uint dataLen = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 1))); uint dataOffset = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 5))); - if (Bid.AdvancedOn) - { - Bid.Trace(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}\n", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture)); - } + SqlClientEventSource._log.Trace($" FedAuthInfoOpt: ID={id}, DataLen={dataLen.ToString(CultureInfo.InvariantCulture)}, Offset={dataOffset.ToString(CultureInfo.InvariantCulture)}\n"); // offset is measured from optCount, so subtract to make offset measured // from the beginning of tokenData @@ -4028,7 +4014,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, // if dataOffset points to a region within FedAuthInfoOpt or after the end of the token, throw if (dataOffset < totalOptionsSize || dataOffset >= tokenLen) { - Bid.Trace(" FedAuthInfoDataOffset points to an invalid location.\n"); + SqlClientEventSource._log.Trace($" FedAuthInfoDataOffset points to an invalid location.\n"); throw SQL.ParsingErrorOffset(ParsingErrorState.FedAuthInfoInvalidOffset, unchecked((int)dataOffset)); } @@ -4040,19 +4026,16 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } catch (ArgumentOutOfRangeException e) { - Bid.Trace(" Failed to read FedAuthInfoData.\n"); + SqlClientEventSource._log.Trace($" Failed to read FedAuthInfoData.\n"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadData, e); } catch (ArgumentException e) { - Bid.Trace(" FedAuthInfoData is not in unicode format.\n"); + SqlClientEventSource._log.Trace($" FedAuthInfoData is not in unicode format.\n"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e); } - if (Bid.AdvancedOn) - { - Bid.Trace(" FedAuthInfoData: {0}\n", data); - } + SqlClientEventSource._log.Trace($" FedAuthInfoData: {data}\n"); // store data in tempFedAuthInfo switch ((TdsEnums.FedAuthInfoId)id) @@ -4064,26 +4047,23 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, tempFedAuthInfo.stsurl = data; break; default: - if (Bid.AdvancedOn) - { - Bid.Trace(" Ignoring unknown federated authentication info option: {0}\n", id); - } + SqlClientEventSource._log.Trace($" Ignoring unknown federated authentication info option: {id}\n"); break; } } } else { - Bid.Trace(" FEDAUTHINFO token stream is not long enough to contain the data it claims to.\n"); + SqlClientEventSource._log.Trace($" FEDAUTHINFO token stream is not long enough to contain the data it claims to.\n"); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForData, tokenLen); } - Bid.Trace(" Processed FEDAUTHINFO token stream: {0}\n", tempFedAuthInfo.ToString()); + SqlClientEventSource._log.Trace($" Processed FEDAUTHINFO token stream: {tempFedAuthInfo.ToString()}\n"); if (String.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || String.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) { // We should be receiving both stsurl and spn - Bid.Trace(" FEDAUTHINFO token stream does not contain both STSURL and SPN.\n"); + SqlClientEventSource._log.Trace($" FEDAUTHINFO token stream does not contain both STSURL and SPN.\n"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDoesNotContainStsurlAndSpn); } @@ -4511,7 +4491,7 @@ internal bool TryProcessTceCryptoMetadata(TdsParserStateObject stateObj, // validate the index (ordinal passed) if (index >= cipherTable.Value.Size) { - Bid.Trace(" Incorrect ordinal received %d, max tab size: %d\n", index, cipherTable.Value.Size); + SqlClientEventSource._log.Trace($" Incorrect ordinal received {index}, max tab size: {cipherTable.Value.Size}\n"); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidOrdinalIntoCipherInfoTable, index); } } @@ -4730,7 +4710,8 @@ internal void DrainData(TdsParserStateObject stateObj) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -4802,7 +4783,8 @@ internal void DrainData(TdsParserStateObject stateObj) } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -8776,10 +8758,8 @@ internal void TdsLogin(SqlLogin rec, } WriteInt(log7Flags, _physicalStateObj); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, TDS Login7 flags = %d:\n", ObjectID, log7Flags); - } + + SqlClientEventSource._log.Trace($" {ObjectID}#, TDS Login7 flags = {log7Flags}:\n"); WriteInt(0, _physicalStateObj); // ClientTimeZone is not used WriteInt(0, _physicalStateObj); // LCID is unused by server @@ -8938,7 +8918,7 @@ internal void TdsLogin(SqlLogin rec, }; if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) { - Bid.Trace(" Sending federated authentication feature request\n"); + SqlClientEventSource._log.Trace($" Sending federated authentication feature request\n"); Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null."); WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true); }; @@ -9012,7 +8992,7 @@ internal void SendFedAuthToken(SqlFedAuthToken fedAuthToken) Debug.Assert(fedAuthToken != null, "fedAuthToken cannot be null"); Debug.Assert(fedAuthToken.accessToken != null, "fedAuthToken.accessToken cannot be null"); - Bid.Trace(" Sending federated authentication token\n"); + SqlClientEventSource._log.Trace($" Sending federated authentication token\n"); _physicalStateObj._outputMessageType = TdsEnums.MT_FEDAUTH; @@ -9157,7 +9137,8 @@ internal byte[] GetDTCAddress(int timeout, TdsParserStateObject stateObj) dtcReader.GetBytes(0, 0, dtcAddr, 0, cb); } #if DEBUG - else { + else + { Debug.Fail("unexpected length (> Int32.MaxValue) returned from dtcReader.GetBytes"); // if we hit this case we'll just return a null address so that the user // will get a transcaction enlistment error in the upper layers @@ -9403,10 +9384,7 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) { int old_outputPacketNumber = stateObj._outputPacketNumber; - if (Bid.TraceOn) - { - Bid.Trace(" Exception caught on ExecuteXXX: '%ls' \n", e.ToString()); - } + SqlClientEventSource._log.Trace($" Exception caught on ExecuteXXX: '{e.ToString()}' \n"); if (stateObj.HasOpenResult) { // SQL BU DT 383773 - need to decrement openResultCount if operation failed. @@ -9440,7 +9418,7 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) } } - Bid.Trace(" Exception rethrown. \n"); + SqlClientEventSource._log.Trace($" Exception rethrown. \n"); } internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, bool sync, bool callerHasConnectionLock = false, byte[] enclavePackage = null) @@ -9496,7 +9474,7 @@ internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationReques stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - Bid.Trace(" Potential multi-threaded misuse of connection, non-MARs connection with an open result %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#\n"); } stateObj.SniContext = SniContext.Snix_Execute; @@ -9625,7 +9603,7 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - Bid.Trace(" Potential multi-threaded misuse of connection, non-MARs connection with an open result %d#\n", ObjectID); + SqlClientEventSource._log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#\n"); } stateObj.SniContext = SniContext.Snix_Execute; @@ -10199,9 +10177,10 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo } } #if DEBUG - else { - Debug.Assert(writeParamTask == null, "Should not have a task when executing sync"); - } + else + { + Debug.Assert(writeParamTask == null, "Should not have a task when executing sync"); + } #endif } // parameter for loop @@ -10314,20 +10293,22 @@ private void TdsExecuteRPC_OnFailure(Exception exc, TdsParserStateObject stateOb try { #if DEBUG - TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); + TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); - RuntimeHelpers.PrepareConstrainedRegions(); - try { - tdsReliabilitySection.Start(); + RuntimeHelpers.PrepareConstrainedRegions(); + try + { + tdsReliabilitySection.Start(); #else { #endif //DEBUG FailureCleanup(stateObj, exc); } #if DEBUG - finally { - tdsReliabilitySection.Stop(); - } + finally + { + tdsReliabilitySection.Stop(); + } #endif //DEBUG } catch (System.OutOfMemoryException) @@ -10362,7 +10343,8 @@ private void ExecuteFlushTaskCallback(Task tsk, TdsParserStateObject stateObj, T TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -10370,7 +10352,8 @@ private void ExecuteFlushTaskCallback(Task tsk, TdsParserStateObject stateObj, T FailureCleanup(stateObj, tsk.Exception); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -10483,12 +10466,11 @@ private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefa metaData.SqlDbType, metaData.IsMultiValued, value, null, SmiContextFactory.KatmaiVersion); } - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Sending parameter '%ls', default flag=%d, metadata:\n", ObjectID, param.ParameterName, sendDefault ? 1 : 0); - Bid.PutStr(metaData.TraceString(3)); - Bid.Trace("\n"); - } + var sendDefaultValue = sendDefault ? 1 : 0; + + SqlClientEventSource._log.Trace($" {ObjectID}#, Sending parameter '{param.ParameterName}', default flag={sendDefaultValue}, metadata:\n"); + SqlClientEventSource._log.PutStr(metaData.TraceString(3)); + SqlClientEventSource._log.Trace("\n"); // // Write parameter metadata @@ -11408,7 +11390,8 @@ internal Task WriteBulkCopyValue(object value, SqlMetaDataPriv metadata, TdsPars #if DEBUG //In DEBUG mode, when SetAlwaysTaskOnWrite is true, we create a task. Allows us to verify async execution paths. - if (_asyncWrite && internalWriteTask == null && SqlBulkCopy.SetAlwaysTaskOnWrite == true) { + if (_asyncWrite && internalWriteTask == null && SqlBulkCopy.SetAlwaysTaskOnWrite == true) + { internalWriteTask = Task.FromResult(null); } #endif @@ -11543,7 +11526,7 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio Debug.Assert(-1 <= timeout, "Timeout"); - Bid.NotificationsTrace(" NotificationRequest: userData: '%ls', options: '%ls', timeout: '%d'\n", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); + SqlClientEventSource._log.NotificationsTrace($" NotificationRequest: userData: '{notificationRequest.UserData}', options: '{notificationRequest.Options}', timeout: '{notificationRequest.Timeout}'\n"); WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj); // Query notifications Type @@ -11570,7 +11553,7 @@ private void WriteTraceHeaderData(TdsParserStateObject stateObj) stateObj.WriteByteArray(actId.Id.ToByteArray(), GUID_SIZE, 0); // Id (Guid) WriteUnsignedInt(actId.Sequence, stateObj); // sequence number - Bid.Trace(" ActivityID %ls\n", actId.ToString()); + SqlClientEventSource._log.Trace($" ActivityID {actId.ToString()}\n"); } private void WriteRPCBatchHeaders(TdsParserStateObject stateObj, SqlNotificationRequest notificationRequest) @@ -12055,7 +12038,8 @@ public override Task WriteAsync(byte[] buffer, int offset, int count, Cancellati TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -12076,7 +12060,8 @@ public override Task WriteAsync(byte[] buffer, int offset, int count, Cancellati } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index 8eb369c2c9..dea9ce05b2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -36,10 +36,8 @@ internal TdsParserSessionPool(TdsParser parser) _cache = new List(); _freeStateObjects = new TdsParserStateObject[MaxInactiveCount]; _freeStateObjectCount = 0; - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# created session pool for parser %d\n", ObjectID, parser.ObjectID); - } + + SqlClientEventSource._log.Trace($" {ObjectID}# created session pool for parser {parser.ObjectID}\n"); } private bool IsDisposed @@ -64,8 +62,7 @@ internal void Deactivate() // cache to make sure they're cleaned up and then we dispose of // sessions that are past what we want to keep around. - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d# deactivating cachedCount=%d\n", ObjectID, _cachedCount); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}# deactivating cachedCount={_cachedCount}\n"); try { @@ -86,10 +83,7 @@ internal void Deactivate() { // TODO: consider adding a performance counter for the number of sessions we reclaim - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# reclaiming session %d\n", ObjectID, session.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}# reclaiming session {session.ObjectID}\n"); PutSession(session); } @@ -101,7 +95,7 @@ internal void Deactivate() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -124,10 +118,7 @@ internal void BestEffortCleanup() internal void Dispose() { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# disposing cachedCount=%d\n", ObjectID, _cachedCount); - } + SqlClientEventSource._log.Trace($" {ObjectID}# disposing cachedCount={_cachedCount}\n"); lock (_cache) { @@ -188,10 +179,7 @@ internal TdsParserStateObject GetSession(object owner) // No free objects, create a new one session = _parser.CreateSession(); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# adding session %d to pool\n", ObjectID, session.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}# adding session {session.ObjectID} to pool\n"); _cache.Add(session); _cachedCount = _cache.Count; @@ -200,10 +188,7 @@ internal TdsParserStateObject GetSession(object owner) session.Activate(owner); } - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# using session %d\n", ObjectID, session.ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}# using session {session.ObjectID}\n"); return session; } @@ -226,10 +211,8 @@ internal void PutSession(TdsParserStateObject session) else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount)) { // Session is good to re-use and our cache has space - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# keeping session %d cachedCount=%d\n", ObjectID, session.ObjectID, _cachedCount); - } + SqlClientEventSource._log.Trace($" {ObjectID}# keeping session {session.ObjectID} cachedCount={_cachedCount}\n"); + Debug.Assert(!session._pendingData, "pending data on a pooled session?"); _freeStateObjects[_freeStateObjectCount] = session; @@ -238,10 +221,7 @@ internal void PutSession(TdsParserStateObject session) else { // Either the session is bad, or we have no cache space - so dispose the session and remove it - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# disposing session %d cachedCount=%d\n", ObjectID, session.ObjectID, _cachedCount); - } + SqlClientEventSource._log.Trace($" {ObjectID}# disposing session {session.ObjectID} cachedCount={_cachedCount}\n"); bool removed = _cache.Remove(session); Debug.Assert(removed, "session not in pool?"); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index b10acfd1e5..e3885f6818 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -174,7 +174,7 @@ internal int ObjectID private SniContext _sniContext = SniContext.Undefined; #if DEBUG - private SniContext _debugOnlyCopyOfSniContext=SniContext.Undefined; + private SniContext _debugOnlyCopyOfSniContext = SniContext.Undefined; #endif private bool _bcpLock = false; @@ -328,8 +328,10 @@ internal bool BcpLock } #if DEBUG - internal SniContext DebugOnlyCopyOfSniContext { - get { + internal SniContext DebugOnlyCopyOfSniContext + { + get + { return _debugOnlyCopyOfSniContext; } } @@ -352,7 +354,8 @@ internal bool HasOpenResult } #if DEBUG - internal void InvalidateDebugOnlyCopyOfSniContext() { + internal void InvalidateDebugOnlyCopyOfSniContext() + { _debugOnlyCopyOfSniContext = SniContext.Undefined; } #endif @@ -557,11 +560,8 @@ internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount) return false; } - if (Bid.TraceOn) - { - Bid.Trace(" %d#, NBCROW bitmap received, column count = %d\n", stateObj.ObjectID, columnsCount); - Bid.TraceBin(" NBCROW bitmap data: ", _nullBitmap, (UInt16)_nullBitmap.Length); - } + SqlClientEventSource._log.Trace($" {stateObj.ObjectID}#, NBCROW bitmap received, column count = {columnsCount}\n"); + SqlClientEventSource._log.TraceBin($" NBCROW bitmap data: ", _nullBitmap, (UInt16)_nullBitmap.Length); return true; } @@ -791,7 +791,7 @@ private void ResetCancelAndProcessAttention() { tdsReliabilitySection.Start(); #endif //DEBUG - Parser.ProcessPendingAck(this); + Parser.ProcessPendingAck(this); #if DEBUG } finally @@ -914,17 +914,11 @@ internal void DecrementOpenResultCount() internal int DecrementPendingCallbacks(bool release) { int remaining = Interlocked.Decrement(ref _pendingCallbacks); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, after decrementing _pendingCallbacks: %d\n", ObjectID, _pendingCallbacks); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, after decrementing _pendingCallbacks: { _pendingCallbacks}\n"); if ((0 == remaining || release) && _gcHandle.IsAllocated) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, FREEING HANDLE!\n", ObjectID); - } + SqlClientEventSource._log.Trace($" {ObjectID}#, FREEING HANDLE!\n"); _gcHandle.Free(); } @@ -1032,10 +1026,9 @@ internal Int32 IncrementAndObtainOpenResultCount(SqlInternalTransaction transact internal int IncrementPendingCallbacks() { int remaining = Interlocked.Increment(ref _pendingCallbacks); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, after incrementing _pendingCallbacks: %d\n", ObjectID, _pendingCallbacks); - } + + SqlClientEventSource._log.Trace($" {ObjectID}#, after incrementing _pendingCallbacks: {_pendingCallbacks}\n"); + Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}"); return remaining; } @@ -1375,15 +1368,18 @@ public bool TryReadByteArray(byte[] buff, int offset, int len, out int totalRead totalRead = 0; #if DEBUG - if (_snapshot != null && _snapshot.DoPend()) { + if (_snapshot != null && _snapshot.DoPend()) + { _networkPacketTaskSource = new TaskCompletionSource(); Thread.MemoryBarrier(); - if (_forcePendingReadsToWaitForUser) { + if (_forcePendingReadsToWaitForUser) + { _realNetworkPacketTaskSource = new TaskCompletionSource(); _realNetworkPacketTaskSource.SetResult(null); } - else { + else + { _networkPacketTaskSource.TrySetResult(null); } return false; @@ -1430,15 +1426,18 @@ internal bool TryReadByte(out byte value) value = 0; #if DEBUG - if (_snapshot != null && _snapshot.DoPend()) { + if (_snapshot != null && _snapshot.DoPend()) + { _networkPacketTaskSource = new TaskCompletionSource(); Thread.MemoryBarrier(); - if (_forcePendingReadsToWaitForUser) { + if (_forcePendingReadsToWaitForUser) + { _realNetworkPacketTaskSource = new TaskCompletionSource(); _realNetworkPacketTaskSource.SetResult(null); } - else { + else + { _networkPacketTaskSource.TrySetResult(null); } return false; @@ -2157,16 +2156,19 @@ internal bool TryReadNetworkPacket() if (_snapshot.Replay()) { #if DEBUG - if (_checkNetworkPacketRetryStacks) { + if (_checkNetworkPacketRetryStacks) + { _snapshot.CheckStack(new StackTrace()); } #endif - Bid.Trace(" Async packet replay\n"); + SqlClientEventSource._log.Trace($" Async packet replay\n"); return true; } #if DEBUG - else { - if (_checkNetworkPacketRetryStacks) { + else + { + if (_checkNetworkPacketRetryStacks) + { _lastStack = new StackTrace(); } } @@ -2186,10 +2188,12 @@ internal bool TryReadNetworkPacket() ReadSni(new TaskCompletionSource()); #if DEBUG - if (_failAsyncPends) { + if (_failAsyncPends) + { throw new InvalidOperationException("Attempted to pend a read when _failAsyncPends test hook was enabled"); } - if (_forceSyncOverAsyncAfterFirstPend) { + if (_forceSyncOverAsyncAfterFirstPend) + { _syncOverAsync = true; } #endif @@ -2244,7 +2248,8 @@ internal void ReadSniSyncOverAsync() Debug.Assert(ADP.PtrZero != readPacket, "ReadNetworkPacket cannot be null in synchronous operation!"); ProcessSniPacket(readPacket, 0); #if DEBUG - if (_forcePendingReadsToWaitForUser) { + if (_forcePendingReadsToWaitForUser) + { _networkPacketTaskSource = new TaskCompletionSource(); Thread.MemoryBarrier(); _networkPacketTaskSource.Task.Wait(); @@ -2432,7 +2437,8 @@ internal void ReadSni(TaskCompletionSource completion) } #if DEBUG - if (_forcePendingReadsToWaitForUser) { + if (_forcePendingReadsToWaitForUser) + { _realNetworkPacketTaskSource = new TaskCompletionSource(); } #endif @@ -2500,7 +2506,8 @@ internal void ReadSni(TaskCompletionSource completion) Debug.Assert(IntPtr.Zero == readPacket, "unexpected readPacket without corresponding SNIPacketRelease"); ReadSniError(this, error); #if DEBUG - if ((_forcePendingReadsToWaitForUser) && (_realNetworkPacketTaskSource != null)) { + if ((_forcePendingReadsToWaitForUser) && (_realNetworkPacketTaskSource != null)) + { _realNetworkPacketTaskSource.TrySetResult(null); } else @@ -2576,7 +2583,7 @@ internal bool IsConnectionAlive(bool throwOnException) if ((error != TdsEnums.SNI_SUCCESS) && (error != TdsEnums.SNI_WAIT_TIMEOUT)) { // Connection is dead - Bid.Trace(" received error %d on idle connection\n", (int)error); + SqlClientEventSource._log.Trace($" received error {(int)error} on idle connection\n"); isAlive = false; if (throwOnException) { @@ -2792,10 +2799,7 @@ public void ProcessSniPacket(IntPtr packet, UInt32 error) SniReadStatisticsAndTracing(); - if (Bid.AdvancedOn) - { - Bid.TraceBin(" Packet read", _inBuff, (UInt16)_inBytesRead); - } + SqlClientEventSource._log.TraceBin($" Packet read", _inBuff, (UInt16)_inBytesRead); AssertValidState(); } @@ -2836,7 +2840,8 @@ public void ReadAsyncCallback(IntPtr key, IntPtr packet, UInt32 error) TaskCompletionSource source = _networkPacketTaskSource; #if DEBUG - if ((_forcePendingReadsToWaitForUser) && (_realNetworkPacketTaskSource != null)) { + if ((_forcePendingReadsToWaitForUser) && (_realNetworkPacketTaskSource != null)) + { source = _realNetworkPacketTaskSource; } #endif @@ -2952,7 +2957,7 @@ public void WriteAsyncCallback(IntPtr key, IntPtr packet, UInt32 sniError) { if (sniError != TdsEnums.SNI_SUCCESS) { - Bid.Trace(" write async returned error code %d\n", (int)sniError); + SqlClientEventSource._log.Trace($" write async returned error code {(int)sniError}\n"); try { AddError(_parser.ProcessSNIError(this)); @@ -2995,16 +3000,20 @@ public void WriteAsyncCallback(IntPtr key, IntPtr packet, UInt32 sniError) finally { #if DEBUG - if (SqlCommand.DebugForceAsyncWriteDelay > 0) { - new Timer(obj => { + if (SqlCommand.DebugForceAsyncWriteDelay > 0) + { + new Timer(obj => + { Interlocked.Decrement(ref _asyncWriteCount); var writeCompletionSource = _writeCompletionSource; - if (_asyncWriteCount == 0 && writeCompletionSource != null) { + if (_asyncWriteCount == 0 && writeCompletionSource != null) + { writeCompletionSource.TrySetResult(null); } }, null, SqlCommand.DebugForceAsyncWriteDelay, Timeout.Infinite); } - else { + else + { #else { #endif @@ -3012,7 +3021,8 @@ public void WriteAsyncCallback(IntPtr key, IntPtr packet, UInt32 sniError) } } #if DEBUG - if (SqlCommand.DebugForceAsyncWriteDelay > 0) { + if (SqlCommand.DebugForceAsyncWriteDelay > 0) + { return; } #endif @@ -3399,30 +3409,36 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr } } #if DEBUG - else if (!sync && !canAccumulate && SqlCommand.DebugForceAsyncWriteDelay > 0) { - // Executed synchronously - callback will not be called - TaskCompletionSource completion = new TaskCompletionSource(); - uint error = sniError; - new Timer(obj=>{ - try { - if (_parser.MARSOn) { // Only take reset lock on MARS. - CheckSetResetConnectionState(error, CallbackType.Write); - } + else if (!sync && !canAccumulate && SqlCommand.DebugForceAsyncWriteDelay > 0) + { + // Executed synchronously - callback will not be called + TaskCompletionSource completion = new TaskCompletionSource(); + uint error = sniError; + new Timer(obj => + { + try + { + if (_parser.MARSOn) + { // Only take reset lock on MARS. + CheckSetResetConnectionState(error, CallbackType.Write); + } - if (error != TdsEnums.SNI_SUCCESS) { - Bid.Trace(" write async returned error code %d\n", (int)error); - AddError(_parser.ProcessSNIError(this)); - ThrowExceptionAndWarning(); - } - AssertValidState(); - completion.SetResult(null); - } - catch (Exception e) { - completion.SetException(e); - } - },null,SqlCommand.DebugForceAsyncWriteDelay,Timeout.Infinite); - task = completion.Task; - } + if (error != TdsEnums.SNI_SUCCESS) + { + SqlClientEventSource._log.Trace($" write async returned error code {(int)error}\n"); + AddError(_parser.ProcessSNIError(this)); + ThrowExceptionAndWarning(); + } + AssertValidState(); + completion.SetResult(null); + } + catch (Exception e) + { + completion.SetException(e); + } + }, null, SqlCommand.DebugForceAsyncWriteDelay, Timeout.Infinite); + task = completion.Task; + } #endif else @@ -3446,7 +3462,7 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr } else { - Bid.Trace(" write async returned error code %d\n", (int)sniError); + SqlClientEventSource._log.Trace($" write async returned error code {(int)sniError}\n"); AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(callerHasConnectionLock); } @@ -3487,35 +3503,35 @@ internal void SendAttention(bool mustTakeWriteLock = false) if (!_skipSendAttention) { #endif - // Take lock and send attention - bool releaseLock = false; - if ((mustTakeWriteLock) && (!_parser.Connection.ThreadHasParserLockForClose)) - { - releaseLock = true; - _parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false); - _parser.Connection.ThreadHasParserLockForClose = true; - } - try - { - // Check again (just in case the connection was closed while we were waiting) - if (_parser.State == TdsParserState.Closed || _parser.State == TdsParserState.Broken) + // Take lock and send attention + bool releaseLock = false; + if ((mustTakeWriteLock) && (!_parser.Connection.ThreadHasParserLockForClose)) { - return; + releaseLock = true; + _parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false); + _parser.Connection.ThreadHasParserLockForClose = true; } + try + { + // Check again (just in case the connection was closed while we were waiting) + if (_parser.State == TdsParserState.Closed || _parser.State == TdsParserState.Broken) + { + return; + } - UInt32 sniError; - _parser._asyncWrite = false; // stop async write - SNIWritePacket(Handle, attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false); - Bid.Trace(" Send Attention ASync .\n"); - } - finally - { - if (releaseLock) + UInt32 sniError; + _parser._asyncWrite = false; // stop async write + SNIWritePacket(Handle, attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false); + SqlClientEventSource._log.Trace($" Send Attention ASync .\n"); + } + finally { - _parser.Connection.ThreadHasParserLockForClose = false; - _parser.Connection._parserLock.Release(); + if (releaseLock) + { + _parser.Connection.ThreadHasParserLockForClose = false; + _parser.Connection._parserLock.Release(); + } } - } #if DEBUG } @@ -3529,11 +3545,8 @@ internal void SendAttention(bool mustTakeWriteLock = false) _attentionSending = false; } - if (Bid.AdvancedOn) - { - Bid.TraceBin(" Packet sent", _outBuff, (UInt16)_outBytesUsed); - } - Bid.Trace(" Attention sent to the server.\n"); + SqlClientEventSource._log.TraceBin($" Packet sent", _outBuff, (UInt16)_outBytesUsed); + SqlClientEventSource._log.Trace($" Attention sent to the server.\n"); AssertValidState(); } @@ -3652,7 +3665,8 @@ private void RemovePacketFromPendingList(IntPtr pointer) _writePacketCache.Add(recoveredPacket); } #if DEBUG - else { + else + { Debug.Assert(false, "Removing a packet from the pending list that was never added to it"); } #endif @@ -3689,37 +3703,34 @@ private void SniWriteStatisticsAndTracing() statistics.RequestNetworkServerTimer(); } - if (Bid.AdvancedOn) + // If we have tracePassword variables set, we are flushing TDSLogin and so we need to + // blank out password in buffer. Buffer has already been sent to netlib, so no danger + // of losing info. + if (_tracePasswordOffset != 0) { - // If we have tracePassword variables set, we are flushing TDSLogin and so we need to - // blank out password in buffer. Buffer has already been sent to netlib, so no danger - // of losing info. - if (_tracePasswordOffset != 0) + for (int i = _tracePasswordOffset; i < _tracePasswordOffset + + _tracePasswordLength; i++) { - for (int i = _tracePasswordOffset; i < _tracePasswordOffset + - _tracePasswordLength; i++) - { - _outBuff[i] = 0; - } - - // Reset state. - _tracePasswordOffset = 0; - _tracePasswordLength = 0; + _outBuff[i] = 0; } - if (_traceChangePasswordOffset != 0) - { - for (int i = _traceChangePasswordOffset; i < _traceChangePasswordOffset + - _traceChangePasswordLength; i++) - { - _outBuff[i] = 0; - } - // Reset state. - _traceChangePasswordOffset = 0; - _traceChangePasswordLength = 0; + // Reset state. + _tracePasswordOffset = 0; + _tracePasswordLength = 0; + } + if (_traceChangePasswordOffset != 0) + { + for (int i = _traceChangePasswordOffset; i < _traceChangePasswordOffset + + _traceChangePasswordLength; i++) + { + _outBuff[i] = 0; } - Bid.TraceBin(" Packet sent", _outBuff, (UInt16)_outBytesUsed); + + // Reset state. + _traceChangePasswordOffset = 0; + _traceChangePasswordLength = 0; } + SqlClientEventSource._log.TraceBin($" Packet sent", _outBuff, (UInt16)_outBytesUsed); } [Conditional("DEBUG")] @@ -3993,22 +4004,28 @@ internal void AssertStateIsClean() } #if DEBUG - internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait) { + internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait) + { var realNetworkPacketTaskSource = _realNetworkPacketTaskSource; var networkPacketTaskSource = _networkPacketTaskSource; Debug.Assert(_forcePendingReadsToWaitForUser, "Not forcing pends to wait for user - can't force complete"); Debug.Assert(networkPacketTaskSource != null, "No pending read to complete"); - - try { - if (realNetworkPacketTaskSource != null) { + + try + { + if (realNetworkPacketTaskSource != null) + { // Wait for the real read to complete realNetworkPacketTaskSource.Task.Wait(); } } - finally { - if (networkPacketTaskSource != null) { - if (resetForcePendingReadsToWait) { + finally + { + if (networkPacketTaskSource != null) + { + if (resetForcePendingReadsToWait) + { _forcePendingReadsToWaitForUser = false; } @@ -4017,30 +4034,38 @@ internal void CompletePendingReadWithSuccess(bool resetForcePendingReadsToWait) } } - internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait) { + internal void CompletePendingReadWithFailure(int errorCode, bool resetForcePendingReadsToWait) + { var realNetworkPacketTaskSource = _realNetworkPacketTaskSource; var networkPacketTaskSource = _networkPacketTaskSource; Debug.Assert(_forcePendingReadsToWaitForUser, "Not forcing pends to wait for user - can't force complete"); Debug.Assert(networkPacketTaskSource != null, "No pending read to complete"); - - try { - if (realNetworkPacketTaskSource != null) { + + try + { + if (realNetworkPacketTaskSource != null) + { // Wait for the real read to complete realNetworkPacketTaskSource.Task.Wait(); } } - finally { - if (networkPacketTaskSource != null) { - if (resetForcePendingReadsToWait) { + finally + { + if (networkPacketTaskSource != null) + { + if (resetForcePendingReadsToWait) + { _forcePendingReadsToWaitForUser = false; } AddError(new SqlError(errorCode, 0x00, TdsEnums.FATAL_ERROR_CLASS, _parser.Server, string.Empty, string.Empty, 0)); - try { + try + { ThrowExceptionAndWarning(); } - catch (Exception ex) { + catch (Exception ex) + { networkPacketTaskSource.TrySetException(ex); } } @@ -4096,12 +4121,15 @@ public StateSnapshot(TdsParserStateObject state) private int _rollingPend = 0; private int _rollingPendCount = 0; - internal bool DoPend() { - if (_failAsyncPends || !_forceAllPends) { + internal bool DoPend() + { + if (_failAsyncPends || !_forceAllPends) + { return false; } - if (_rollingPendCount == _rollingPend) { + if (_rollingPendCount == _rollingPend) + { _rollingPend++; _rollingPendCount = 0; return true; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsValueSetter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsValueSetter.cs index 52cca761a8..c4779b3e64 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsValueSetter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsValueSetter.cs @@ -26,7 +26,7 @@ internal class TdsValueSetter private Encoder _encoder; // required for chunking character type data private SmiMetaData _variantType; // required for sql_variant #if DEBUG - private int _currentOffset; // for chunking, verify that caller is using correct offsets + private int _currentOffset; // for chunking, verify that caller is using correct offsets #endif #endregion diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs index 540b4294e0..5fb7aa6d47 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs @@ -53,11 +53,8 @@ internal SqlInternalTransaction(SqlInternalConnection innerConnection, Transacti internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction, long transactionId) { - Bid.PoolerTrace(" %d#, Created for connection %d#, outer transaction %d#, Type %d\n", - ObjectID, - innerConnection.ObjectID, - (null != outerTransaction) ? outerTransaction.ObjectID : -1, - (int)type); + var outerTransactionObjectId = (null != outerTransaction) ? outerTransaction.ObjectID : -1; + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Created for connection {innerConnection.ObjectID}#, outer transaction {outerTransactionObjectId}#, Type {(int)type}\n"); _innerConnection = innerConnection; _transactionType = type; @@ -273,7 +270,7 @@ internal void CloseFromConnection() Debug.Assert(innerConnection != null, "How can we be here if the connection is null?"); - Bid.PoolerTrace(" %d#, Closing\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Closing\n"); bool processFinallyBlock = true; try { @@ -300,8 +297,7 @@ internal void CloseFromConnection() internal void Commit() { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); if (_innerConnection.IsLockedForBulkCopy) { @@ -346,7 +342,7 @@ internal void Commit() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -375,7 +371,7 @@ internal void Dispose() private /*protected override*/ void Dispose(bool disposing) { - Bid.PoolerTrace(" %d#, Disposing\n", ObjectID); + SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Disposing\n"); if (disposing) { if (null != _innerConnection) @@ -430,8 +426,7 @@ internal void InitParent(SqlTransaction transaction) internal void Rollback() { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); if (_innerConnection.IsLockedForBulkCopy) { @@ -472,14 +467,13 @@ internal void Rollback() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } internal void Rollback(string transactionName) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#, transactionName='%ls'", ObjectID, transactionName); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#, transactionName='{transactionName}'"); if (_innerConnection.IsLockedForBulkCopy) { @@ -522,14 +516,13 @@ internal void Rollback(string transactionName) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } internal void Save(string savePointName) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#, savePointName='%ls'", ObjectID, savePointName); + var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#, savePointName='{savePointName}'"); _innerConnection.ValidateConnectionForExecute(null); @@ -561,7 +554,7 @@ internal void Save(string savePointName) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs index 5571633e5c..25a8bb397d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs @@ -12,6 +12,7 @@ using System.Diagnostics; using System.Runtime.Versioning; using Microsoft.Data.Common; +using Microsoft.Data.SqlClient; namespace Microsoft.Data.SqlTypes { @@ -65,8 +66,7 @@ Int64 allocationSize ) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d# access=%d options=%d path='%ls' ", ObjectID, (int)access, (int)options, path); + var scopeID = SqlClientEventSource._log.ScopeEnter($" { ObjectID}# access={(int)access} options={(int)options} path='{path}'"); try { @@ -92,7 +92,7 @@ Int64 allocationSize } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource._log.ScopeLeave(scopeID); } } @@ -715,8 +715,8 @@ Int64 allocationSize UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode); try { - Bid.Trace(" %d#, desiredAccess=0x%08x, allocationSize=%I64d, fileAttributes=0x%08x, shareAccess=0x%08x, dwCreateDisposition=0x%08x, createOptions=0x%08x\n", - ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition, dwCreateOptions); + SqlClientEventSource._log.Trace($" {ObjectID}#, desiredAccess=0x{(int)nDesiredAccess}, allocationSize={allocationSize}, " + + $"fileAttributes=0x%{0}, shareAccess=0x{(int)shareAccess}, dwCreateDisposition=0x{dwCreateDisposition}, createOptions=0x{ dwCreateOptions}\n"); retval = UnsafeNativeMethods.NtCreateFile(out hFile, nDesiredAccess, ref oa, out ioStatusBlock, ref allocationSize, From aab8e8b67ffe5f17841ddd89f05210dfa396569e Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 28 Jan 2020 16:12:08 -0800 Subject: [PATCH 03/46] Adding IsTraceEnabled --- .../src/Microsoft/Data/Common/AdapterUtil.cs | 348 ++++++++++-------- .../Data/Common/DBConnectionString.cs | 12 +- .../Data/Common/DbConnectionOptions.cs | 24 +- .../netfx/src/Microsoft/Data/DataException.cs | 10 +- .../Data/ProviderBase/DbConnectionFactory.cs | 66 +++- .../Data/ProviderBase/DbConnectionInternal.cs | 42 ++- .../Data/ProviderBase/DbConnectionPool.cs | 101 ++--- .../ProviderBase/DbConnectionPoolGroup.cs | 21 +- .../Data/ProviderBase/SqlConnectionHelper.cs | 43 ++- .../Microsoft/Data/SqlClient/LocalDBAPI.cs | 42 ++- .../SqlClient/Server/SmiEventSink_Default.cs | 10 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 21 +- .../Data/SqlClient/SqlClientEventSource.cs | 7 +- .../Data/SqlClient/SqlClientLogger.cs | 12 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 191 ++++++---- .../Microsoft/Data/SqlClient/SqlCommandSet.cs | 22 +- .../Microsoft/Data/SqlClient/SqlConnection.cs | 96 +++-- .../Data/SqlClient/SqlConnectionFactory.cs | 7 +- .../SqlConnectionPoolGroupProviderInfo.cs | 13 +- .../Data/SqlClient/SqlDataAdapter.cs | 14 +- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 44 ++- .../Data/SqlClient/SqlDataReaderSmi.cs | 52 ++- .../Data/SqlClient/SqlDelegatedTransaction.cs | 36 +- .../Microsoft/Data/SqlClient/SqlDependency.cs | 139 +++---- .../Data/SqlClient/SqlDependencyListener.cs | 197 +++++----- .../Data/SqlClient/SqlDependencyUtils.cs | 83 ++--- .../src/Microsoft/Data/SqlClient/SqlError.cs | 6 +- .../Data/SqlClient/SqlInternalConnection.cs | 18 +- .../SqlClient/SqlInternalConnectionSmi.cs | 117 ++++-- .../SqlClient/SqlInternalConnectionTds.cs | 267 ++++++++++---- .../Data/SqlClient/SqlTransaction.cs | 35 +- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 264 ++++++++++--- .../Data/SqlClient/TdsParserSessionPool.cs | 40 +- .../Data/SqlClient/TdsParserStateObject.cs | 71 +++- .../Data/SqlClient/sqlinternaltransaction.cs | 25 +- .../Microsoft/Data/SqlTypes/SqlFileStream.cs | 13 +- 36 files changed, 1658 insertions(+), 851 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index cd354d72ee..42546f9622 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -21,11 +21,12 @@ using System.Threading; using System.Threading.Tasks; using System.Xml; -using Microsoft.Data.SqlClient; +using static Microsoft.Data.SqlClient.SqlClientEventSource; using Microsoft.Data.SqlClient.Server; using Microsoft.Win32; using SysES = System.EnterpriseServices; using SysTx = System.Transactions; +using Microsoft.Data.SqlClient; namespace Microsoft.Data.Common { @@ -100,9 +101,9 @@ static private void TraceException( string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e) + if (null != e && _log.IsTraceEnabled()) { - SqlClientEventSource._log.Trace(e.ToString()); // will include callstack if permission is available + _log.Trace(e.ToString()); // will include callstack if permission is available } } @@ -473,11 +474,12 @@ static internal ArgumentOutOfRangeException NotSupportedEnumerationValue(Type ty static internal ArgumentOutOfRangeException InvalidAcceptRejectRule(AcceptRejectRule value) { #if DEBUG - switch(value) { - case AcceptRejectRule.None: - case AcceptRejectRule.Cascade: - Debug.Assert(false, "valid AcceptRejectRule " + value.ToString()); - break; + switch (value) + { + case AcceptRejectRule.None: + case AcceptRejectRule.Cascade: + Debug.Assert(false, "valid AcceptRejectRule " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(AcceptRejectRule), (int)value); @@ -486,11 +488,12 @@ static internal ArgumentOutOfRangeException InvalidAcceptRejectRule(AcceptReject static internal ArgumentOutOfRangeException InvalidCatalogLocation(CatalogLocation value) { #if DEBUG - switch(value) { - case CatalogLocation.Start: - case CatalogLocation.End: - Debug.Assert(false, "valid CatalogLocation " + value.ToString()); - break; + switch (value) + { + case CatalogLocation.Start: + case CatalogLocation.End: + Debug.Assert(false, "valid CatalogLocation " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(CatalogLocation), (int)value); @@ -499,7 +502,8 @@ static internal ArgumentOutOfRangeException InvalidCatalogLocation(CatalogLocati static internal ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value) { #if DEBUG - if ((0 <= (int)value) && ((int)value <= 0x3F)) { + if ((0 <= (int)value) && ((int)value <= 0x3F)) + { Debug.Assert(false, "valid CommandType " + value.ToString()); } #endif @@ -526,12 +530,13 @@ static internal ArgumentException MustBeReadOnly(string argumentName) static internal ArgumentOutOfRangeException InvalidCommandType(CommandType value) { #if DEBUG - switch(value) { - case CommandType.Text: - case CommandType.StoredProcedure: - case CommandType.TableDirect: - Debug.Assert(false, "valid CommandType " + value.ToString()); - break; + switch (value) + { + case CommandType.Text: + case CommandType.StoredProcedure: + case CommandType.TableDirect: + Debug.Assert(false, "valid CommandType " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(CommandType), (int)value); @@ -540,12 +545,13 @@ static internal ArgumentOutOfRangeException InvalidCommandType(CommandType value static internal ArgumentOutOfRangeException InvalidConflictOptions(ConflictOption value) { #if DEBUG - switch(value) { - case ConflictOption.CompareAllSearchableValues: - case ConflictOption.CompareRowVersion: - case ConflictOption.OverwriteChanges: - Debug.Assert(false, "valid ConflictOption " + value.ToString()); - break; + switch (value) + { + case ConflictOption.CompareAllSearchableValues: + case ConflictOption.CompareRowVersion: + case ConflictOption.OverwriteChanges: + Debug.Assert(false, "valid ConflictOption " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(ConflictOption), (int)value); @@ -555,14 +561,15 @@ static internal ArgumentOutOfRangeException InvalidConflictOptions(ConflictOptio static internal ArgumentOutOfRangeException InvalidDataRowState(DataRowState value) { #if DEBUG - switch(value) { - case DataRowState.Detached: - case DataRowState.Unchanged: - case DataRowState.Added: - case DataRowState.Deleted: - case DataRowState.Modified: - Debug.Assert(false, "valid DataRowState " + value.ToString()); - break; + switch (value) + { + case DataRowState.Detached: + case DataRowState.Unchanged: + case DataRowState.Added: + case DataRowState.Deleted: + case DataRowState.Modified: + Debug.Assert(false, "valid DataRowState " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(DataRowState), (int)value); @@ -572,13 +579,14 @@ static internal ArgumentOutOfRangeException InvalidDataRowState(DataRowState val static internal ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value) { #if DEBUG - switch(value) { - case DataRowVersion.Default: - case DataRowVersion.Current: - case DataRowVersion.Original: - case DataRowVersion.Proposed: - Debug.Assert(false, "valid DataRowVersion " + value.ToString()); - break; + switch (value) + { + case DataRowVersion.Default: + case DataRowVersion.Current: + case DataRowVersion.Original: + case DataRowVersion.Proposed: + Debug.Assert(false, "valid DataRowVersion " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(DataRowVersion), (int)value); @@ -588,16 +596,17 @@ static internal ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion static internal ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value) { #if DEBUG - switch(value) { - case IsolationLevel.Unspecified: - case IsolationLevel.Chaos: - case IsolationLevel.ReadUncommitted: - case IsolationLevel.ReadCommitted: - case IsolationLevel.RepeatableRead: - case IsolationLevel.Serializable: - case IsolationLevel.Snapshot: - Debug.Assert(false, "valid IsolationLevel " + value.ToString()); - break; + switch (value) + { + case IsolationLevel.Unspecified: + case IsolationLevel.Chaos: + case IsolationLevel.ReadUncommitted: + case IsolationLevel.ReadCommitted: + case IsolationLevel.RepeatableRead: + case IsolationLevel.Serializable: + case IsolationLevel.Snapshot: + Debug.Assert(false, "valid IsolationLevel " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(IsolationLevel), (int)value); @@ -607,11 +616,12 @@ static internal ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel static internal ArgumentOutOfRangeException InvalidKeyRestrictionBehavior(KeyRestrictionBehavior value) { #if DEBUG - switch(value) { - case KeyRestrictionBehavior.PreventUsage: - case KeyRestrictionBehavior.AllowOnly: - Debug.Assert(false, "valid KeyRestrictionBehavior " + value.ToString()); - break; + switch (value) + { + case KeyRestrictionBehavior.PreventUsage: + case KeyRestrictionBehavior.AllowOnly: + Debug.Assert(false, "valid KeyRestrictionBehavior " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(KeyRestrictionBehavior), (int)value); @@ -621,12 +631,13 @@ static internal ArgumentOutOfRangeException InvalidKeyRestrictionBehavior(KeyRes static internal ArgumentOutOfRangeException InvalidLoadOption(LoadOption value) { #if DEBUG - switch(value) { - case LoadOption.OverwriteChanges: - case LoadOption.PreserveChanges: - case LoadOption.Upsert: - Debug.Assert(false, "valid LoadOption " + value.ToString()); - break; + switch (value) + { + case LoadOption.OverwriteChanges: + case LoadOption.PreserveChanges: + case LoadOption.Upsert: + Debug.Assert(false, "valid LoadOption " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(LoadOption), (int)value); @@ -636,12 +647,13 @@ static internal ArgumentOutOfRangeException InvalidLoadOption(LoadOption value) static internal ArgumentOutOfRangeException InvalidMissingMappingAction(MissingMappingAction value) { #if DEBUG - switch(value) { - case MissingMappingAction.Passthrough: - case MissingMappingAction.Ignore: - case MissingMappingAction.Error: - Debug.Assert(false, "valid MissingMappingAction " + value.ToString()); - break; + switch (value) + { + case MissingMappingAction.Passthrough: + case MissingMappingAction.Ignore: + case MissingMappingAction.Error: + Debug.Assert(false, "valid MissingMappingAction " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(MissingMappingAction), (int)value); @@ -651,13 +663,14 @@ static internal ArgumentOutOfRangeException InvalidMissingMappingAction(MissingM static internal ArgumentOutOfRangeException InvalidMissingSchemaAction(MissingSchemaAction value) { #if DEBUG - switch(value) { - case MissingSchemaAction.Add: - case MissingSchemaAction.Ignore: - case MissingSchemaAction.Error: - case MissingSchemaAction.AddWithKey: - Debug.Assert(false, "valid MissingSchemaAction " + value.ToString()); - break; + switch (value) + { + case MissingSchemaAction.Add: + case MissingSchemaAction.Ignore: + case MissingSchemaAction.Error: + case MissingSchemaAction.AddWithKey: + Debug.Assert(false, "valid MissingSchemaAction " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(MissingSchemaAction), (int)value); @@ -667,13 +680,14 @@ static internal ArgumentOutOfRangeException InvalidMissingSchemaAction(MissingSc static internal ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value) { #if DEBUG - switch(value) { - case ParameterDirection.Input: - case ParameterDirection.Output: - case ParameterDirection.InputOutput: - case ParameterDirection.ReturnValue: - Debug.Assert(false, "valid ParameterDirection " + value.ToString()); - break; + switch (value) + { + case ParameterDirection.Input: + case ParameterDirection.Output: + case ParameterDirection.InputOutput: + case ParameterDirection.ReturnValue: + Debug.Assert(false, "valid ParameterDirection " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(ParameterDirection), (int)value); @@ -682,11 +696,12 @@ static internal ArgumentOutOfRangeException InvalidParameterDirection(ParameterD static internal ArgumentOutOfRangeException InvalidPermissionState(PermissionState value) { #if DEBUG - switch(value) { - case PermissionState.Unrestricted: - case PermissionState.None: - Debug.Assert(false, "valid PermissionState " + value.ToString()); - break; + switch (value) + { + case PermissionState.Unrestricted: + case PermissionState.None: + Debug.Assert(false, "valid PermissionState " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(PermissionState), (int)value); @@ -695,13 +710,14 @@ static internal ArgumentOutOfRangeException InvalidPermissionState(PermissionSta static internal ArgumentOutOfRangeException InvalidRule(Rule value) { #if DEBUG - switch(value) { - case Rule.None: - case Rule.Cascade: - case Rule.SetNull: - case Rule.SetDefault: - Debug.Assert(false, "valid Rule " + value.ToString()); - break; + switch (value) + { + case Rule.None: + case Rule.Cascade: + case Rule.SetNull: + case Rule.SetDefault: + Debug.Assert(false, "valid Rule " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(Rule), (int)value); @@ -711,11 +727,12 @@ static internal ArgumentOutOfRangeException InvalidRule(Rule value) static internal ArgumentOutOfRangeException InvalidSchemaType(SchemaType value) { #if DEBUG - switch(value) { - case SchemaType.Source: - case SchemaType.Mapped: - Debug.Assert(false, "valid SchemaType " + value.ToString()); - break; + switch (value) + { + case SchemaType.Source: + case SchemaType.Mapped: + Debug.Assert(false, "valid SchemaType " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(SchemaType), (int)value); @@ -725,14 +742,15 @@ static internal ArgumentOutOfRangeException InvalidSchemaType(SchemaType value) static internal ArgumentOutOfRangeException InvalidStatementType(StatementType value) { #if DEBUG - switch(value) { - case StatementType.Select: - case StatementType.Insert: - case StatementType.Update: - case StatementType.Delete: - case StatementType.Batch: - Debug.Assert(false, "valid StatementType " + value.ToString()); - break; + switch (value) + { + case StatementType.Select: + case StatementType.Insert: + case StatementType.Update: + case StatementType.Delete: + case StatementType.Batch: + Debug.Assert(false, "valid StatementType " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(StatementType), (int)value); @@ -742,13 +760,14 @@ static internal ArgumentOutOfRangeException InvalidStatementType(StatementType v static internal ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value) { #if DEBUG - switch(value) { - case UpdateRowSource.None: - case UpdateRowSource.OutputParameters: - case UpdateRowSource.FirstReturnedRecord: - case UpdateRowSource.Both: - Debug.Assert(false, "valid UpdateRowSource " + value.ToString()); - break; + switch (value) + { + case UpdateRowSource.None: + case UpdateRowSource.OutputParameters: + case UpdateRowSource.FirstReturnedRecord: + case UpdateRowSource.Both: + Debug.Assert(false, "valid UpdateRowSource " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value); @@ -758,13 +777,14 @@ static internal ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSour static internal ArgumentOutOfRangeException InvalidUpdateStatus(UpdateStatus value) { #if DEBUG - switch(value) { - case UpdateStatus.Continue: - case UpdateStatus.ErrorsOccurred: - case UpdateStatus.SkipAllRemainingRows: - case UpdateStatus.SkipCurrentRow: - Debug.Assert(false, "valid UpdateStatus " + value.ToString()); - break; + switch (value) + { + case UpdateStatus.Continue: + case UpdateStatus.ErrorsOccurred: + case UpdateStatus.SkipAllRemainingRows: + case UpdateStatus.SkipCurrentRow: + Debug.Assert(false, "valid UpdateStatus " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(UpdateStatus), (int)value); @@ -783,12 +803,13 @@ static internal ArgumentOutOfRangeException NotSupportedStatementType(StatementT static internal ArgumentOutOfRangeException InvalidUserDefinedTypeSerializationFormat(Format value) { #if DEBUG - switch(value) { - case Format.Unknown: - case Format.Native: - case Format.UserDefined: - Debug.Assert(false, "valid UserDefinedTypeSerializationFormat " + value.ToString()); - break; + switch (value) + { + case Format.Unknown: + case Format.Native: + case Format.UserDefined: + Debug.Assert(false, "valid UserDefinedTypeSerializationFormat " + value.ToString()); + break; } #endif return InvalidEnumerationValue(typeof(Format), (int)value); @@ -1299,9 +1320,9 @@ static internal InvalidOperationException UpdateConnectionRequired(StatementType resource = Strings.ADP_ConnectionRequired_Batch; goto default; #if DEBUG - case StatementType.Select: - Debug.Assert(false, "shouldn't be here"); - goto default; + case StatementType.Select: + Debug.Assert(false, "shouldn't be here"); + goto default; #endif default: throw ADP.InvalidStatementType(statementType); @@ -1314,16 +1335,17 @@ static internal InvalidOperationException ConnectionRequired_Res(string method) { string resource = "ADP_ConnectionRequired_" + method; #if DEBUG - switch(resource) { - case StringsHelper.ResourceNames.ADP_ConnectionRequired_Fill: - case StringsHelper.ResourceNames.ADP_ConnectionRequired_FillPage: - case StringsHelper.ResourceNames.ADP_ConnectionRequired_FillSchema: - case StringsHelper.ResourceNames.ADP_ConnectionRequired_Update: - case StringsHelper.ResourceNames.ADP_ConnecitonRequired_UpdateRows: - break; - default: - Debug.Assert(false, "missing resource string: " + resource); - break; + switch (resource) + { + case StringsHelper.ResourceNames.ADP_ConnectionRequired_Fill: + case StringsHelper.ResourceNames.ADP_ConnectionRequired_FillPage: + case StringsHelper.ResourceNames.ADP_ConnectionRequired_FillSchema: + case StringsHelper.ResourceNames.ADP_ConnectionRequired_Update: + case StringsHelper.ResourceNames.ADP_ConnecitonRequired_UpdateRows: + break; + default: + Debug.Assert(false, "missing resource string: " + resource); + break; } #endif return InvalidOperation(StringsHelper.GetString(resource)); @@ -1349,12 +1371,12 @@ static internal InvalidOperationException UpdateOpenConnectionRequired(Statement resource = Strings.ADP_OpenConnectionRequired_Delete; break; #if DEBUG - case StatementType.Select: - Debug.Assert(false, "shouldn't be here"); - goto default; - case StatementType.Batch: - Debug.Assert(false, "isRowUpdatingCommand should have been true"); - goto default; + case StatementType.Select: + Debug.Assert(false, "shouldn't be here"); + goto default; + case StatementType.Batch: + Debug.Assert(false, "isRowUpdatingCommand should have been true"); + goto default; #endif default: throw ADP.InvalidStatementType(statementType); @@ -1517,10 +1539,10 @@ static internal Exception UpdateConcurrencyViolation(StatementType statementType resource = Strings.ADP_UpdateConcurrencyViolation_Batch; break; #if DEBUG - case StatementType.Select: - case StatementType.Insert: - Debug.Assert(false, "should be here"); - goto default; + case StatementType.Select: + case StatementType.Insert: + Debug.Assert(false, "should be here"); + goto default; #endif default: throw ADP.InvalidStatementType(statementType); @@ -1554,9 +1576,9 @@ static internal InvalidOperationException UpdateRequiresCommand(StatementType st resource = Strings.ADP_UpdateRequiresCommandDelete; break; #if DEBUG - case StatementType.Batch: - Debug.Assert(false, "isRowUpdatingCommand should have been true"); - goto default; + case StatementType.Batch: + Debug.Assert(false, "isRowUpdatingCommand should have been true"); + goto default; #endif default: throw ADP.InvalidStatementType(statementType); @@ -2927,15 +2949,17 @@ static internal bool IsDirection(IDataParameter value, ParameterDirection condit return (condition == (condition & value.Direction)); } #if DEBUG - static private void IsDirectionValid(ParameterDirection value) { - switch (value) { // @perfnote: Enum.IsDefined - case ParameterDirection.Input: - case ParameterDirection.Output: - case ParameterDirection.InputOutput: - case ParameterDirection.ReturnValue: - break; - default: - throw ADP.InvalidParameterDirection(value); + static private void IsDirectionValid(ParameterDirection value) + { + switch (value) + { // @perfnote: Enum.IsDefined + case ParameterDirection.Input: + case ParameterDirection.Output: + case ParameterDirection.InputOutput: + case ParameterDirection.ReturnValue: + break; + default: + throw ADP.InvalidParameterDirection(value); } } #endif diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs index 8897905b83..6d9930aaa4 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs @@ -12,7 +12,7 @@ namespace Microsoft.Data.Common using System.Diagnostics; using System.Linq; using System.Text; - using Microsoft.Data.SqlClient; + using static Microsoft.Data.SqlClient.SqlClientEventSource; [Serializable] // MDAC 83147 internal sealed class DBConnectionString @@ -470,7 +470,10 @@ static private string[] NoDuplicateUnion(string[] a, string[] b) private static string[] ParseRestrictions(string restrictions, Hashtable synonyms) { #if DEBUG - SqlClientEventSource._log.Trace($" Restrictions='{restrictions}'\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Restrictions='{restrictions}'"); + } #endif List restrictionValues = new List(); StringBuilder buffer = new StringBuilder(restrictions.Length); @@ -486,7 +489,10 @@ private static string[] ParseRestrictions(string restrictions, Hashtable synonym if (!ADP.IsEmpty(keyname)) { #if DEBUG - SqlClientEventSource._log.Trace($" KeyName='{keyname}'\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" KeyName='{keyname}'"); + } #endif string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144 if (ADP.IsEmpty(realkeyname)) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs index 6d83210530..ae67c7d69f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs @@ -12,7 +12,7 @@ namespace Microsoft.Data.Common using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; - using Microsoft.Data.SqlClient; + using static Microsoft.Data.SqlClient.SqlClientEventSource; internal class DbConnectionOptions { @@ -630,15 +630,19 @@ private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hash Debug.Assert(keyname == keyname.ToLower(CultureInfo.InvariantCulture), "missing ToLower"); string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); - if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) - { // don't trace passwords ever! - if (null != keyvalue) - { - SqlClientEventSource._log.Trace($" KeyName='{keyname}', KeyValue='{keyvalue}'\n"); - } - else - { - SqlClientEventSource._log.Trace($" KeyName='{keyname}'\n"); + + if (_log.IsTraceEnabled()) + { + if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) + { // don't trace passwords ever! + if (null != keyvalue) + { + _log.Trace($" KeyName='{keyname}', KeyValue='{keyvalue}'\n"); + } + else + { + _log.Trace($" KeyName='{keyname}'\n"); + } } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs index be2d6f2ef2..c1ef0bce8c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Globalization; using Microsoft.Data.SqlClient; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data { @@ -27,18 +28,19 @@ static private void TraceException( string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e) + if (null != e && _log.IsTraceEnabled()) { - SqlClientEventSource._log.Trace(e.Message); + _log.Trace(e.Message); + try { - SqlClientEventSource._log.Trace($", StackTrace='{Environment.StackTrace}'"); + _log.Trace($"{trace}, StackTrace='{Environment.StackTrace}'"); } catch (System.Security.SecurityException) { // if you don't have permission - you don't get the stack trace + _log.Trace("Permission Denied"); } - SqlClientEventSource._log.Trace("\n"); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index 3357c7b7dd..e96aba8d2c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -13,7 +13,7 @@ namespace Microsoft.Data.ProviderBase using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Common; - using Microsoft.Data.SqlClient; + using static Microsoft.Data.SqlClient.SqlClientEventSource; internal abstract class DbConnectionFactory { @@ -66,7 +66,7 @@ internal int ObjectID public void ClearAllPools() { - var scopeID = SqlClientEventSource._log.ScopeEnter(" "); + var scopeID = _log.ScopeEnter(" "); try { Dictionary connectionPoolGroups = _connectionPoolGroups; @@ -81,7 +81,7 @@ public void ClearAllPools() } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -89,7 +89,7 @@ public void ClearPool(DbConnection connection) { ADP.CheckArgumentNull(connection, "connection"); - var scopeID = SqlClientEventSource._log.ScopeEnter($" {GetObjectId(connection)}#"); + var scopeID = _log.ScopeEnter($" {GetObjectId(connection)}#"); try { DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); @@ -100,7 +100,7 @@ public void ClearPool(DbConnection connection) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -109,7 +109,7 @@ public void ClearPool(DbConnectionPoolKey key) Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, "key.ConnectionString"); - var scopeID = SqlClientEventSource._log.ScopeEnter(" connectionString"); + var scopeID = _log.ScopeEnter(" connectionString"); try { DbConnectionPoolGroup poolGroup; @@ -121,7 +121,7 @@ public void ClearPool(DbConnectionPoolKey key) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -153,7 +153,10 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakeNonPooledObject(owningConnection, PerformanceCounters); } - SqlClientEventSource._log.Trace($" {ObjectID}#, Non-pooled database connection created.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Non-pooled database connection created."); + } return newConnection; } @@ -163,12 +166,18 @@ internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbCo DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo; DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions); + if (null != newConnection) { PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakePooledConnection(pool); } - SqlClientEventSource._log.Trace($" {ObjectID}#, Pooled database connection created.\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Pooled database connection created."); + } + return newConnection; } @@ -363,8 +372,12 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour // connection creation failed on semaphore waiting or if max pool reached if (connectionPool.IsRunning) { + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred."); + } + // If GetConnection failed while the pool is running, the pool timeout occurred. - SqlClientEventSource._log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred.\n"); throw ADP.PooledOpenTimeout(); } else @@ -381,8 +394,12 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour if (connection == null) { + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred and all retries were exhausted."); + } + // exhausted all retries or timed out - give up - SqlClientEventSource._log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred and all retries were exhausted.\n"); throw ADP.PooledOpenTimeout(); } @@ -407,7 +424,10 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti // however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) { - SqlClientEventSource._log.Trace($" {ObjectID}#, DisabledPoolGroup={connectionPoolGroup.ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, DisabledPoolGroup={connectionPoolGroup.ObjectID}#"); + } // reusing existing pool option in case user originally used SetConnectionPoolOptions DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions; @@ -537,8 +557,11 @@ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPo private void PruneConnectionPoolGroups(object state) { - // when debugging this method, expect multiple threads at the same time - SqlClientEventSource._log.Trace($" {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + // when debugging this method, expect multiple threads at the same time + _log.Trace($" {ObjectID}#"); + } // First, walk the pool release list and attempt to clear each // pool, when the pool is finally empty, we dispose of it. If the @@ -559,7 +582,10 @@ private void PruneConnectionPoolGroups(object state) { _poolsToRelease.Remove(pool); - SqlClientEventSource._log.Trace($" { ObjectID}#, ReleasePool={pool.ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" { ObjectID}#, ReleasePool={pool.ObjectID}#"); + } PerformanceCounters.NumberOfInactiveConnectionPools.Decrement(); } @@ -586,7 +612,10 @@ private void PruneConnectionPoolGroups(object state) { _poolGroupsToRelease.Remove(poolGroup); - SqlClientEventSource._log.Trace($" {ObjectID}#, ReleasePoolGroup={poolGroup.ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, ReleasePoolGroup={poolGroup.ObjectID}#"); + } PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Decrement(); } @@ -653,7 +682,10 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { Debug.Assert(null != poolGroup, "null poolGroup?"); - SqlClientEventSource._log.Trace($" {ObjectID}#, poolGroup={poolGroup.ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, poolGroup={poolGroup.ObjectID}#"); + } lock (_poolGroupsToRelease) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index ed08ac67b1..ed1bde3fa6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -14,7 +14,7 @@ namespace Microsoft.Data.ProviderBase using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Common; - using Microsoft.Data.SqlClient; + using static Microsoft.Data.SqlClient.SqlClientEventSource; using SysTx = System.Transactions; internal abstract class DbConnectionInternal @@ -164,7 +164,7 @@ protected internal SysTx.Transaction EnlistedTransaction if (null != value) { int x = value.GetHashCode(); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {x}#, Enlisting.\n"); + _log.PoolerTrace($" {ObjectID}#, Transaction {x}#, Enlisting."); TransactionOutcomeEnlist(value); } @@ -391,7 +391,10 @@ internal void ActivateConnection(SysTx.Transaction transaction) // Internal method called from the connection pooler so we don't expose // the Activate method publicly. - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Activating\n"); + if (_log.IsTraceEnabled()) + { + _log.PoolerTrace($" {ObjectID}#, Activating"); + } #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); Debug.Assert(1 == activateCount, "activated multiple times?"); @@ -463,7 +466,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac Debug.Assert(null != owningObject, "null owningObject"); Debug.Assert(null != connectionFactory, "null connectionFactory"); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}# Closing.\n"); + _log.PoolerTrace($" {ObjectID}# Closing."); // if an exception occurs after the state change but before the try block // the connection will be stuck in OpenBusy state. The commented out try-catch @@ -569,7 +572,7 @@ internal void DeactivateConnection() // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Deactivating\n"); + _log.PoolerTrace($" {ObjectID}#, Deactivating"); #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); Debug.Assert(0 == activateCount, "activated multiple times?"); @@ -604,7 +607,10 @@ virtual internal void DelegatedTransactionEnded() // you call this method to prevent race conditions with Clear and // ReclaimEmancipatedObjects. - SqlClientEventSource._log.Trace($" {ObjectID}#, Delegated Transaction Completed.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Delegated Transaction Completed."); + } if (1 == _pooledCount) { @@ -667,7 +673,7 @@ public virtual void Dispose() protected internal void DoNotPoolThisConnection() { _cannotBePooled = true; - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Marking pooled object as non-poolable so it will be disposed\n"); + _log.PoolerTrace($" {ObjectID}#, Marking pooled object as non-poolable so it will be disposed"); } /// Ensure that this connection cannot be put back into the pool. @@ -675,7 +681,7 @@ protected internal void DoNotPoolThisConnection() protected internal void DoomThisConnection() { _connectionIsDoomed = true; - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Dooming\n"); + _log.PoolerTrace($" {ObjectID}#, Dooming"); } // Reset connection doomed status so it can be re-connected and pooled. @@ -808,7 +814,7 @@ internal void PrePush(object expectedOwner) throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time } //DbConnection x = (expectedOwner as DbConnection); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Preparing to push into pool, owning connection {0}#, pooledCount={ _pooledCount}\n"); + _log.PoolerTrace($" {ObjectID}#, Preparing to push into pool, owning connection {0}#, pooledCount={ _pooledCount}"); _pooledCount++; _owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2% } @@ -839,7 +845,7 @@ internal void PostPop(object newOwner) _pooledCount--; //DbConnection x = (newOwner as DbConnection); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Preparing to pop from pool, owning connection {0}#, pooledCount={_pooledCount}\n"); + _log.PoolerTrace($" {ObjectID}#, Preparing to pop from pool, owning connection {0}#, pooledCount={_pooledCount}"); //3 // The following tests are retail assertions of things we can't allow to happen. if (null != Pool) @@ -896,7 +902,10 @@ internal void DetachCurrentTransactionIfEnded() // Detach transaction from connection. internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})"); + } // potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new // transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should @@ -938,7 +947,10 @@ void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) { SysTx.Transaction transaction = e.Transaction; - SqlClientEventSource._log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})"); + } CleanupTransactionOnCompletion(transaction); @@ -956,7 +968,7 @@ private void TransactionOutcomeEnlist(SysTx.Transaction transaction) internal void SetInStasis() { _isInStasis = true; - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.\n"); + _log.PoolerTrace($" {ObjectID}#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose."); PerformanceCounters.NumberOfStasisConnections.Increment(); } @@ -964,11 +976,11 @@ private void TerminateStasis(bool returningToPool) { if (returningToPool) { - SqlClientEventSource._log.PoolerTrace($" { ObjectID}#, Delegated Transaction has ended, connection is closed. Returning to general pool.\n"); + _log.PoolerTrace($" { ObjectID}#, Delegated Transaction has ended, connection is closed. Returning to general pool."); } else { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Delegated Transaction has ended, connection is closed/leaked. Disposing.\n"); + _log.PoolerTrace($" {ObjectID}#, Delegated Transaction has ended, connection is closed/leaked. Disposing."); } PerformanceCounters.NumberOfStasisConnections.Decrement(); _isInStasis = false; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index 33c86f7a45..15fa154ae4 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -19,6 +19,7 @@ namespace Microsoft.Data.ProviderBase using System.Threading.Tasks; using Microsoft.Data.Common; using Microsoft.Data.SqlClient; + using static Microsoft.Data.SqlClient.SqlClientEventSource; using SysTx = System.Transactions; sealed internal class DbConnectionPool @@ -82,7 +83,7 @@ internal TransactedConnectionPool(DbConnectionPool pool) _pool = pool; _transactedCxns = new Dictionary(); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Constructed for connection pool {_pool.ObjectID}#\n"); + _log.PoolerTrace($" {ObjectID}#, Constructed for connection pool {_pool.ObjectID}#"); } internal int ObjectID @@ -141,7 +142,7 @@ internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction) if (null != transactedObject) { - SqlClientEventSource._log.PoolerTrace($" { ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Popped.\n"); + _log.PoolerTrace($" { ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Popped."); } return transactedObject; } @@ -168,7 +169,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing.\n"); + _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing."); connections.Add(transactedObject); } @@ -204,14 +205,14 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing.\n"); + _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing."); connections.Add(transactedObject); } } else { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Adding List to transacted pool.\n"); + _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Adding List to transacted pool."); // add the connection/transacted object to the list newConnections.Add(transactedObject); @@ -239,7 +240,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt } } } - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Added.\n"); + _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Added."); } Pool.PerformanceCounters.NumberOfFreeConnections.Increment(); @@ -248,7 +249,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionInternal transactedObject) { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed\n"); + _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed"); TransactedConnectionList connections; int entry = -1; @@ -283,7 +284,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern // safely remove the list from the transacted pool. if (0 >= connections.Count) { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Removing List from transacted pool.\n"); + _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Removing List from transacted pool."); _transactedCxns.Remove(transaction); // we really need to dispose our connection list; it may have @@ -300,7 +301,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern else { //Debug.Assert ( false, "TransactionCompletedEvent fired before PutTransactedObject put the connection in the transacted pool." ); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transacted pool not yet created prior to transaction completing. Connection may be leaked.\n"); + _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transacted pool not yet created prior to transaction completing. Connection may be leaked."); } } @@ -528,7 +529,7 @@ internal DbConnectionPool( _poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback _state = State.Running; - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Constructed.\n"); + _log.PoolerTrace($" {ObjectID}#, Constructed."); //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls // StartBackgroundCallbacks after pool is actually in the collection @@ -677,7 +678,7 @@ private void CleanupCallback(Object state) // With this logic, objects are pruned from the pool if unused for // at least one period but not more than two periods. - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#\n"); + _log.PoolerTrace($" {ObjectID}#"); // Destroy free objects that put us above MinPoolSize from old stack. while (Count > MinPoolSize) @@ -752,7 +753,7 @@ private void CleanupCallback(Object state) Debug.Assert(obj != null, "null connection is not expected"); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, ChangeStacks={obj.ObjectID}#\n"); + _log.PoolerTrace($" {ObjectID}#, ChangeStacks={obj.ObjectID}#"); Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); Debug.Assert(obj.CanBePooled, "pooled object is not poolable"); @@ -768,7 +769,7 @@ private void CleanupCallback(Object state) internal void Clear() { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Clearing.\n"); + _log.PoolerTrace($" {ObjectID}#, Clearing."); DbConnectionInternal obj; @@ -806,7 +807,7 @@ internal void Clear() // it's been doomed, will cause it to be disposed of as well) ReclaimEmancipatedObjects(); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Cleared.\n"); + _log.PoolerTrace($" {ObjectID}#, Cleared."); } private Timer CreateCleanupTimer() @@ -896,7 +897,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio } } } - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {newObj.ObjectID}#, Added to pool.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {newObj.ObjectID}#, Added to pool."); // Reset the error wait: _errorWait = ERROR_WAIT_DEFAULT; @@ -957,7 +958,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio private void DeactivateObject(DbConnectionInternal obj) { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Deactivating.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Deactivating."); obj.DeactivateConnection(); // we presume this operation is safe outside of a lock... @@ -1098,11 +1099,11 @@ internal void DestroyObject(DbConnectionInternal obj) // again. if (obj.IsTxRootWaitingForTxEnd) { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Has Delegated Transaction, waiting to Dispose.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Has Delegated Transaction, waiting to Dispose."); } else { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removing from pool.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removing from pool."); bool removed = false; lock (_objectList) @@ -1114,19 +1115,19 @@ internal void DestroyObject(DbConnectionInternal obj) if (removed) { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removed from pool.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removed from pool."); PerformanceCounters.NumberOfPooledConnections.Decrement(); } obj.Dispose(); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Disposed.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Disposed."); PerformanceCounters.HardDisconnectsPerSecond.Increment(); } } private void ErrorCallback(Object state) { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Resetting Error handling.\n"); + _log.PoolerTrace($" {ObjectID}#, Resetting Error handling."); _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); @@ -1301,7 +1302,7 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource {ObjectID}#, DbConnectionInternal State != Running.\n"); + _log.PoolerTrace($" {ObjectID}#, DbConnectionInternal State != Running."); connection = null; return true; } @@ -1347,7 +1348,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj PerformanceCounters.SoftConnectsPerSecond.Increment(); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Getting connection.\n"); + _log.PoolerTrace($" {ObjectID}#, Getting connection."); // If automatic transaction enlistment is required, then we try to // get the connection from the transacted connection pool first. @@ -1400,19 +1401,19 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj switch (waitResult) { case WAIT_TIMEOUT: - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Wait timed out.\n"); + _log.PoolerTrace($" {ObjectID}#, Wait timed out."); Interlocked.Decrement(ref _waitCount); connection = null; return false; case ERROR_HANDLE: // Throw the error that PoolCreateRequest stashed. - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Errors are set.\n"); + _log.PoolerTrace($" {ObjectID}#, Errors are set."); Interlocked.Decrement(ref _waitCount); throw TryCloneCachedException(); case CREATION_HANDLE: - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Creating new connection.\n"); + _log.PoolerTrace($" {ObjectID}#, Creating new connection."); try { @@ -1466,7 +1467,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj if ((obj != null) && (!obj.IsConnectionAlive())) { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); DestroyObject(obj); obj = null; // Setting to null in case creating a new object fails @@ -1477,7 +1478,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj RuntimeHelpers.PrepareConstrainedRegions(); try { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Creating new connection.\n"); + _log.PoolerTrace($" {ObjectID}#, Creating new connection."); obj = UserCreateRequest(owningObject, userOptions); } finally @@ -1488,7 +1489,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj else { // Timeout waiting for creation semaphore - return null - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Wait timed out.\n"); + _log.PoolerTrace($" {ObjectID}#, Wait timed out."); connection = null; return false; } @@ -1498,24 +1499,24 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case WAIT_FAILED: Debug.Assert(waitForMultipleObjectsExHR != 0, "WaitForMultipleObjectsEx failed but waitForMultipleObjectsExHR remained 0"); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Wait failed.\n"); + _log.PoolerTrace($" {ObjectID}#, Wait failed.\n"); Interlocked.Decrement(ref _waitCount); Marshal.ThrowExceptionForHR(waitForMultipleObjectsExHR); goto default; // if ThrowExceptionForHR didn't throw for some reason case (WAIT_ABANDONED + SEMAPHORE_HANDLE): - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Semaphore handle abandonded.\n"); + _log.PoolerTrace($" {ObjectID}#, Semaphore handle abandonded."); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(SEMAPHORE_HANDLE, _waitHandles.PoolSemaphore); case (WAIT_ABANDONED + ERROR_HANDLE): - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Error handle abandonded.\n"); + _log.PoolerTrace($" {ObjectID}#, Error handle abandonded."); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(ERROR_HANDLE, _waitHandles.ErrorEvent); case (WAIT_ABANDONED + CREATION_HANDLE): - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Creation handle abandoned.\n"); + _log.PoolerTrace($" {ObjectID}#, Creation handle abandoned."); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(CREATION_HANDLE, _waitHandles.CreationSemaphore); default: - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, WaitForMultipleObjects={waitResult}\n"); + _log.PoolerTrace($" {ObjectID}#, WaitForMultipleObjects={waitResult}"); Interlocked.Decrement(ref _waitCount); throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult); } @@ -1580,7 +1581,7 @@ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal o internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) { PerformanceCounters.SoftConnectsPerSecond.Increment(); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, replacing connection.\n"); + _log.PoolerTrace($" {ObjectID}#, replacing connection."); DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); @@ -1623,7 +1624,7 @@ private DbConnectionInternal GetFromGeneralPool() if (null != obj) { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from general pool.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from general pool."); PerformanceCounters.NumberOfFreeConnections.Decrement(); } return (obj); @@ -1640,7 +1641,7 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac if (null != obj) { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from transacted pool.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from transacted pool."); PerformanceCounters.NumberOfFreeConnections.Decrement(); if (obj.IsTransactionRoot) @@ -1651,14 +1652,14 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac } catch { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); DestroyObject(obj); throw; } } else if (!obj.IsConnectionAlive()) { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); DestroyObject(obj); obj = null; } @@ -1675,7 +1676,7 @@ private void PoolCreateRequest(object state) // creation mutex has not been obtained - var scopeID = SqlClientEventSource._log.PoolerScopeEnter($" {ObjectID}#\n"); + var scopeID = _log.PoolerScopeEnter($" {ObjectID}#"); try { @@ -1761,7 +1762,7 @@ private void PoolCreateRequest(object state) else { // trace waitResult and ignore the failure - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called WaitForSingleObject failed {waitResult}"); + _log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called WaitForSingleObject failed {waitResult}"); } } catch (Exception e) @@ -1775,7 +1776,7 @@ private void PoolCreateRequest(object state) // Now that CreateObject can throw, we need to catch the exception and discard it. // There is no further action we can take beyond tracing. The error will be // thrown to the user the next time they request a connection. - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called CreateConnection which threw an exception: {e}"); + _log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called CreateConnection which threw an exception: {e}"); } finally { @@ -1795,7 +1796,7 @@ private void PoolCreateRequest(object state) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1809,7 +1810,7 @@ internal void PutNewObject(DbConnectionInternal obj) // against checked bits. // Debug.Assert(obj.CanBePooled, "non-poolable object in pool"); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Pushing to general pool.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Pushing to general pool."); _stackNew.Push(obj); _waitHandles.PoolSemaphore.Release(1); @@ -1859,7 +1860,7 @@ internal void PutObjectFromTransactedPool(DbConnectionInternal obj) // that is using the connection, and that all pre-push logic has been // done and all transactions are ended. - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Transaction has ended.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Transaction has ended."); if (_state == State.Running && obj.CanBePooled) { @@ -1885,7 +1886,7 @@ private bool ReclaimEmancipatedObjects() { bool emancipatedObjectFound = false; - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#\n"); + _log.PoolerTrace($" {ObjectID}#"); List reclaimedObjects = new List(); int count; @@ -1939,7 +1940,7 @@ private bool ReclaimEmancipatedObjects() { DbConnectionInternal obj = reclaimedObjects[i]; - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Reclaiming.\n"); + _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Reclaiming."); PerformanceCounters.NumberOfReclaimedConnections.Increment(); emancipatedObjectFound = true; @@ -1952,7 +1953,7 @@ private bool ReclaimEmancipatedObjects() internal void Startup() { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, CleanupWait={_cleanupWait}\n"); + _log.PoolerTrace($" {ObjectID}#, CleanupWait={_cleanupWait}"); _cleanupTimer = CreateCleanupTimer(); if (NeedToReplenish) @@ -1963,7 +1964,7 @@ internal void Startup() internal void Shutdown() { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#\n"); + _log.PoolerTrace($" {ObjectID}#\n"); _state = State.ShuttingDown; @@ -1986,7 +1987,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern Debug.Assert(null != transactedObject, "null transactedObject?"); // Note: connection may still be associated with transaction due to Explicit Unbinding requirement. - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed\n"); + _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed"); // called by the internal connection when it get's told that the // transaction is completed. We tell the transacted pool to remove diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs index fbccb7b5f0..4506ee0b14 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -7,7 +7,7 @@ namespace Microsoft.Data.ProviderBase using System.Collections.Concurrent; using System.Diagnostics; using Microsoft.Data.Common; - using Microsoft.Data.SqlClient; + using static Microsoft.Data.SqlClient.SqlClientEventSource; // set_ConnectionString calls DbConnectionFactory.GetConnectionPoolGroup // when not found a new pool entry is created and potentially added @@ -272,7 +272,11 @@ private bool MarkPoolGroupAsActive() if (PoolGroupStateIdle == _state) { _state = PoolGroupStateActive; - SqlClientEventSource._log.Trace($" {ObjectID}#, Active\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Active"); + } } return (PoolGroupStateActive == _state); } @@ -334,14 +338,23 @@ internal bool Prune() if (PoolGroupStateActive == _state) { _state = PoolGroupStateIdle; - SqlClientEventSource._log.Trace($" {ObjectID}#, Idle\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Idle"); + } } else if (PoolGroupStateIdle == _state) { _state = PoolGroupStateDisabled; - SqlClientEventSource._log.Trace($" {ObjectID}#, Disabled\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Disabled"); + } } } + return (PoolGroupStateDisabled == _state); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs index 2eebf9569c..e00bea8807 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs @@ -12,6 +12,7 @@ namespace Microsoft.Data.SqlClient using System.Threading; using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; + using static Microsoft.Data.SqlClient.SqlClientEventSource; using SysTx = System.Transactions; public sealed partial class SqlConnection : DbConnection @@ -86,7 +87,11 @@ internal DbConnectionOptions ConnectionOptions private string ConnectionString_Get() { - SqlClientEventSource._log.Trace($" {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#"); + } + bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions connectionOptions = UserConnectionOptions; return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); @@ -131,7 +136,11 @@ private void ConnectionString_Set(DbConnectionPoolKey key) } string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); - SqlClientEventSource._log.Trace($" {ObjectID}#, '{cstr}'\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, '{cstr}'"); + } } internal DbConnectionInternal InnerConnection @@ -179,13 +188,16 @@ internal void Abort(Exception e) // NOTE: we put the tracing last, because the ToString() calls (and // the SqlClientEventSource.Log.Trace, for that matter) have no reliability contract and // will end the reliable try... - if (e is OutOfMemoryException) - { - SqlClientEventSource._log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {"OutOfMemory"}\n"); - } - else + if (_log.IsTraceEnabled()) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {e.ToString()}\n"); + if (e is OutOfMemoryException) + { + _log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {"OutOfMemory"}"); + } + else + { + _log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {e.ToString()}"); + } } } @@ -198,7 +210,7 @@ internal void AddWeakReference(object value, int tag) override protected DbCommand CreateDbCommand() { DbCommand command = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#\n"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); try { DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; @@ -207,7 +219,7 @@ override protected DbCommand CreateDbCommand() } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } return command; } @@ -244,7 +256,11 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)); permissionSet.Demand(); - SqlClientEventSource._log.Trace($" {ObjectID}#, Connection enlisting in a transaction.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Connection enlisting in a transaction."); + } + SysTx.Transaction indigoTransaction = null; if (null != transaction) @@ -270,7 +286,10 @@ override public void EnlistTransaction(SysTx.Transaction transaction) { SqlConnection.ExecutePermission.Demand(); - SqlClientEventSource._log.Trace($" {ObjectID}#, Connection enlisting in a transaction.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Connection enlisting in a transaction."); + } // If we're currently enlisted in a transaction and we were called // on the EnlistTransaction method (Whidbey) we're not allowed to diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs index 4d4ebf0cf7..4acb7407ef 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs @@ -13,6 +13,7 @@ using System.Text; using System.Threading; using Microsoft.Data.SqlClient; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data { @@ -73,7 +74,10 @@ static IntPtr UserInstanceDLLHandle SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle); if (s_userInstanceDLLHandle != IntPtr.Zero) { - SqlClientEventSource._log.Trace(" LocalDB - handle obtained"); + if (_log.IsTraceEnabled()) + { + _log.Trace(" LocalDB - handle obtained"); + } } else { @@ -117,7 +121,12 @@ static LocalDBCreateInstanceDelegate LocalDBCreateInstance if (functionAddr == IntPtr.Zero) { int hResult = Marshal.GetLastWin32Error(); - SqlClientEventSource._log.Trace($" GetProcAddress for LocalDBCreateInstance error 0x{hResult}"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" GetProcAddress for LocalDBCreateInstance error 0x{hResult}"); + } + throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); } s_localDBCreateInstance = (LocalDBCreateInstanceDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBCreateInstanceDelegate)); @@ -159,7 +168,12 @@ static LocalDBFormatMessageDelegate LocalDBFormatMessage { // SNI checks for LocalDBFormatMessage during DLL loading, so it is practically impossibe to get this error. int hResult = Marshal.GetLastWin32Error(); - SqlClientEventSource._log.Trace($" GetProcAddress for LocalDBFormatMessage error 0x{hResult}"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" GetProcAddress for LocalDBFormatMessage error 0x{hResult}"); + } + throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); } s_localDBFormatMessage = (LocalDBFormatMessageDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBFormatMessageDelegate)); @@ -314,7 +328,12 @@ internal static void CreateLocalDBInstance(string instance) } } else - SqlClientEventSource._log.Trace(" No system.data.localdb section found in configuration"); + { + if (_log.IsTraceEnabled()) + { + _log.Trace(" No system.data.localdb section found in configuration"); + } + } s_configurableInstances = tempConfigurableInstances; } } @@ -340,10 +359,21 @@ internal static void CreateLocalDBInstance(string instance) // LocalDBCreateInstance is thread- and cross-process safe method, it is OK to call from two threads simultaneously int hr = LocalDBCreateInstance(instanceInfo.version, instance, flags: 0); - SqlClientEventSource._log.Trace($" Starting creation of instance {instance} version {instanceInfo.version}"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" Starting creation of instance {instance} version {instanceInfo.version}"); + } + if (hr < 0) + { throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_CreateFailed"), instance: instance, localDbError: hr); - SqlClientEventSource._log.Trace($" Finished creation of instance {instance}"); + } + + if (_log.IsTraceEnabled()) + { + _log.Trace($" Finished creation of instance {instance}"); + } instanceInfo.created = true; // mark instance as created } // CreateLocalDbInstance } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs index 549b64498d..f2e1854a88 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient.Server { @@ -266,12 +267,13 @@ internal override void DefaultDatabaseChanged(string databaseName) // Called for messages and errors (ERROR and INFO tokens) internal override void MessagePosted(int number, byte state, byte errorClass, string server, string message, string procedure, int lineNumber) { - var serverValue = (null != server) ? server : ""; - var messageBody = (null != message) ? message : ""; - var proc = (null != procedure) ? procedure : ""; if (null == _parent) { - SqlClientEventSource._log.Trace($" {0}#, number={number} state={state} errorClass={errorClass} server='{serverValue}' message='{messageBody}' procedure='{proc}' linenumber={lineNumber}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {0}#, number={number} state={state} errorClass={errorClass} server='{server ?? ""}' message='{message ?? ""}' procedure='{procedure ?? ""}' linenumber={lineNumber}."); + } + SqlError error = new SqlError(number, state, errorClass, server, message, procedure, lineNumber); if (error.Class < TdsEnums.MIN_ERROR_CLASS) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index be6978029e..bd49a6cb6c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs @@ -15,6 +15,7 @@ using System.Threading.Tasks; using System.Xml; using Microsoft.Data.Common; +using static Microsoft.Data.SqlClient.SqlClientEventSource; // todo list: // * An ID column need to be ignored - even if there is an association @@ -593,8 +594,16 @@ private string CreateInitialQuery() private Task CreateAndExecuteInitialQueryAsync(out BulkCopySimpleResultSet result) { string TDSCommand = CreateInitialQuery(); - SqlClientEventSource._log.Trace($" Initial Query: '{TDSCommand}' \n"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); + + if (_log.IsTraceEnabled()) + { + if (_log.IsTraceEnabled()) + { + _log.Trace($" Initial Query: '{TDSCommand}'"); + } + } + + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls"); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); @@ -885,7 +894,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i // private Task SubmitUpdateBulkCommand(string TDSCommand) { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); @@ -2516,7 +2525,11 @@ private void CheckAndRaiseNotification() // it's also the user's chance to cause an exception ... _stateObj.BcpLock = true; abortOperation = FireRowsCopiedEvent(_rowsCopied); - SqlClientEventSource._log.Trace(" \n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace(""); + } // just in case some pathological person closes the target connection ... if (ConnectionState.Open != _connection.State) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 046341b98c..e9d16be506 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -44,13 +44,12 @@ public class Keywords internal const EventKeywords StringPrintOut = (EventKeywords)0x1000; // Integer 4096 } + [NonEvent] + internal bool IsTraceEnabled() => _log.IsEnabled(EventLevel.Informational, Keywords.Trace); + [Event(TraceEventId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] internal void Trace(string message) { - if (!_log.IsEnabled(EventLevel.Informational, Keywords.Trace)) - { - return; - } WriteEvent(TraceEventId, message); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs index aaa535aea6..189a518aa2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -17,13 +19,19 @@ internal enum LogLevel /// public void LogInfo(string type, string method, string message) { - SqlClientEventSource._log.Trace($"{message}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($"{message}"); + } } /// public void LogError(string type, string method, string message) { - SqlClientEventSource._log.Trace($"{message}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($"{message}"); + } } /// diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index 5d037b1f1a..676596f489 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -24,6 +24,7 @@ using Microsoft.Data.Sql; using Microsoft.Data.SqlClient.Server; using SysTx = System.Transactions; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -346,7 +347,11 @@ internal CommandEventSink(SqlCommand command) : base() internal override void StatementCompleted(int rowsAffected) { - SqlClientEventSource._log.Trace($" {_command.ObjectID}#, rowsAffected={rowsAffected}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {_command.ObjectID}#, rowsAffected={rowsAffected}."); + } + _command.InternalRecordsAffected = rowsAffected; // UNDONE: need to fire events back to user code, but this may be called @@ -358,20 +363,27 @@ internal override void StatementCompleted(int rowsAffected) internal override void BatchCompleted() { - SqlClientEventSource._log.Trace($" {_command.ObjectID}#.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {_command.ObjectID}#."); + } } internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 parameterValues) { var metaDataLength = (null != metaData) ? metaData.Length : -1; - SqlClientEventSource._log.Trace($" {_command.ObjectID}# metaData.Length={metaDataLength}.\n"); - if (null != metaData) + if (_log.IsTraceEnabled()) + { + _log.Trace($" {_command.ObjectID}# metaData.Length={metaDataLength}."); + } + + if (null != metaData && _log.IsTraceEnabled()) { for (int i = 0; i < metaData.Length; i++) { - SqlClientEventSource._log.Trace($" {_command.ObjectID}#, metaData[{i}] is {metaData[i].GetType().ToString()}{metaData[i].TraceString()}\n"); + _log.Trace($" {_command.ObjectID}#, metaData[{i}] is {metaData[i].GetType().ToString()}{metaData[i].TraceString()}"); } } @@ -381,10 +393,11 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter parameterValues, int ordinal) { - if (null != metaData) + if (null != metaData && _log.IsTraceEnabled()) { - SqlClientEventSource._log.Trace($" {_command.ObjectID}#, metaData[{ordinal}] is {metaData.GetType().ToString()}{ metaData.TraceString()}\n"); + _log.Trace($" {_command.ObjectID}#, metaData[{ordinal}] is {metaData.GetType().ToString()}{ metaData.TraceString()}"); } + Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion); _command.OnParameterAvailableSmi(metaData, parameterValues, ordinal); } @@ -570,7 +583,11 @@ private SqlCommand(SqlCommand from) : this() _activeConnection = value; // UNDONE: Designers need this setter. Should we block other scenarios? var _activeConnectionObjectID = (null != value) ? value.ObjectID : -1; - SqlClientEventSource._log.Trace($" {ObjectID}#, {_activeConnectionObjectID}#\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, {_activeConnectionObjectID}#"); + } } } @@ -648,13 +665,16 @@ public SqlNotificationRequest Notification } set { - SqlClientEventSource._log.Trace($" {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#"); + } + _sqlDep = null; _notification = value; } } - internal SqlStatistics Statistics { get @@ -699,7 +719,10 @@ internal SqlStatistics Statistics } // TODO: Add objid here - SqlClientEventSource._log.Trace($" {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#"); + } _transaction = value; } } @@ -734,10 +757,12 @@ override public string CommandText } set { + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#"); + } - SqlClientEventSource._log.Trace($" {ObjectID}# '"); - SqlClientEventSource._log.PutStr(value); // Use PutStr to write out entire string - SqlClientEventSource._log.Trace("'\n"); + _log.PutStr(value); // Use PutStr to write out entire string if (0 != ADP.SrcCompare(_commandText, value)) { @@ -775,11 +800,16 @@ override public int CommandTimeout } set { - SqlClientEventSource._log.Trace($" {ObjectID}#, {value}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, {value}"); + } + if (value < 0) { throw ADP.InvalidCommandTimeout(value); } + if (value != _commandTimeout) { PropertyChanging(); @@ -819,7 +849,10 @@ override public CommandType CommandType } set { - SqlClientEventSource._log.Trace($" {ObjectID}#, {(int)value}{_commandType}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, {(int)value}{_commandType}"); + } if (_commandType != value) { switch (value) @@ -962,7 +995,11 @@ internal void OnStatementCompleted(int recordCount) { try { - SqlClientEventSource._log.Trace($" {ObjectID}#, recordCount={recordCount}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, recordCount={recordCount}"); + } + handler(this, new StatementCompletedEventArgs(recordCount)); } catch (Exception e) @@ -1000,8 +1037,8 @@ override public void Prepare() } SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); statistics = SqlStatistics.StartTimer(Statistics); // only prepare if batch with parameters @@ -1102,7 +1139,7 @@ override public void Prepare() } SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } private void InternalPrepare() @@ -1166,7 +1203,10 @@ internal void Unprepare() } _cachedMetaData = null; - SqlClientEventSource._log.Trace($" {ObjectID}#, Command unprepared.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Command unprepared."); + } } // Cancel is supposed to be multi-thread safe. @@ -1176,8 +1216,8 @@ internal void Unprepare() /// override public void Cancel() { - var scopeID = SqlClientEventSource._log.ScopeEnter($"< sc.SqlCommand.Cancel | API > {ObjectID}#"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + var scopeID = _log.ScopeEnter($"< sc.SqlCommand.Cancel | API > {ObjectID}#"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}"); SqlStatistics statistics = null; try @@ -1296,7 +1336,7 @@ override public void Cancel() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1339,8 +1379,8 @@ override public object ExecuteScalar() _pendingCancel = false; SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); bool success = false; int? sqlExceptionNumber = null; @@ -1362,7 +1402,7 @@ override public object ExecuteScalar() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1407,8 +1447,8 @@ override public int ExecuteNonQuery() _pendingCancel = false; SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); bool success = false; int? sqlExceptionNumber = null; try @@ -1428,7 +1468,7 @@ override public int ExecuteNonQuery() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1444,7 +1484,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) _pendingCancel = false; SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1454,7 +1494,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1470,7 +1510,7 @@ public IAsyncResult BeginExecuteNonQuery() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); return BeginExecuteNonQueryInternal(0, callback, stateObject, 0, inRetry: false); } @@ -1696,7 +1736,7 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) } finally { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); } } @@ -1714,7 +1754,7 @@ private void ThrowIfReconnectionHasBeenCanceled() private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -1974,7 +2014,12 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st else { // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); - SqlClientEventSource._log.Trace($" {ObjectID}#, Command executed as RPC.\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Command executed as RPC."); + } + SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, methodName, completion, timeout, out task, out usedCache, asyncWrite, inRetry); if (null != reader) { @@ -2026,8 +2071,8 @@ public XmlReader ExecuteXmlReader() _pendingCancel = false; SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); bool success = false; int? sqlExceptionNumber = null; try @@ -2050,7 +2095,7 @@ public XmlReader ExecuteXmlReader() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -2067,7 +2112,7 @@ public IAsyncResult BeginExecuteXmlReader() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); return BeginExecuteXmlReaderInternal(CommandBehavior.SequentialAccess, callback, stateObject, 0, inRetry: false); } @@ -2220,13 +2265,13 @@ public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) } finally { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); } } private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2345,7 +2390,7 @@ public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObjec /// override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); return ExecuteReader(behavior, ADP.ExecuteReader); } @@ -2353,8 +2398,8 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) new public SqlDataReader ExecuteReader() { SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -2363,22 +2408,22 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } /// new public SqlDataReader ExecuteReader(CommandBehavior behavior) { - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#, behavior={(int)behavior}"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {SqlClientEventSource._log.Guid}\n"); + var scopeID = _log.ScopeEnter($" {ObjectID}#, behavior={(int)behavior}"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {_log.Guid}\n"); try { return ExecuteReader(behavior, ADP.ExecuteReader); } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -2393,7 +2438,7 @@ public IAsyncResult BeginExecuteReader(CommandBehavior behavior) [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior) { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {_log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); return BeginExecuteReaderInternal(behavior, callback, stateObject, 0, inRetry: false); } @@ -2475,13 +2520,13 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) } finally { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); } } private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2883,7 +2928,7 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -2969,7 +3014,7 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b new public Task ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {_log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3104,7 +3149,7 @@ public Task ExecuteXmlReaderAsync() public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken) { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3711,7 +3756,12 @@ private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, b // no parameters are sent over // no data reader is returned // use this overload for "batch SQL" tds token type - SqlClientEventSource._log.Trace($" {ObjectID}#, Command executed as SQLBATCH.\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Command executed as SQLBATCH."); + } + Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(this.CommandText, timeout, this.Notification, _stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -3773,7 +3823,10 @@ private void RunExecuteNonQuerySmi(bool sendToPipe) SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - SqlClientEventSource._log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{(int)CommandBehavior.Default}, cmdBehavior=%d.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, cmdBehavior={(int)CommandBehavior.Default}."); + } if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { @@ -5250,11 +5303,12 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // Send over SQL Batch command if we are not a stored proc and have no parameters // MDAC BUG #'s 73776 & 72101 Debug.Assert(!IsUserPrepared, "CommandType.Text with no params should not be prepared!"); - if (returnStream) + if (returnStream && _log.IsTraceEnabled()) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Command executed as SQLBATCH.\n"); + _log.Trace($" {ObjectID}#, Command executed as SQLBATCH."); } string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior); + //If the query requires enclave computations, pass the enclavepackage in the SQLBatch TDS stream if (requiresEnclaveComputations) { @@ -5314,9 +5368,9 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // if shiloh, then set NOMETADATA_UNLESSCHANGED flag if (_activeConnection.IsShiloh) rpc.options = TdsEnums.RPC_NOMETADATA; - if (returnStream) + if (returnStream && _log.IsTraceEnabled()) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Command executed as RPC.\n"); + _log.Trace($" {ObjectID}#, Command executed as RPC."); } // TODO: Medusa: Unprepare only happens for SQL 7.0 which may be broken anyway (it's not re-prepared). Consider removing the reset here if we're really dropping 7.0 support. @@ -5337,9 +5391,9 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // then batch sql them over. This is inefficient (3 round trips) but the only way we can get metadata only from // a stored proc optionSettings = GetSetOptionsString(cmdBehavior); - if (returnStream) + if (returnStream && _log.IsTraceEnabled()) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Command executed as RPC.\n"); + _log.Trace($" {ObjectID}#, Command executed as RPC."); } // turn set options ON if (null != optionSettings) @@ -5434,7 +5488,10 @@ private SqlDataReader RunExecuteReaderSmi(CommandBehavior cmdBehavior, RunBehavi SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - SqlClientEventSource._log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, commandBehavior={(int)cmdBehavior}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, commandBehavior={(int)cmdBehavior}."); + } if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { @@ -5654,7 +5711,11 @@ private void NotifyDependency() public SqlCommand Clone() { SqlCommand clone = new SqlCommand(this); - SqlClientEventSource._log.Trace($" {ObjectID}#, clone={clone.ObjectID}#\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, clone={clone.ObjectID}#"); + } return clone; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index 375194228c..b543c5726d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -10,6 +10,7 @@ using System.Text; using System.Text.RegularExpressions; using Microsoft.Data.Common; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -129,7 +130,10 @@ internal int ObjectID internal void Append(SqlCommand command) { ADP.CheckArgumentNull(command, "command"); - SqlClientEventSource._log.Trace($" {ObjectID}#, command={command.ObjectID}, parameterCount={command.Parameters.Count}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, command={command.ObjectID}, parameterCount={command.Parameters.Count}"); + } string cmdText = command.CommandText; if (ADP.IsEmpty(cmdText)) @@ -264,7 +268,11 @@ internal static void BuildStoredProcedureName(StringBuilder builder, string part internal void Clear() { - SqlClientEventSource._log.Trace($" {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#"); + } + DbCommand batchCommand = BatchCommand; if (null != batchCommand) { @@ -280,7 +288,11 @@ internal void Clear() internal void Dispose() { - SqlClientEventSource._log.Trace($" {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#"); + } + SqlCommand command = _batchCommand; _commandList = null; _batchCommand = null; @@ -295,7 +307,7 @@ internal int ExecuteNonQuery() { SqlConnection.ExecutePermission.Demand(); - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); try { if (Connection.IsContextConnection) @@ -315,7 +327,7 @@ internal int ExecuteNonQuery() } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index d02d82ce26..8bde1b76cd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -28,6 +28,7 @@ using System.Threading.Tasks; using Microsoft.Data.ProviderBase; using Microsoft.Data.SqlClient.Server; +using static Microsoft.Data.SqlClient.SqlClientEventSource; [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Data.DataSetExtensions, PublicKey=" + Microsoft.Data.SqlClient.AssemblyRef.EcmaPublicKeyFull)] // DevDiv Bugs 92166 @@ -1102,7 +1103,7 @@ public SqlTransaction BeginTransaction(string transactionName) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#, isolationLevel={(int)isolationLevel}"); + var scopeID = _log.ScopeEnter($" {ObjectID}#, isolationLevel={(int)isolationLevel}"); try { @@ -1118,7 +1119,7 @@ override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLeve } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1128,7 +1129,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam WaitForPendingReconnection(); SqlStatistics statistics = null; string xactName = ADP.IsEmpty(transactionName) ? "None" : transactionName; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#, iso={(int)iso}, transactionName='{xactName}'\n"); + var scopeID = _log.ScopeEnter($" {ObjectID}#, iso={(int)iso}, transactionName='{xactName}'\n"); try { @@ -1156,7 +1157,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); SqlStatistics.StopTimer(statistics); } } @@ -1166,7 +1167,7 @@ override public void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -1259,8 +1260,8 @@ void CloseInnerConnection() /// override public void Close() { - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); try { SqlStatistics statistics = null; @@ -1342,7 +1343,7 @@ override public void Close() { SqlDebugContext sdc = _sdc; _sdc = null; - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); if (sdc != null) { sdc.Dispose(); @@ -1395,8 +1396,8 @@ public void EnlistDistributedTransaction(System.EnterpriseServices.ITransaction /// override public void Open() { - var scopeID = SqlClientEventSource._log.ScopeEnter($" ObjectID: {ObjectID}, ActivityID {SqlClientEventSource._log.Guid}\n"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); + var scopeID = _log.ScopeEnter($" ObjectID: {ObjectID}, ActivityID {_log.Guid}\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); try { @@ -1430,7 +1431,7 @@ override public void Open() } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1464,7 +1465,10 @@ private async Task ReconnectAsync(int timeout) { if (ctoken.IsCancellationRequested) { - SqlClientEventSource._log.Trace($" Orginal ClientConnectionID: {_originalConnectionId.ToString()} - reconnection cancelled.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Orginal ClientConnectionID: {_originalConnectionId.ToString()} - reconnection cancelled."); + } return; } try @@ -1485,15 +1489,27 @@ private async Task ReconnectAsync(int timeout) _impersonateIdentity = null; ForceNewConnection = false; } - SqlClientEventSource._log.Trace($" Reconnection suceeded. ClientConnectionID {_originalConnectionId.ToString()} -> {ClientConnectionId.ToString()} \n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" Reconnection suceeded. ClientConnectionID {_originalConnectionId.ToString()} -> {ClientConnectionId.ToString()}"); + } return; } catch (SqlException e) { - SqlClientEventSource._log.Trace($" Orginal ClientConnectionID {_originalConnectionId} - reconnection attempt failed error {e.Message}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Orginal ClientConnectionID {_originalConnectionId} - reconnection attempt failed error {e.Message}"); + } + if (attempt == retryCount - 1) { - SqlClientEventSource._log.Trace($" Orginal ClientConnectionID {_originalConnectionId.ToString()} - give up reconnection\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Orginal ClientConnectionID {_originalConnectionId.ToString()} - give up reconnection"); + } + throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) @@ -1559,7 +1575,11 @@ internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) if (cData._unrecoverableStatesCount == 0) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; - SqlClientEventSource._log.Trace($" Connection ClientConnectionID {_originalConnectionId.ToString()} is invalid, reconnecting\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" Connection ClientConnectionID {_originalConnectionId.ToString()} is invalid, reconnecting"); + } _recoverySessionData = cData; if (beforeDisconnect != null) { @@ -1651,8 +1671,8 @@ void CancelOpenAndWait() /// public override Task OpenAsync(CancellationToken cancellationToken) { - var scopeID = SqlClientEventSource._log.PoolerScopeEnter($" {ObjectID}#"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); + var scopeID = _log.PoolerScopeEnter($" {ObjectID}#"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); try { @@ -1729,7 +1749,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1750,7 +1770,10 @@ public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource retryTask) { - SqlClientEventSource._log.Trace($" {_parent.ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {_parent.ObjectID}#"); + } _registration.Dispose(); try { @@ -2097,7 +2120,11 @@ internal void OnError(SqlException exception, bool breakConnection, Action {ObjectID}#, Connection broken.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Connection broken."); + } + Close(); } }; @@ -2106,7 +2133,10 @@ internal void OnError(SqlException exception, bool breakConnection, Action {ObjectID}#, Connection broken.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Connection broken."); + } Close(); } } @@ -2214,7 +2244,11 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) Debug.Assert(null != imevent, "null SqlInfoMessageEventArgs"); var imeventValue = (null != imevent) ? imevent.Message : ""; - SqlClientEventSource._log.Trace($" {ObjectID}#, Message='{imeventValue}'\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Message='{imeventValue}'"); + } SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage]; if (null != handler) @@ -2428,8 +2462,8 @@ private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, s /// public static void ChangePassword(string connectionString, string newPassword) { - var scopeID = SqlClientEventSource._log.ScopeEnter(""); - SqlClientEventSource._log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); + var scopeID = _log.ScopeEnter(""); + _log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); try { if (ADP.IsEmpty(connectionString)) @@ -2468,15 +2502,15 @@ public static void ChangePassword(string connectionString, string newPassword) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } /// public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { - var scopeID = SqlClientEventSource._log.ScopeEnter(""); - SqlClientEventSource._log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); + var scopeID = _log.ScopeEnter(""); + _log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); try { if (ADP.IsEmpty(connectionString)) @@ -2538,7 +2572,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -2644,9 +2678,9 @@ private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) Debug.Assert(TypeSystemAssemblyVersion != null, "TypeSystemAssembly should be set !"); if (string.Compare(asmRef.Name, "Microsoft.SqlServer.Types", StringComparison.OrdinalIgnoreCase) == 0) { - if (asmRef.Version != TypeSystemAssemblyVersion) + if (asmRef.Version != TypeSystemAssemblyVersion && _log.IsTraceEnabled()) { - SqlClientEventSource._log.Trace($" SQL CLR type version change: Server sent {asmRef.Version.ToString()}, client will instantiate {TypeSystemAssemblyVersion.ToString()}"); + _log.Trace($" SQL CLR type version change: Server sent {asmRef.Version.ToString()}, client will instantiate {TypeSystemAssemblyVersion.ToString()}"); } asmRef.Version = TypeSystemAssemblyVersion; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs index fb23107e49..807959fa02 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs @@ -12,6 +12,7 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; using Microsoft.Data.SqlClient.Server; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -192,7 +193,11 @@ override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions { connectionTimeout *= 10; } - SqlClientEventSource._log.Trace($"Set connection pool CreateTimeout={connectionTimeout} when AD Interactive is in use.\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($"Set connection pool CreateTimeout={connectionTimeout} when AD Interactive is in use."); + } } poolingOptions = new DbConnectionPoolGroupOptions( diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs index 55ee60a23e..3af5b4261e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs @@ -4,6 +4,7 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -55,7 +56,11 @@ internal void AliasCheck(string server) } else if (_alias != server) { - SqlClientEventSource._log.Trace($" alias change detected. Clearing PoolGroup\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" alias change detected. Clearing PoolGroup"); + } + base.PoolGroup.Clear(); _alias = server; } @@ -99,7 +104,11 @@ internal void FailoverCheck(SqlInternalConnection connection, bool actualUseFail if (UseFailoverPartner != actualUseFailoverPartner) { // TODO: will connections in progress somehow be active for two different datasources? - SqlClientEventSource._log.Trace($" Failover detected. failover partner='{actualFailoverPartner}'. Clearing PoolGroup\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Failover detected. failover partner='{actualFailoverPartner}'. Clearing PoolGroup"); + } + base.PoolGroup.Clear(); _useFailoverPartner = actualUseFailoverPartner; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index a89af98830..660ce00c4d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -8,6 +8,7 @@ using System.Data.Common; using System.Diagnostics; using Microsoft.Data.Common; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -142,7 +143,11 @@ override public int UpdateBatchSize throw ADP.ArgumentOutOfRange("UpdateBatchSize"); } _updateBatchSize = value; - SqlClientEventSource._log.Trace($" {ObjectID}#, {value}\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, {value}"); + } } } @@ -249,7 +254,7 @@ override protected RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, override protected int ExecuteBatch() { Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); return _commandSet.ExecuteNonQuery(); } @@ -272,7 +277,10 @@ override protected bool GetBatchedRecordsAffected(int commandIdentifier, out int /// override protected void InitializeBatching() { - SqlClientEventSource._log.Trace($" {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#"); + } _commandSet = new SqlCommandSet(); SqlCommand command = SelectCommand; if (null == command) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs index 92a3bdc43f..37433bc318 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -21,6 +21,7 @@ using Microsoft.Data.SqlClient.DataClassification; using Microsoft.Data.SqlClient.Server; using Microsoft.Data.SqlTypes; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -939,7 +940,7 @@ private void CleanPartialReadReliable() override public void Close() { SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1025,7 +1026,7 @@ override public void Close() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1669,7 +1670,7 @@ override public int GetProviderSpecificValues(object[] values) override public DataTable GetSchemaTable() { SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1692,7 +1693,7 @@ override public DataTable GetSchemaTable() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -3600,7 +3601,7 @@ override public bool NextResult() private bool TryNextResult(out bool more) { SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -3778,7 +3779,7 @@ private bool TryNextResult(out bool more) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -3806,7 +3807,7 @@ override public bool Read() private bool TryReadInternal(bool setTimeout, out bool more) { SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -4008,7 +4009,7 @@ private bool TryReadInternal(bool setTimeout, out bool more) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -4473,7 +4474,7 @@ private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateO // broken connection, so check state first. if (parser.State == TdsParserState.OpenLoggedIn) { - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); Task executeTask = parser.TdsExecuteSQLBatch(_resetOptionsString, (_command != null) ? _command.CommandTimeout : 0, null, stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -4785,7 +4786,7 @@ private void AssertReaderState(bool requireData, bool permitAsync, int? columnIn /// public override Task NextResultAsync(CancellationToken cancellationToken) { - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); try { @@ -4831,7 +4832,10 @@ public override Task NextResultAsync(CancellationToken cancellationToken) { if (t != null) { - SqlClientEventSource._log.Trace($" attempt retry {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" attempt retry {ObjectID}#"); + } PrepareForAsyncContinuation(); } @@ -4849,7 +4853,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -4913,7 +4917,11 @@ internal Task GetBytesAsync(int i, byte[] buffer, int index, int length, in { if (t != null) { - SqlClientEventSource._log.Trace($" attempt retry {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" attempt retry {ObjectID}#"); + } + PrepareForAsyncContinuation(); } @@ -5084,7 +5092,7 @@ private Task GetBytesAsyncReadDataStage(int i, byte[] buffer, int index, in /// public override Task ReadAsync(CancellationToken cancellationToken) { - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); try { @@ -5205,7 +5213,11 @@ public override Task ReadAsync(CancellationToken cancellationToken) { if (t != null) { - SqlClientEventSource._log.Trace($" attempt retry {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" attempt retry {ObjectID}#"); + } + PrepareForAsyncContinuation(); } @@ -5244,7 +5256,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs index 7d892d544c..c91a1dbdc6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs @@ -15,6 +15,8 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; using Microsoft.Data.SqlClient.Server; +using static Microsoft.Data.SqlClient.SqlClientEventSource; + using Microsoft.Data.SqlTypes; namespace Microsoft.Data.SqlClient @@ -374,7 +376,7 @@ public override void Close() private void CloseInternal(bool closeConnection) { - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); bool processFinallyBlock = true; try { @@ -410,7 +412,7 @@ private void CloseInternal(bool closeConnection) Connection.Close(); } - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } } @@ -433,7 +435,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) { - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); try { _hasRows = false; @@ -466,7 +468,7 @@ internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -486,7 +488,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) internal unsafe bool InternalRead(bool ignoreNonFatalErrors) { - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); try { // Don't move unless currently in results. @@ -525,7 +527,7 @@ internal unsafe bool InternalRead(bool ignoreNonFatalErrors) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1316,13 +1318,18 @@ internal ReaderEventSink(SqlDataReaderSmi reader, SmiEventSink parent) internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIsRow) { var mdLength = (null != md) ? md.Length : -1; - SqlClientEventSource._log.Trace($" {reader.ObjectID}#, md.Length={mdLength} nextEventIsRow={nextEventIsRow}.\n"); - if (null != md) + if (_log.IsTraceEnabled()) { - for (int i = 0; i < md.Length; i++) + _log.Trace($" {reader.ObjectID}#, md.Length={mdLength} nextEventIsRow={nextEventIsRow}."); + + + if (null != md) { - SqlClientEventSource._log.Trace($" {reader.ObjectID}#, metaData[{i}] is {md[i].GetType().ToString()}{md[i].TraceString()}\n"); + for (int i = 0; i < md.Length; i++) + { + _log.Trace($" {reader.ObjectID}#, metaData[{i}] is {md[i].GetType().ToString()}{md[i].TraceString()}"); + } } } this.reader.MetaDataAvailable(md, nextEventIsRow); @@ -1331,25 +1338,37 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs // Obsolete V2- method internal override void RowAvailable(ITypedGetters row) { - SqlClientEventSource._log.Trace($" {reader.ObjectID}# (v2).\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {reader.ObjectID}# (v2)."); + } this.reader.RowAvailable(row); } internal override void RowAvailable(ITypedGettersV3 row) { - SqlClientEventSource._log.Trace($" {reader.ObjectID}# (ITypedGettersV3).\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {reader.ObjectID}# (ITypedGettersV3)."); + } this.reader.RowAvailable(row); } internal override void RowAvailable(SmiTypedGetterSetter rowData) { - SqlClientEventSource._log.Trace($" {reader.ObjectID}# (SmiTypedGetterSetter).\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {reader.ObjectID}# (SmiTypedGetterSetter)."); + } this.reader.RowAvailable(rowData); } internal override void StatementCompleted(int recordsAffected) { - SqlClientEventSource._log.Trace($" {reader.ObjectID}# recordsAffected= {recordsAffected}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {reader.ObjectID}# recordsAffected= {recordsAffected}."); + } // devnote: relies on SmiEventSink_Default to pass event to parent // Both command and reader care about StatementCompleted, but for different reasons. @@ -1360,7 +1379,10 @@ internal override void StatementCompleted(int recordsAffected) internal override void BatchCompleted() { - SqlClientEventSource._log.Trace($" {reader.ObjectID}#.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {reader.ObjectID}#."); + } // devnote: relies on SmiEventSink_Default to pass event to parent // parent's callback *MUST* come before reader's BatchCompleted, since diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs index 3978939845..d789ff5afd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs @@ -8,6 +8,7 @@ using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Data.Common; +using static Microsoft.Data.SqlClient.SqlClientEventSource; using SysTx = System.Transactions; namespace Microsoft.Data.SqlClient @@ -88,8 +89,10 @@ public void Initialize() // transaction. SqlInternalConnection connection = _connection; SqlConnection usersConnection = connection.Connection; - - SqlClientEventSource._log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, delegating transaction.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, delegating transaction."); + } RuntimeHelpers.PrepareConstrainedRegions(); try @@ -104,8 +107,13 @@ public void Initialize() { #endif //DEBUG if (connection.IsEnlistedInTransaction) - { // defect first - SqlClientEventSource._log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, was enlisted, now defecting.\n"); + { + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, was enlisted, now defecting."); + } + + // defect first connection.EnlistNull(); } @@ -165,7 +173,10 @@ public Byte[] Promote() byte[] returnValue = null; SqlConnection usersConnection = connection.Connection; - SqlClientEventSource._log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, promoting transaction.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, promoting transaction."); + } RuntimeHelpers.PrepareConstrainedRegions(); try @@ -264,7 +275,10 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) SqlInternalConnection connection = GetValidConnection(); SqlConnection usersConnection = connection.Connection; - SqlClientEventSource._log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, aborting transaction.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, aborting transaction."); + } RuntimeHelpers.PrepareConstrainedRegions(); try @@ -357,7 +371,10 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) SqlInternalConnection connection = GetValidConnection(); SqlConnection usersConnection = connection.Connection; - SqlClientEventSource._log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, committing transaction.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, committing transaction."); + } RuntimeHelpers.PrepareConstrainedRegions(); try @@ -487,7 +504,10 @@ internal void TransactionEnded(SysTx.Transaction transaction) if (connection != null) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, transaction completed externally.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, transaction completed externally."); + } lock (connection) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs index a9765f975a..c8e046ec23 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -18,6 +18,7 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; using Microsoft.Data.Sql; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -316,7 +317,7 @@ public SqlDependency(SqlCommand command) : this(command, null, SQL.SqlDependency [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public SqlDependency(SqlCommand command, string options, int timeout) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, options: '{options}', timeout: '{timeout}'"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, options: '{options}', timeout: '{timeout}'"); try { if (InOutOfProcHelper.InProc) @@ -339,7 +340,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -436,7 +437,7 @@ public event OnChangeEventHandler OnChange // EventHandlers to be fired when dependency is notified. add { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { if (null != value) @@ -447,12 +448,12 @@ public event OnChangeEventHandler OnChange { if (_dependencyFired) { // If fired, fire the new event immediately. - SqlClientEventSource._log.NotificationsTrace($" Dependency already fired, firing new event.\n"); + _log.NotificationsTrace($" Dependency already fired, firing new event.\n"); sqlNotificationEvent = new SqlNotificationEventArgs(SqlNotificationType.Subscribe, SqlNotificationInfo.AlreadyChanged, SqlNotificationSource.Client); } else { - SqlClientEventSource._log.NotificationsTrace($" Dependency has not fired, adding new event.\n"); + _log.NotificationsTrace($" Dependency has not fired, adding new event.\n"); EventContextPair pair = new EventContextPair(value, this); if (!_eventList.Contains(pair)) { @@ -473,12 +474,12 @@ public event OnChangeEventHandler OnChange } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } remove { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { if (null != value) @@ -496,7 +497,7 @@ public event OnChangeEventHandler OnChange } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } } @@ -513,7 +514,7 @@ public void AddCommandDependency(SqlCommand command) { // Adds command to dependency collection so we automatically create the SqlNotificationsRequest object // and listen for a notification for the added commands. - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { if (command == null) @@ -525,7 +526,7 @@ public void AddCommandDependency(SqlCommand command) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -551,9 +552,9 @@ private static void ObtainProcessDispatcher() if (nativeStorage == null) { - SqlClientEventSource._log.NotificationsTrace($" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher.\n"); + _log.NotificationsTrace($" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher.\n"); #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource._log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}\n"); + _log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}\n"); #endif _AppDomain masterDomain = SNINativeMethodWrapper.GetDefaultAppDomain(); @@ -578,32 +579,32 @@ private static void ObtainProcessDispatcher() } else { - SqlClientEventSource._log.NotificationsTrace($" ERROR - ObjectHandle.Unwrap returned null!\n"); + _log.NotificationsTrace($" ERROR - ObjectHandle.Unwrap returned null!\n"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyObtainProcessDispatcherFailureObjectHandle); } } else { - SqlClientEventSource._log.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!\n"); + _log.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!\n"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureCreateInstance); } } else { - SqlClientEventSource._log.NotificationsTrace(" ERROR - unable to obtain default AppDomain!\n"); + _log.NotificationsTrace(" ERROR - unable to obtain default AppDomain!\n"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureAppDomain); } } else { - SqlClientEventSource._log.NotificationsTrace(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher.\n"); + _log.NotificationsTrace(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher.\n"); #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource._log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}\n"); + _log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}\n"); #endif BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(nativeStorage); _processDispatcher = GetDeserializedObject(formatter, stream); // Deserialize and set for appdomain. - SqlClientEventSource._log.NotificationsTrace($" processDispatcher obtained, ID: {_processDispatcher.ObjectID}\n"); + _log.NotificationsTrace($" processDispatcher obtained, ID: {_processDispatcher.ObjectID}\n"); } } @@ -650,7 +651,7 @@ public static bool Start(string connectionString, string queue) internal static bool Start(string connectionString, string queue, bool useDefaults) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); + var scopeID = _log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -723,7 +724,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul SqlDependencyPerAppDomainDispatcher.SingletonInstance, out errorOccurred, out appDomainStart); - SqlClientEventSource._log.NotificationsTrace($" Start (defaults) returned: '{result}', with service: '{service}', server: '{server}', database: '{database}'\n"); + _log.NotificationsTrace($" Start (defaults) returned: '{result}', with service: '{service}', server: '{server}', database: '{database}'\n"); } finally { @@ -745,7 +746,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - SqlClientEventSource._log.NotificationsTrace(" Exception occurred from Stop() after duplicate was found on Start().\n"); + _log.NotificationsTrace(" Exception occurred from Stop() after duplicate was found on Start().\n"); } throw SQL.SqlDependencyDuplicateStart(); } @@ -758,7 +759,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul queue, _appDomainKey, SqlDependencyPerAppDomainDispatcher.SingletonInstance); - SqlClientEventSource._log.NotificationsTrace($" Start (user provided queue) returned: '{result}'\n"); + _log.NotificationsTrace($" Start (user provided queue) returned: '{result}'\n"); // No need to call AddToServerDatabaseHash since if not using default queue user is required // to provide options themselves. } @@ -772,7 +773,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - SqlClientEventSource._log.NotificationsTrace($" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...).\n"); + _log.NotificationsTrace($" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...).\n"); throw; } } @@ -781,7 +782,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -801,7 +802,7 @@ public static bool Stop(string connectionString, string queue) internal static bool Stop(string connectionString, string queue, bool useDefaults, bool startFailed) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); + var scopeID = _log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -911,7 +912,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -921,7 +922,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault private static bool AddToServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); + var scopeID = _log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); try { bool result = false; @@ -932,7 +933,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!_serverUserHash.ContainsKey(server)) { - SqlClientEventSource._log.NotificationsTrace(" Hash did not contain server, adding.\n"); + _log.NotificationsTrace(" Hash did not contain server, adding.\n"); identityDatabaseHash = new Dictionary>(); _serverUserHash.Add(server, identityDatabaseHash); } @@ -945,7 +946,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!identityDatabaseHash.ContainsKey(identityUser)) { - SqlClientEventSource._log.NotificationsTrace(" Hash contained server but not user, adding user.\n"); + _log.NotificationsTrace(" Hash contained server but not user, adding user.\n"); databaseServiceList = new List(); identityDatabaseHash.Add(identityUser, databaseServiceList); } @@ -956,13 +957,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!databaseServiceList.Contains(databaseService)) { - SqlClientEventSource._log.NotificationsTrace(" Adding database.\n"); + _log.NotificationsTrace(" Adding database.\n"); databaseServiceList.Add(databaseService); result = true; } else { - SqlClientEventSource._log.NotificationsTrace(" ERROR - hash already contained server, user, and database - we will throw!.\n"); + _log.NotificationsTrace(" ERROR - hash already contained server, user, and database - we will throw!.\n"); } } @@ -970,13 +971,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } private static void RemoveFromServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); + var scopeID = _log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); try { lock (_serverUserHash) @@ -996,43 +997,43 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair int index = databaseServiceList.IndexOf(databaseService); if (index >= 0) { - SqlClientEventSource._log.NotificationsTrace(" Hash contained server, user, and database - removing database.\n"); + _log.NotificationsTrace(" Hash contained server, user, and database - removing database.\n"); databaseServiceList.RemoveAt(index); if (databaseServiceList.Count == 0) { - SqlClientEventSource._log.NotificationsTrace(" databaseServiceList count 0, removing the list for this server and user.\n"); + _log.NotificationsTrace(" databaseServiceList count 0, removing the list for this server and user.\n"); identityDatabaseHash.Remove(identityUser); if (identityDatabaseHash.Count == 0) { - SqlClientEventSource._log.NotificationsTrace(" identityDatabaseHash count 0, removing the hash for this server.\n"); + _log.NotificationsTrace(" identityDatabaseHash count 0, removing the hash for this server.\n"); _serverUserHash.Remove(server); } } } else { - SqlClientEventSource._log.NotificationsTrace(" ERROR - hash contained server and user but not database!\n"); + _log.NotificationsTrace(" ERROR - hash contained server and user but not database!\n"); Debug.Assert(false, "Unexpected state - hash did not contain database!"); } } else { - SqlClientEventSource._log.NotificationsTrace(" ERROR - hash contained server but not user!\n"); + _log.NotificationsTrace(" ERROR - hash contained server but not user!\n"); Debug.Assert(false, "Unexpected state - hash did not contain user!"); } } else { - SqlClientEventSource._log.NotificationsTrace(" ERROR - hash did not contain server!\n"); + _log.NotificationsTrace(" ERROR - hash did not contain server!\n"); Debug.Assert(false, "Unexpected state - hash did not contain server!"); } } } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1040,7 +1041,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { // Server must be an exact match, but user and database only needs to match exactly if there is more than one // for the given user or database passed. That is ambiguious and we must fail. - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" server: '{server}', failoverServer: '{failoverServer}', database: '{database}'"); + var scopeID = _log.NotificationsScopeEnter($" server: '{server}', failoverServer: '{failoverServer}', database: '{database}'"); try { string result; @@ -1051,17 +1052,17 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { if (0 == _serverUserHash.Count) { // Special error for no calls to start. - SqlClientEventSource._log.NotificationsTrace(" ERROR - no start calls have been made, about to throw.\n"); + _log.NotificationsTrace(" ERROR - no start calls have been made, about to throw.\n"); throw SQL.SqlDepDefaultOptionsButNoStart(); } else if (!ADP.IsEmpty(failoverServer) && _serverUserHash.ContainsKey(failoverServer)) { - SqlClientEventSource._log.NotificationsTrace(" using failover server instead\n"); + _log.NotificationsTrace(" using failover server instead\n"); server = failoverServer; } else { - SqlClientEventSource._log.NotificationsTrace(" ERROR - not listening to this server, about to throw.\n"); + _log.NotificationsTrace(" ERROR - not listening to this server, about to throw.\n"); throw SQL.SqlDependencyNoMatchingServerStart(); } } @@ -1074,7 +1075,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { if (identityDatabaseHash.Count > 1) { - SqlClientEventSource._log.NotificationsTrace(" ERROR - not listening for this user, but listening to more than one other user, about to throw.\n"); + _log.NotificationsTrace(" ERROR - not listening for this user, but listening to more than one other user, about to throw.\n"); throw SQL.SqlDependencyNoMatchingServerStart(); } else @@ -1120,19 +1121,19 @@ internal static string GetDefaultComposedOptions(string server, string failoverS } else { // More than one database for given server, ambiguous - fail the default case! - SqlClientEventSource._log.NotificationsTrace(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database.\n"); + _log.NotificationsTrace(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database.\n"); throw SQL.SqlDependencyNoMatchingServerDatabaseStart(); } } } Debug.Assert(!ADP.IsEmpty(result), "GetDefaultComposedOptions should never return null or empty string!"); - SqlClientEventSource._log.NotificationsTrace($" resulting options: '{result}'.\n"); + _log.NotificationsTrace($" resulting options: '{result}'.\n"); return result; } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1144,7 +1145,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS // use this list for a reverse lookup based on server. internal void AddToServerList(string server) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); try { lock (_serverList) @@ -1152,7 +1153,7 @@ internal void AddToServerList(string server) int index = _serverList.BinarySearch(server, StringComparer.OrdinalIgnoreCase); if (0 > index) { // If less than 0, item was not found in list. - SqlClientEventSource._log.NotificationsTrace($" Server not present in hashtable, adding server: '{server}'.\n"); + _log.NotificationsTrace($" Server not present in hashtable, adding server: '{server}'.\n"); index = ~index; // BinarySearch returns the 2's compliment of where the item should be inserted to preserver a sorted list after insertion. _serverList.Insert(index, server); @@ -1161,7 +1162,7 @@ internal void AddToServerList(string server) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1175,7 +1176,7 @@ internal bool ContainsServer(string server) internal string ComputeHashAndAddToDispatcher(SqlCommand command) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); try { // Create a string representing the concatenation of the connection string, command text and .ToString on all parameter values. @@ -1190,18 +1191,18 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) string commandHash = ComputeCommandHash(command.Connection.ConnectionString, command); // calculate the string representation of command string idString = SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddCommandEntry(commandHash, this); // Add to map. - SqlClientEventSource._log.NotificationsTrace($" computed id string: '{idString}'.\n"); + _log.NotificationsTrace($" computed id string: '{idString}'.\n"); return idString; } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { List eventList = null; @@ -1219,12 +1220,12 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql // raises Timeout event but before removing this event from the list. If notification is received from // server in this case, we will hit this code path. // It is safe to ignore this race condition because no event is sent to user and no leak happens. - SqlClientEventSource._log.NotificationsTrace(" ignore notification received after timeout!"); + _log.NotificationsTrace(" ignore notification received after timeout!"); } else { Debug.Assert(false, "Received notification twice - we should never enter this state!"); - SqlClientEventSource._log.NotificationsTrace(" ERROR - notification received twice - we should never enter this state!"); + _log.NotificationsTrace(" ERROR - notification received twice - we should never enter this state!"); } } else @@ -1238,7 +1239,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (eventList != null) { - SqlClientEventSource._log.NotificationsTrace(" Firing events.\n"); + _log.NotificationsTrace(" Firing events.\n"); foreach (EventContextPair pair in eventList) { pair.Invoke(new SqlNotificationEventArgs(type, info, source)); @@ -1247,19 +1248,19 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } // This method is used by SqlCommand. internal void StartTimer(SqlNotificationRequest notificationRequest) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { if (_expirationTime == DateTime.MaxValue) { - SqlClientEventSource._log.NotificationsTrace(" We've timed out, executing logic.\n"); + _log.NotificationsTrace(" We've timed out, executing logic.\n"); int seconds = SQL.SqlDependencyServerTimeout; if (0 != _timeout) @@ -1278,7 +1279,7 @@ internal void StartTimer(SqlNotificationRequest notificationRequest) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1291,7 +1292,7 @@ private void AddCommandInternal(SqlCommand cmd) if (cmd != null) { // Don't bother with BID if command null. - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {cmd.ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {cmd.ObjectID}#"); try { SqlConnection connection = cmd.Connection; @@ -1301,7 +1302,7 @@ private void AddCommandInternal(SqlCommand cmd) // Fail if cmd has notification that is not already associated with this dependency. if (cmd._sqlDep == null || cmd._sqlDep != this) { - SqlClientEventSource._log.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception.\n"); + _log.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception.\n"); throw SQL.SqlCommandHasExistingSqlNotificationRequest(); } } @@ -1332,7 +1333,7 @@ private void AddCommandInternal(SqlCommand cmd) Debug.Assert(0 == _eventList.Count, "How can we have an event at this point?"); if (0 == _eventList.Count) { // Keep logic just in case. - SqlClientEventSource._log.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point.\n"); + _log.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point.\n"); needToInvalidate = true; // Delay invalidation until outside of lock. } } @@ -1346,14 +1347,14 @@ private void AddCommandInternal(SqlCommand cmd) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } } private string ComputeCommandHash(string connectionString, SqlCommand command) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); try { // Create a string representing the concatenation of the connection string, the command text and .ToString on all its parameter values. @@ -1411,12 +1412,12 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) string result = builder.ToString(); - SqlClientEventSource._log.NotificationsTrace($" ComputeCommandHash result: '{result}'.\n"); + _log.NotificationsTrace($" ComputeCommandHash result: '{result}'.\n"); return result; } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index 0248aa7167..ac126a5303 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -17,6 +17,7 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; using Microsoft.Data.SqlClient; +using static Microsoft.Data.SqlClient.SqlClientEventSource; // This class is the process wide dependency dispatcher. It contains all connection listeners for the entire process and // receives notifications on those connections to dispatch to the corresponding AppDomain dispatcher to notify the @@ -79,7 +80,7 @@ internal int ObjectID internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, queue: '{hashHelper.Queue}'"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, queue: '{hashHelper.Queue}'"); bool setupCompleted = false; @@ -103,7 +104,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(_hashHelper.ConnectionStringBuilder.ConnectionString); - SqlClientEventSource._log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'\n"); + _log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); #endif // Always use ConnectionStringBuilder since in default case it is different from the @@ -218,7 +219,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -278,7 +279,7 @@ internal string Server // SqlDependencyProcessDispatcher.QueueAppDomainUnload on AppDomain.Unload. internal bool AppDomainUnload(string appDomainKey) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, AppDomainKey: '{ appDomainKey}'"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, AppDomainKey: '{ appDomainKey}'"); try { Debug.Assert(!ADP.IsEmpty(appDomainKey), "Unexpected empty appDomainKey!"); @@ -289,9 +290,9 @@ internal bool AppDomainUnload(string appDomainKey) { if (_appDomainKeyHash.ContainsKey(appDomainKey)) { // Do nothing if AppDomain did not call Start! - SqlClientEventSource._log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}'.\n"); + _log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}'."); int value = _appDomainKeyHash[appDomainKey]; - SqlClientEventSource._log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{appDomainKey}' count: '{value}'.\n"); + _log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{appDomainKey}' count: '{value}'."); Debug.Assert(value > 0, "Why is value 0 or less?"); bool ignored = false; @@ -308,27 +309,27 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { - SqlClientEventSource._log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{appDomainKey}' entry not removed from hash. Count: {_appDomainKeyHash[appDomainKey]}'\n"); + _log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{appDomainKey}' entry not removed from hash. Count: {_appDomainKeyHash[appDomainKey]}'"); } } else { - SqlClientEventSource._log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}'.\n"); + _log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}'."); } } - SqlClientEventSource._log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{_stopped}'.\n"); + _log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{_stopped}'."); return _stopped; } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } private void AsynchronouslyQueryServiceBrokerQueue() { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { AsyncCallback callback = new AsyncCallback(AsyncResultCallback); @@ -336,13 +337,13 @@ private void AsynchronouslyQueryServiceBrokerQueue() } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } private void AsyncResultCallback(IAsyncResult asyncResult) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { using (SqlDataReader reader = _com.EndExecuteReader(asyncResult)) @@ -369,7 +370,7 @@ private void AsyncResultCallback(IAsyncResult asyncResult) throw; } - SqlClientEventSource._log.NotificationsTrace($" Exception occurred.\n"); + _log.NotificationsTrace($" Exception occurred."); if (!_stop) { // Only assert if not in cancel path. ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. @@ -388,13 +389,13 @@ private void AsyncResultCallback(IAsyncResult asyncResult) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } private void CreateQueueAndService(bool restart) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { SqlCommand com = new SqlCommand(); @@ -524,18 +525,18 @@ private void CreateQueueAndService(bool restart) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { appDomainStart = false; // Reset out param. int result = Interlocked.Increment(ref _startCount); // Add to refCount. - SqlClientEventSource._log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> {_staticInstance.ObjectID}#, incremented _startCount: {result}\n"); + _log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> {_staticInstance.ObjectID}#, incremented _startCount: {result}"); // Dictionary used to track how many times start has been called per app domain. // For each increment, add to count, and create entry if not present. @@ -544,25 +545,25 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { _appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1; - SqlClientEventSource._log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', incremented count: '{_appDomainKeyHash[appDomainKey]}'.\n"); + _log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', incremented count: '{_appDomainKeyHash[appDomainKey]}'."); } else { _appDomainKeyHash[appDomainKey] = 1; appDomainStart = true; - SqlClientEventSource._log.NotificationsTrace($" _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}', added to hashtable and value set to 1.\n"); + _log.NotificationsTrace($" _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}', added to hashtable and value set to 1."); } } } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } private void ProcessNotificationResults(SqlDataReader reader) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { Guid handle = Guid.Empty; // Conversation_handle. Always close this! @@ -572,17 +573,17 @@ private void ProcessNotificationResults(SqlDataReader reader) { while (reader.Read()) { - SqlClientEventSource._log.NotificationsTrace($" Row read.\n"); + _log.NotificationsTrace($" Row read."); #if DEBUG for (int i = 0; i < reader.FieldCount; i++) { - SqlClientEventSource._log.NotificationsTrace($" column: {reader.GetName(i)}, value: {reader.GetValue(i).ToString()}\n"); + _log.NotificationsTrace($" column: {reader.GetName(i)}, value: {reader.GetValue(i).ToString()}"); } #endif string msgType = reader.GetString(0); - SqlClientEventSource._log.NotificationsTrace($" msgType: '{ msgType}'\n"); + _log.NotificationsTrace($" msgType: '{ msgType}'"); handle = reader.GetGuid(1); - // SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.ProcessNotificationResults(SqlDataReader)|DEP> conversationHandle: '%p(GUID)'\n", conversationHandle); + // SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.ProcessNotificationResults(SqlDataReader)|DEP> conversationHandle: '%p(GUID)'", conversationHandle); // Only process QueryNotification messages. if (0 == String.Compare(msgType, "http://schemas.microsoft.com/SQL/Notifications/QueryNotification", StringComparison.OrdinalIgnoreCase)) @@ -594,7 +595,7 @@ private void ProcessNotificationResults(SqlDataReader reader) if (null != notification) { string key = notification.Key; - SqlClientEventSource._log.NotificationsTrace($" Key: '{key}'\n"); + _log.NotificationsTrace($" Key: '{key}'"); int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash" if (index >= 0) @@ -623,25 +624,25 @@ private void ProcessNotificationResults(SqlDataReader reader) else { Debug.Assert(false, "Received notification but do not have an associated PerAppDomainDispatcher!"); - SqlClientEventSource._log.NotificationsTrace($" Received notification but do not have an associated PerAppDomainDispatcher!\n"); + _log.NotificationsTrace($" Received notification but do not have an associated PerAppDomainDispatcher!"); } } else { Debug.Assert(false, "Unexpected ID format received!"); - SqlClientEventSource._log.NotificationsTrace($" Unexpected ID format received!\n"); + _log.NotificationsTrace($" Unexpected ID format received!"); } } else { Debug.Assert(false, "Null notification returned from ProcessMessage!"); - SqlClientEventSource._log.NotificationsTrace($" Null notification returned from ProcessMessage!\n"); + _log.NotificationsTrace($" Null notification returned from ProcessMessage!"); } } else { Debug.Assert(false, "Null payload for QN notification type!"); - SqlClientEventSource._log.NotificationsTrace($" Null payload for QN notification type!\n"); + _log.NotificationsTrace($" Null payload for QN notification type!"); } } else @@ -649,7 +650,7 @@ private void ProcessNotificationResults(SqlDataReader reader) handle = Guid.Empty; // VSDD 546707: this assert was hit by SQL Notification fuzzing tests, disable it to let these tests run on Debug bits // Debug.Assert(false, "Unexpected message format received!"); - SqlClientEventSource._log.NotificationsTrace($" Unexpected message format received!\n"); + _log.NotificationsTrace($" Unexpected message format received!"); } } } @@ -681,7 +682,7 @@ private void ProcessNotificationResults(SqlDataReader reader) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -692,7 +693,7 @@ private void ProcessNotificationResults(SqlDataReader reader) private void Restart(object unused) { // Unused arg required by TimerCallback. - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { try @@ -854,13 +855,13 @@ private void Restart(object unused) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } internal bool Stop(string appDomainKey, out bool appDomainStop) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { appDomainStop = false; @@ -881,14 +882,14 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) Debug.Assert(value > 0, "Unexpected count for appDomainKey"); - SqlClientEventSource._log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', pre-decrement Count: '{value}'.\n"); + _log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', pre-decrement Count: '{value}'."); if (value > 0) { _appDomainKeyHash[appDomainKey] = value - 1; } else { - SqlClientEventSource._log.NotificationsTrace($" ERROR pre-decremented count <= 0!\n"); + _log.NotificationsTrace($" ERROR pre-decremented count <= 0!"); Debug.Assert(false, "Unexpected AppDomainKey count in Stop()"); } @@ -900,7 +901,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource._log.NotificationsTrace($" ERROR appDomainKey not null and not found in hash!\n"); + _log.NotificationsTrace($" ERROR appDomainKey not null and not found in hash!"); Debug.Assert(false, "Unexpected state on Stop() - no AppDomainKey entry in hashtable!"); } } @@ -912,7 +913,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) if (0 == result) { // If we've reached refCount 0, destroy. // Lock to ensure Cancel() complete prior to other thread calling TearDown. - SqlClientEventSource._log.NotificationsTrace($" Reached 0 count, cancelling and waiting.\n"); + _log.NotificationsTrace($" Reached 0 count, cancelling and waiting."); lock (this) { try @@ -955,7 +956,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) // TearDownAndDispose in the maximum retry period case as well as in the _errorState case. if (_errorState || retryStopwatch.Elapsed.Seconds >= 30) { - SqlClientEventSource._log.NotificationsTrace($" forcing cleanup. elapsedSeconds: '{retryStopwatch.Elapsed.Seconds}', _errorState: '{_errorState}'.\n"); + _log.NotificationsTrace($" forcing cleanup. elapsedSeconds: '{retryStopwatch.Elapsed.Seconds}', _errorState: '{_errorState}'."); Timer retryTimer = _retryTimer; _retryTimer = null; @@ -975,7 +976,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource._log.NotificationsTrace($" _startCount not 0 after decrement. _startCount: '{_startCount}'.\n"); + _log.NotificationsTrace($" _startCount not 0 after decrement. _startCount: '{_startCount}'."); } Debug.Assert(0 <= _startCount, "Invalid start count state"); @@ -984,13 +985,13 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } private void SynchronouslyQueryServiceBrokerQueue() { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { using (SqlDataReader reader = _com.ExecuteReader()) @@ -1000,14 +1001,14 @@ private void SynchronouslyQueryServiceBrokerQueue() } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } [SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")] private void TearDownAndDispose() { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { lock (this) @@ -1080,7 +1081,7 @@ private void TearDownAndDispose() } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } } @@ -1224,42 +1225,61 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) catch (ArgumentException e) { ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace. - SqlClientEventSource._log.Trace($" Exception thrown - Enum.Parse failed to parse the value '{xmlReader.Value}' of the attribute '{xmlReader.LocalName}'.\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" Exception thrown - Enum.Parse failed to parse the value '{xmlReader.Value}' of the attribute '{xmlReader.LocalName}'."); + } return null; } } if (MessageAttributes.All != messageAttributes) { - SqlClientEventSource._log.Trace($" Not all expected attributes in Message; messageAttributes = '{(int)messageAttributes}'.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Not all expected attributes in Message; messageAttributes = '{(int)messageAttributes}'."); + } return null; } // Proceed to the "Message" node. if (!xmlReader.Read()) { - SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + } return null; } // Verify state after Read(). - if ((XmlNodeType.Element != xmlReader.NodeType) || (0 != String.Compare(xmlReader.LocalName, MessageNode, StringComparison.OrdinalIgnoreCase))) + if ((XmlNodeType.Element != xmlReader.NodeType) || (0 != string.Compare(xmlReader.LocalName, MessageNode, StringComparison.OrdinalIgnoreCase))) { - SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + } return null; } // Proceed to the Text Node. if (!xmlReader.Read()) { - SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + } return null; } // Verify state after Read(). if (xmlReader.NodeType != XmlNodeType.Text) { - SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + } return null; } @@ -1269,7 +1289,10 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the Text Node. if (!xmlMessageReader.Read()) { - SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + } return null; } @@ -1280,7 +1303,10 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + } return null; } } @@ -1289,7 +1315,10 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - SqlClientEventSource._log.Trace($" unexpected Read failure on xml or unexpected structure of xml.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + } return null; // failure } } @@ -1469,19 +1498,19 @@ internal int ObjectID private SqlDependencyProcessDispatcher(object dummyVariable) { Debug.Assert(null == _staticInstance, "Real constructor called with static instance already created!"); - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}\n"); + _log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); #endif _connectionContainers = new Dictionary(); _sqlDependencyPerAppDomainDispatchers = new Dictionary(); } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1489,18 +1518,18 @@ private SqlDependencyProcessDispatcher(object dummyVariable) // Required to be public, even on internal class, for Remoting infrastructure. public SqlDependencyProcessDispatcher() { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { // Empty constructor and object - dummy to obtain singleton. #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}\n"); + _log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); #endif } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1526,7 +1555,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS out string user, string queue) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {_staticInstance.ObjectID}#, queue: {queue}"); + var scopeID = _log.NotificationsScopeEnter($" {_staticInstance.ObjectID}#, queue: {queue}"); try { // Force certain connection string properties to be used by SqlDependencyProcessDispatcher. @@ -1559,7 +1588,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1571,7 +1600,7 @@ public override object InitializeLifetimeService() private void Invalidate(string server, SqlNotification sqlNotification) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, server: {server}"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, server: {server}"); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1603,7 +1632,7 @@ private void Invalidate(string server, SqlNotification sqlNotification) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1620,7 +1649,7 @@ internal void QueueAppDomainUnloading(string appDomainKey) // This method is only called by queued work-items from the method above. private void AppDomainUnloading(object state) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { string appDomainKey = (string)state; @@ -1652,7 +1681,7 @@ private void AppDomainUnloading(object state) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1719,7 +1748,7 @@ private bool Start(string connectionString, out bool appDomainStart, bool useDefaults) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, queue: '{ queueService}', appDomainKey: '{appDomainKey}', perAppDomainDispatcher ID: '{dispatcher.ObjectID}'"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, queue: '{ queueService}', appDomainKey: '{appDomainKey}', perAppDomainDispatcher ID: '{dispatcher.ObjectID}'"); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1746,7 +1775,7 @@ private bool Start(string connectionString, queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - SqlClientEventSource._log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'\n"); + _log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); #endif bool started = false; @@ -1756,7 +1785,7 @@ private bool Start(string connectionString, { if (!_connectionContainers.ContainsKey(hashHelper)) { - SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, hashtable miss, creating new container.\n"); + _log.NotificationsTrace($" {ObjectID}#, hashtable miss, creating new container."); container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults); _connectionContainers.Add(hashHelper, container); started = true; @@ -1765,10 +1794,10 @@ private bool Start(string connectionString, else { container = _connectionContainers[hashHelper]; - SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}\n"); + _log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}"); if (container.InErrorState) { - SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, container: {container.ObjectID} is in error state!\n"); + _log.NotificationsTrace($" {ObjectID}#, container: {container.ObjectID} is in error state!"); errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start(). } else @@ -1783,16 +1812,16 @@ private bool Start(string connectionString, server = container.Server; database = container.Database; queueService = container.Queue; - SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, default service: '{queueService}', server: '{server}', database: '{database}'\n"); + _log.NotificationsTrace($" {ObjectID}#, default service: '{queueService}', server: '{server}', database: '{database}'"); } - SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, started: {started}\n"); + _log.NotificationsTrace($" {ObjectID}#, started: {started}"); return started; } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -1809,7 +1838,7 @@ internal bool Stop(string connectionString, string appDomainKey, out bool appDomainStop) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, queue: '{queueService}'"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, queue: '{queueService}'"); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1827,7 +1856,7 @@ internal bool Stop(string connectionString, queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - SqlClientEventSource._log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'\n"); + _log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); #endif bool stopped = false; @@ -1837,7 +1866,7 @@ internal bool Stop(string connectionString, if (_connectionContainers.ContainsKey(hashHelper)) { SqlConnectionContainer container = _connectionContainers[hashHelper]; - SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}\n"); + _log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}"); server = container.Server; // Return server, database, and queue info for use by calling SqlDependency. database = container.Database; queueService = container.Queue; @@ -1849,16 +1878,16 @@ internal bool Stop(string connectionString, } else { - SqlClientEventSource._log.NotificationsTrace($" {ObjectID}#, hashtable miss.\n"); + _log.NotificationsTrace($" {ObjectID}#, hashtable miss."); } } - SqlClientEventSource._log.NotificationsTrace($" %d#, stopped: {stopped}\n"); + _log.NotificationsTrace($" %d#, stopped: {stopped}"); return stopped; } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs index c828314245..1f99347239 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Threading; using Microsoft.Data.Common; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -92,7 +93,7 @@ internal int ObjectID private SqlDependencyPerAppDomainDispatcher() { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { _dependencyIdToDependencyHash = new Dictionary(); @@ -106,7 +107,7 @@ private SqlDependencyPerAppDomainDispatcher() } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -124,7 +125,7 @@ public override object InitializeLifetimeService() private void UnloadEventHandler(object sender, EventArgs e) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); try { // Make non-blocking call to ProcessDispatcher to ThreadPool.QueueUserWorkItem to complete @@ -139,7 +140,7 @@ private void UnloadEventHandler(object sender, EventArgs e) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -150,7 +151,7 @@ private void UnloadEventHandler(object sender, EventArgs e) // This method is called upon SqlDependency constructor. internal void AddDependencyEntry(SqlDependency dep) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); try { lock (this) @@ -160,7 +161,7 @@ internal void AddDependencyEntry(SqlDependency dep) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -169,14 +170,14 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) { string notificationId = string.Empty; - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{commandHash}', SqlDependency: {dep.ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{commandHash}', SqlDependency: {dep.ObjectID}#"); try { lock (this) { if (!_dependencyIdToDependencyHash.ContainsKey(dep.Id)) { // Determine if depId->dep hashtable contains dependency. If not, it's been invalidated. - SqlClientEventSource._log.NotificationsTrace($" Dependency not present in depId->dep hash, must have been invalidated.\n"); + _log.NotificationsTrace($" Dependency not present in depId->dep hash, must have been invalidated.\n"); } else { @@ -197,12 +198,12 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // join the new dependency to the list if (!dependencyList.Contains(dep)) { - SqlClientEventSource._log.NotificationsTrace($" Dependency not present for commandHash, adding.\n"); + _log.NotificationsTrace($" Dependency not present for commandHash, adding.\n"); dependencyList.Add(dep); } else { - SqlClientEventSource._log.NotificationsTrace($" Dependency already present for commandHash.\n"); + _log.NotificationsTrace($" Dependency already present for commandHash.\n"); } } else @@ -217,7 +218,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) Guid.NewGuid().ToString("D", System.Globalization.CultureInfo.InvariantCulture) ); - SqlClientEventSource._log.NotificationsTrace($" Creating new Dependencies list for commandHash.\n"); + _log.NotificationsTrace($" Creating new Dependencies list for commandHash.\n"); DependencyList dependencyList = new DependencyList(commandHash); dependencyList.Add(dep); @@ -239,7 +240,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } return notificationId; @@ -248,7 +249,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // This method is called by the ProcessDispatcher upon a notification for this AppDomain. internal void InvalidateCommandID(SqlNotification sqlNotification) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{sqlNotification.Key}'"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{sqlNotification.Key}'"); try { List dependencyList = null; @@ -259,7 +260,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) if (null != dependencyList) { - SqlClientEventSource._log.NotificationsTrace($" commandHash found in hashtable.\n"); + _log.NotificationsTrace($" commandHash found in hashtable.\n"); foreach (SqlDependency dependency in dependencyList) { @@ -272,7 +273,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } else { - SqlClientEventSource._log.NotificationsTrace($" commandHash NOT found in hashtable.\n"); + _log.NotificationsTrace($" commandHash NOT found in hashtable.\n"); } } @@ -281,7 +282,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) // After removal from hashtables, invalidate. foreach (SqlDependency dependency in dependencyList) { - SqlClientEventSource._log.NotificationsTrace($" Dependency found in commandHash dependency ArrayList - calling invalidate.\n"); + _log.NotificationsTrace($" Dependency found in commandHash dependency ArrayList - calling invalidate.\n"); try { @@ -303,14 +304,14 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } // This method is called when a connection goes down or other unknown error occurs in the ProcessDispatcher. internal void InvalidateServer(string server, SqlNotification sqlNotification) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); try { List dependencies = new List(); @@ -357,14 +358,14 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } // This method is called by SqlCommand to enable ASP.NET scenarios - map from ID to Dependency. internal SqlDependency LookupDependencyEntry(string id) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, Key: '{id}'"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, Key: '{id}'"); try { if (null == id) @@ -386,7 +387,7 @@ internal SqlDependency LookupDependencyEntry(string id) } else { - SqlClientEventSource._log.NotificationsTrace($" ERROR - dependency ID mismatch - not throwing.\n"); + _log.NotificationsTrace($" ERROR - dependency ID mismatch - not throwing.\n"); } } @@ -394,21 +395,21 @@ internal SqlDependency LookupDependencyEntry(string id) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } // Remove the dependency from the hashtable with the passed id. private void LookupDependencyEntryWithRemove(string id) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, id: '{id}'"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, id: '{id}'"); try { lock (this) { if (_dependencyIdToDependencyHash.ContainsKey(id)) { - SqlClientEventSource._log.NotificationsTrace($" Entry found in hashtable - removing.\n"); + _log.NotificationsTrace($" Entry found in hashtable - removing.\n"); _dependencyIdToDependencyHash.Remove(id); // if there are no more dependencies then we can dispose the timer. @@ -420,20 +421,20 @@ private void LookupDependencyEntryWithRemove(string id) } else { - SqlClientEventSource._log.NotificationsTrace($" Entry NOT found in hashtable.\n"); + _log.NotificationsTrace($" Entry NOT found in hashtable.\n"); } } } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } // Find and return arraylist, and remove passed hash value. private List LookupCommandEntryWithRemove(string notificationId) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{notificationId}'"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{notificationId}'"); try { DependencyList entry = null; @@ -442,7 +443,7 @@ private List LookupCommandEntryWithRemove(string notificationId) { if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry)) { - SqlClientEventSource._log.NotificationsTrace($" Entries found in hashtable - removing.\n"); + _log.NotificationsTrace($" Entries found in hashtable - removing.\n"); // update the tables - do it inside finally block to avoid ThreadAbort exception interrupt this operation try @@ -456,7 +457,7 @@ private List LookupCommandEntryWithRemove(string notificationId) } else { - SqlClientEventSource._log.NotificationsTrace($" Entries NOT found in hashtable.\n"); + _log.NotificationsTrace($" Entries NOT found in hashtable.\n"); } Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!"); @@ -466,14 +467,14 @@ private List LookupCommandEntryWithRemove(string notificationId) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } // Remove from commandToDependenciesHash all references to the passed dependency. private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency dependency) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dependency.ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dependency.ObjectID}#"); try { lock (this) @@ -486,7 +487,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende DependencyList dependencies = entry.Value; if (dependencies.Remove(dependency)) { - SqlClientEventSource._log.NotificationsTrace($" Removed SqlDependency: {dependency.ObjectID}#, with ID: '{dependency.Id}'.\n"); + _log.NotificationsTrace($" Removed SqlDependency: {dependency.ObjectID}#, with ID: '{dependency.Id}'.\n"); if (dependencies.Count == 0) { // this dependency was the last associated with this notification ID, remove the entry @@ -519,7 +520,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -529,7 +530,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende internal void StartTimer(SqlDependency dep) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); + var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); try { // If this dependency expires sooner than the current next timeout, change @@ -540,7 +541,7 @@ internal void StartTimer(SqlDependency dep) // Enable the timer if needed (disable when empty, enable on the first addition). if (!_SqlDependencyTimeOutTimerStarted) { - SqlClientEventSource._log.NotificationsTrace($" Timer not yet started, starting.\n"); + _log.NotificationsTrace($" Timer not yet started, starting.\n"); _timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */); @@ -550,7 +551,7 @@ internal void StartTimer(SqlDependency dep) } else if (_nextTimeout > dep.ExpirationTime) { - SqlClientEventSource._log.NotificationsTrace($" Timer already started, resetting time.\n"); + _log.NotificationsTrace($" Timer already started, resetting time.\n"); // Save this as the earlier timeout to come. _nextTimeout = dep.ExpirationTime; @@ -559,13 +560,13 @@ internal void StartTimer(SqlDependency dep) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } private static void TimeoutTimerCallback(object state) { - var scopeID = SqlClientEventSource._log.NotificationsScopeEnter($" AppDomainKey: '{SqlDependency.AppDomainKey}'"); + var scopeID = _log.NotificationsScopeEnter($" AppDomainKey: '{SqlDependency.AppDomainKey}'"); try { SqlDependency[] dependencies; @@ -578,12 +579,12 @@ private static void TimeoutTimerCallback(object state) if (0 == SingletonInstance._dependencyIdToDependencyHash.Count) { // Nothing to check. - SqlClientEventSource._log.NotificationsTrace($" No dependencies, exiting.\n"); + _log.NotificationsTrace($" No dependencies, exiting.\n"); return; } if (SingletonInstance._nextTimeout > DateTime.UtcNow) { - SqlClientEventSource._log.NotificationsTrace($" No timeouts expired, exiting.\n"); + _log.NotificationsTrace($" No timeouts expired, exiting.\n"); // No dependency timed-out yet. return; } @@ -653,7 +654,7 @@ private static void TimeoutTimerCallback(object state) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs index 5dd27c71b6..a2142e14a6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -41,7 +42,10 @@ internal SqlError(int infoNumber, byte errorState, byte errorClass, string serve this.lineNumber = lineNumber; if (errorClass != 0) { - SqlClientEventSource._log.Trace($" infoNumber={infoNumber}, errorState={(int)errorState}, errorClass={(int)errorClass}, errorMessage='{errorMessage}', procedure='{procedure ?? "None"}', lineNumber={(int)lineNumber}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" infoNumber={infoNumber}, errorState={(int)errorState}, errorClass={(int)errorClass}, errorMessage='{errorMessage}', procedure='{procedure ?? "None"}', lineNumber={(int)lineNumber}"); + } } this.win32ErrorCode = 0; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index bfa9fb9609..6883f75610 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -9,7 +9,9 @@ using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using Microsoft.Data.Common; +using static Microsoft.Data.SqlClient.SqlClientEventSource; using Microsoft.Data.ProviderBase; + using SysTx = System.Transactions; namespace Microsoft.Data.SqlClient @@ -313,7 +315,7 @@ override protected DbReferenceCollection CreateReferenceCollection() override protected void Deactivate() { - SqlClientEventSource._log.Trace($" {ObjectID}# deactivating\n"); + _log.Trace($" {ObjectID}# deactivating\n"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -436,13 +438,13 @@ private void EnlistNonNull(SysTx.Transaction tx) { Debug.Assert(null != tx, "null transaction?"); - SqlClientEventSource._log.Trace($" {ObjectID}#, transaction {tx.GetHashCode()}#.\n"); + _log.Trace($" {ObjectID}#, transaction {tx.GetHashCode()}#.\n"); bool hasDelegatedTransaction = false; if (IsYukonOrNewer) { - SqlClientEventSource._log.Trace($" {ObjectID}#, attempting to delegate\n"); + _log.Trace($" {ObjectID}#, attempting to delegate\n"); // Promotable transactions are only supported on Yukon // servers or newer. @@ -518,7 +520,7 @@ private void EnlistNonNull(SysTx.Transaction tx) transactionId = CurrentTransaction.TransactionId; transactionObjectID = CurrentTransaction.ObjectID; } - SqlClientEventSource._log.Trace($" {ObjectID}#, delegated to transaction {transactionObjectID}# with transactionId=0x{transactionId}\n"); + _log.Trace($" {ObjectID}#, delegated to transaction {transactionObjectID}# with transactionId=0x{transactionId}\n"); } } catch (SqlException e) @@ -551,7 +553,7 @@ private void EnlistNonNull(SysTx.Transaction tx) if (!hasDelegatedTransaction) { - SqlClientEventSource._log.Trace($" {ObjectID}#, delegation not possible, enlisting.\n"); + _log.Trace($" {ObjectID}#, delegation not possible, enlisting.\n"); byte[] cookie = null; @@ -591,7 +593,7 @@ private void EnlistNonNull(SysTx.Transaction tx) transactionId = CurrentTransaction.TransactionId; transactionObjectID = CurrentTransaction.ObjectID; } - SqlClientEventSource._log.Trace($" {ObjectID}#, enlisted with transaction {transactionObjectID}# with transactionId=0x{transactionId}\n"); + _log.Trace($" {ObjectID}#, enlisted with transaction {transactionObjectID}# with transactionId=0x{transactionId}\n"); } EnlistedTransaction = tx; // Tell the base class about our enlistment @@ -615,7 +617,7 @@ private void EnlistNonNull(SysTx.Transaction tx) internal void EnlistNull() { - SqlClientEventSource._log.Trace($" {ObjectID}#, unenlisting.\n"); + _log.Trace($" {ObjectID}#, unenlisting.\n"); // We were in a transaction, but now we are not - so send // message to server with empty transaction - confirmed proper @@ -634,7 +636,7 @@ internal void EnlistNull() _isEnlistedInTransaction = false; EnlistedTransaction = null; // Tell the base class about our enlistment - SqlClientEventSource._log.Trace($" {ObjectID}#, unenlisted.\n"); + _log.Trace($" {ObjectID}#, unenlisted.\n"); // The EnlistTransaction above will return an TransactionEnded event, // which causes the TdsParser or SmiEventSink should to clear the diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs index bbb6934911..2960ac038a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using Microsoft.Data.Common; using Microsoft.Data.SqlClient.Server; +using static Microsoft.Data.SqlClient.SqlClientEventSource; using SysTx = System.Transactions; namespace Microsoft.Data.SqlClient @@ -66,37 +67,55 @@ internal EventSink(SqlInternalConnectionSmi connection) internal override void DefaultDatabaseChanged(string databaseName) { - SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, databaseName='{databaseName}'.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {_connection.ObjectID}#, databaseName='{databaseName}'."); + } _connection.CurrentDatabase = databaseName; } internal override void TransactionCommitted(long transactionId) { - SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); + } _connection.TransactionEnded(transactionId, TransactionState.Committed); } internal override void TransactionDefected(long transactionId) { - SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); + } _connection.TransactionEnded(transactionId, TransactionState.Unknown); } internal override void TransactionEnlisted(long transactionId) { - SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); + } _connection.TransactionStarted(transactionId, true); // distributed; } internal override void TransactionEnded(long transactionId) { - SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); + } _connection.TransactionEndedByServer(transactionId, TransactionState.Unknown); } internal override void TransactionRolledBack(long transactionId) { - SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); + } // Dev11 1066: ensure delegated transaction is rolled back _connection.TransactionEndedByServer(transactionId, TransactionState.Aborted); @@ -104,7 +123,10 @@ internal override void TransactionRolledBack(long transactionId) internal override void TransactionStarted(long transactionId) { - SqlClientEventSource._log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); + } _connection.TransactionStarted(transactionId, false); // not distributed; } } @@ -121,7 +143,10 @@ internal SqlInternalConnectionSmi(SqlConnectionString connectionOptions, SmiCont _smiEventSink = new EventSink(this); - SqlClientEventSource._log.Trace($" {ObjectID}#, constructed new SMI internal connection\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, constructed new SMI internal connection"); + } } internal SmiContext InternalContext @@ -274,7 +299,10 @@ internal void AutomaticEnlistment() var contextTransactionValue = (null != contextTransaction) ? contextTransaction.GetHashCode() : 0; var currentSystemTransactionValue = (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0; - SqlClientEventSource._log.Trace($" {ObjectID}#, contextTransactionId=0x{contextTransactionId}, contextTransaction={contextTransactionValue}#, currentSystemTransaction={currentSystemTransactionValue}#.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, contextTransactionId=0x{contextTransactionId}, contextTransaction={contextTransactionValue}#, currentSystemTransaction={currentSystemTransactionValue}#."); + } if (SqlInternalTransaction.NullTransactionId != contextTransactionId) { @@ -282,7 +310,11 @@ internal void AutomaticEnlistment() { throw SQL.NestedTransactionScopesNotSupported(); // can't use TransactionScope(RequiresNew) inside a Sql Transaction. } - SqlClientEventSource._log.Trace($" {ObjectID}#, using context transaction with transactionId=0x{contextTransactionId}\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, using context transaction with transactionId=0x{contextTransactionId}"); + } _currentTransaction = new SqlInternalTransaction(this, TransactionType.Context, null, contextTransactionId); ContextTransaction = contextTransaction; } @@ -290,11 +322,17 @@ internal void AutomaticEnlistment() { _currentTransaction = null; // there really isn't a transaction. - SqlClientEventSource._log.Trace($" {ObjectID}#, no transaction.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, no transaction."); + } } else { - SqlClientEventSource._log.Trace($" {ObjectID}#, using current System.Transaction.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, using current System.Transaction."); + } base.Enlist(currentSystemTransaction); } } @@ -307,7 +345,10 @@ override protected void ChangeDatabaseInternal(string database) override protected void InternalDeactivate() { - SqlClientEventSource._log.Trace($" {ObjectID}#, Deactivating.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Deactivating."); + } // When we put this to bed, we should not hold on to the transaction // or any activity (commit/rollback) may cause it to stop responding. @@ -337,14 +378,20 @@ override internal void DelegatedTransactionEnded() { base.DelegatedTransactionEnded(); - SqlClientEventSource._log.Trace($" {ObjectID}#, cleaning up after Delegated Transaction Completion\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, cleaning up after Delegated Transaction Completion"); + } _currentTransaction = null; // clean up our current transaction too } override internal void DisconnectTransaction(SqlInternalTransaction internalTransaction) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Disconnecting Transaction {internalTransaction.ObjectID}#.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Disconnecting Transaction {internalTransaction.ObjectID}#."); + } // VSTS 215465/15029: allow _currentTransaction to be null - it can be cleared before by server's callback Debug.Assert(_currentTransaction == null || _currentTransaction == internalTransaction, "disconnecting different transaction"); @@ -372,7 +419,10 @@ override internal void ExecuteTransaction( var internalTransactionValue = (null != internalTransaction) ? internalTransaction.ObjectID : 0; var internalTransactionIdValue = (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId; - SqlClientEventSource._log.Trace($" {ObjectID}#, transactionRequest={transactionRequest.ToString()}, transactionName='{transactionNameValue}', isolationLevel={iso.ToString()}, internalTransaction=#{internalTransactionIdValue} transactionId=0x{internalTransactionIdValue}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, transactionRequest={transactionRequest.ToString()}, transactionName='{transactionNameValue}', isolationLevel={iso.ToString()}, internalTransaction=#{internalTransactionIdValue} transactionId=0x{internalTransactionIdValue}."); + } switch (transactionRequest) { @@ -427,13 +477,16 @@ override protected byte[] GetDTCAddress() _smiEventSink.ProcessMessagesAndThrow(); - if (null != whereAbouts) - { - SqlClientEventSource._log.TraceBin($" whereAbouts", whereAbouts, (UInt16)whereAbouts.Length); - } - else + if (_log.IsTraceEnabled()) { - SqlClientEventSource._log.Trace($" whereAbouts=null\n"); + if (null != whereAbouts) + { + _log.TraceBin($" whereAbouts", whereAbouts, (ushort)whereAbouts.Length); + } + else + { + _log.Trace($" whereAbouts=null"); + } } return whereAbouts; } @@ -458,7 +511,10 @@ private void OnOutOfScope(object s, EventArgs e) // Called whenever the context goes out of scope, we need to make // sure that we close the connection, or the next person that uses // the context may appear to have the connection in use. - SqlClientEventSource._log.Trace($" {ObjectID}# context is out of scope\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# context is out of scope"); + } // TODO: This is suspect to me -- if I go out of scope, who will commit the transaction? DelegatedTransaction = null; // we don't want to hold this over to the next usage; it will automatically be reused as the context transaction... @@ -486,13 +542,16 @@ private void OnOutOfScope(object s, EventArgs e) override protected void PropagateTransactionCookie(byte[] transactionCookie) { - if (null != transactionCookie) - { - SqlClientEventSource._log.TraceBin($" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); - } - else + if (_log.IsTraceEnabled()) { - SqlClientEventSource._log.Trace($" null\n"); + if (null != transactionCookie) + { + _log.TraceBin($" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); + } + else + { + _log.Trace($" null"); + } } // Propagate the transaction cookie to the server diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs index bead8c2950..f83dc4d71e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs @@ -19,6 +19,7 @@ using Microsoft.Data.ProviderBase; using Microsoft.Identity.Client; using SysTx = System.Transactions; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -515,8 +516,10 @@ internal SqlInternalConnectionTds( ThreadHasParserLockForClose = false; _parserLock.Release(); } - - SqlClientEventSource._log.Trace($" {ObjectID}#, constructed new TDS internal connection\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, constructed new TDS internal connection"); + } } // The erros in the transient error set are contained in @@ -771,7 +774,11 @@ override protected void ChangeDatabaseInternal(string database) override public void Dispose() { - SqlClientEventSource._log.Trace($" {ObjectID}# disposing\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# disposing"); + } + try { TdsParser parser = Interlocked.Exchange(ref _parser, null); // guard against multiple concurrent dispose calls -- Delegated Transactions might cause this. @@ -1362,12 +1369,19 @@ private void CompleteLogin(bool enlistOK) { // ROR should not affect state of connection recovery if (_federatedAuthenticationRequested && !_federatedAuthenticationAcknowledged) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Server did not acknowledge the federated authentication request\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Server did not acknowledge the federated authentication request"); + } + throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged); } if (_federatedAuthenticationInfoRequested && !_federatedAuthenticationInfoReceived) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Server never sent the requested federated authentication info\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Server never sent the requested federated authentication info"); + } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoNotReceived); } @@ -1406,7 +1420,10 @@ private void CompleteLogin(bool enlistOK) _fConnectionOpen = true; // mark connection as open - SqlClientEventSource._log.Trace($" Post-Login Phase: Server connection obtained.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Post-Login Phase: Server connection obtained."); + } // for non-pooled connections, enlist in a distributed transaction // if present - and user specified to enlist @@ -1535,7 +1552,10 @@ private void Login(ServerInfo server, TimeoutTimer timeout, string newPassword, private void LoginFailure() { - SqlClientEventSource._log.Trace($" {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#"); + } // If the parser was allocated and we failed, then we must have failed on // either the Connect or Login, either way we should call Disconnect. @@ -1661,7 +1681,10 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt int routingAttempts = 0; ServerInfo originalServerInfo = serverInfo; // serverInfo may end up pointing to new object due to routing, original object is used to set CurrentDatasource - SqlClientEventSource._log.Trace($" {ObjectID}#, host={serverInfo.UserServerName}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, host={serverInfo.UserServerName}"); + } int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. @@ -1767,7 +1790,10 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt if (_routingInfo != null) { - SqlClientEventSource._log.Trace($" Routed to {serverInfo.ExtendedServerName}"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Routed to {serverInfo.ExtendedServerName}"); + } if (routingAttempts > _maxNumberOfRedirectRoute) { @@ -1856,7 +1882,11 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt // Sleep for a bit to prevent clogging the network with requests, // then update sleep interval for next iteration (max 1 second interval) - SqlClientEventSource._log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]"); + } + Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } @@ -1938,11 +1968,10 @@ TimeoutTimer timeout Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used"); - SqlClientEventSource._log.Trace($" {ObjectID}#, useFailover={useFailoverHost}[bool], primary="); - SqlClientEventSource._log.PutStr(primaryServerInfo.UserServerName); - SqlClientEventSource._log.PutStr(", failover="); - SqlClientEventSource._log.PutStr(failoverHost); - SqlClientEventSource._log.PutStr("\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, useFailover={useFailoverHost}[bool], primary={primaryServerInfo.UserServerName}, failover={failoverHost}"); + } int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. long timeoutUnitInterval; @@ -2010,7 +2039,10 @@ TimeoutTimer timeout // Primary server may give us a different failover partner than the connection string indicates. Update it if (null != ServerProvidedFailOverPartner && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) { - SqlClientEventSource._log.Trace($" {ObjectID}#, new failover partner={ServerProvidedFailOverPartner}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, new failover partner={ServerProvidedFailOverPartner}"); + } failoverServerInfo.SetDerivedNames(protocol, ServerProvidedFailOverPartner); } currentServerInfo = failoverServerInfo; @@ -2043,7 +2075,10 @@ TimeoutTimer timeout } routingAttempts++; - SqlClientEventSource._log.Trace($" Routed to {_routingInfo.ServerName}"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Routed to {_routingInfo.ServerName}"); + } if (_parser != null) _parser.Disconnect(); @@ -2112,7 +2147,10 @@ TimeoutTimer timeout // the network with requests, then update sleep interval for next iteration (max 1 second interval) if (1 == attemptNumber % 2) { - SqlClientEventSource._log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]"); + } Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; @@ -2188,9 +2226,10 @@ private void ResolveExtendedServerName(ServerInfo serverInfo, bool aliasLookup, // Common code path for making one attempt to establish a connection and log in to server. private void AttemptOneLogin(ServerInfo serverInfo, string newPassword, SecureString newSecurePassword, bool ignoreSniOpenTimeout, TimeoutTimer timeout, bool withFailover = false, bool isFirstTransparentAttempt = true, bool disableTnir = false) { - SqlClientEventSource._log.Trace($" {ObjectID}#, timout={timeout.MillisecondsRemaining}[msec], server="); - SqlClientEventSource._log.PutStr(serverInfo.ExtendedServerName); - SqlClientEventSource._log.Trace("\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, timout={timeout.MillisecondsRemaining}[msec], server={serverInfo.ExtendedServerName}"); + } _routingInfo = null; // forget routing information @@ -2342,7 +2381,11 @@ internal bool GetSessionAndReconnectIfNeeded(SqlConnection parent, int timeout = internal void BreakConnection() { var connection = Connection; - SqlClientEventSource._log.Trace($" {ObjectID}#, Breaking connection.\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Breaking connection."); + } DoomThisConnection(); // Mark connection as unusable, so it will be destroyed if (null != connection) { @@ -2434,7 +2477,10 @@ internal void OnEnvChange(SqlEnvChange rec) case TdsEnums.ENV_ROUTING: - SqlClientEventSource._log.Trace($" {ObjectID}#, Received routing info\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Received routing info"); + } if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0) { @@ -2480,7 +2526,10 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) Debug.Assert(fedAuthInfo != null, "info should not be null."); Debug.Assert(_dbConnectionPoolAuthenticationContextKey == null, "_dbConnectionPoolAuthenticationContextKey should be null."); - SqlClientEventSource._log.Trace($" {ObjectID}#, Generating federated authentication token\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Generating federated authentication token"); + } DbConnectionPoolAuthenticationContext dbConnectionPoolAuthenticationContext = null; @@ -2512,7 +2561,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // And on successful login, try to update the cache with the new token. if (contextValidity <= _dbAuthenticationContextUnLockedRefreshTimeSpan) { - SqlClientEventSource._log.Trace($" {ObjectID}#, The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. Current Time is {DateTime.UtcNow.ToLongTimeString()}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, " + + $"The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + + $"The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. Current Time is {DateTime.UtcNow.ToLongTimeString()}."); + } attemptRefreshTokenUnLocked = true; } @@ -2533,7 +2587,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // If a thread is already doing the refresh, just use the existing token in the cache and proceed. else if (contextValidity <= _dbAuthenticationContextLockedRefreshTimeSpan) { - SqlClientEventSource._log.Trace($" {ObjectID}#, The authentication context needs a refresh.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. Current Time is {DateTime.UtcNow.ToLongTimeString()}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, " + + $"The authentication context needs a refresh.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. " + + $"Current Time is {DateTime.UtcNow.ToLongTimeString()}."); + } // Call the function which tries to acquire a lock over the authentication context before trying to update. // If the lock could not be obtained, it will return false, without attempting to fetch a new token. @@ -2547,12 +2606,17 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // Indicate in Bid Trace that we are successful with the update. if (attemptRefreshTokenLocked) { - SqlClientEventSource._log.Trace($" %d#, The attempt to get a new access token succeeded under the locked mode."); + if (_log.IsTraceEnabled()) + { + _log.Trace($" %d#, The attempt to get a new access token succeeded under the locked mode."); + } } } - - SqlClientEventSource._log.Trace($" {ObjectID}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token."); + } } } @@ -2612,13 +2676,21 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP // Else some other thread is already updating it, so just proceed forward with the existing token in the cache. if (dbConnectionPoolAuthenticationContext.LockToUpdate()) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Acquired the lock to update the authentication context.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. Current Time is {DateTime.UtcNow.ToLongTimeString()}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, " + + $"Acquired the lock to update the authentication context.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. " + + $"Current Time is {DateTime.UtcNow.ToLongTimeString()}."); + } authenticationContextLocked = true; } else { - SqlClientEventSource._log.Trace($" {ObjectID}#, Refreshing the context is already in progress by another thread.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Refreshing the context is already in progress by another thread."); + } } if (authenticationContextLocked) @@ -2776,8 +2848,10 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) || _timeout.IsExpired || _timeout.MillisecondsRemaining <= sleepInterval) { - - SqlClientEventSource._log.Trace($" {msalException.ErrorCode}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {msalException.ErrorCode}#"); + } // Error[0] SqlErrorCollection sqlErs = new SqlErrorCollection(); @@ -2796,8 +2870,11 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) throw exc; } - SqlClientEventSource._log.Trace($" {ObjectID}#, sleeping {sleepInterval}[Milliseconds]\n"); - SqlClientEventSource._log.Trace($" {ObjectID}#, remaining {_timeout.MillisecondsRemaining}[Milliseconds]\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, sleeping {sleepInterval}[Milliseconds]"); + _log.Trace($" {ObjectID}#, remaining {_timeout.MillisecondsRemaining}[Milliseconds]"); + } Thread.Sleep(sleepInterval); sleepInterval *= 2; @@ -2814,7 +2891,10 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) _newDbConnectionPoolAuthenticationContext = new DbConnectionPoolAuthenticationContext(fedAuthToken.accessToken, expirationTime); } - SqlClientEventSource._log.Trace($" {ObjectID}#, Finished generating federated authentication token.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Finished generating federated authentication token."); + } return fedAuthToken; } @@ -2878,11 +2958,18 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_FEDAUTH: { - SqlClientEventSource._log.Trace($" {ObjectID}#, Received feature extension acknowledgement for federated authentication\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Received feature extension acknowledgement for federated authentication"); + } if (!_federatedAuthenticationRequested) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Did not request federated authentication\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Did not request federated authentication"); + } + throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); } @@ -2895,14 +2982,22 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // The server shouldn't have sent any additional data with the ack (like a nonce) if (data.Length != 0) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Federated authentication feature extension ack for MSAL and Security Token includes extra data\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, " + + $"Federated authentication feature extension ack for MSAL and Security Token includes extra data"); + } throw SQL.ParsingError(ParsingErrorState.FedAuthFeatureAckContainsExtraData); } break; default: Debug.Fail("Unknown _fedAuthLibrary type"); - SqlClientEventSource._log.Trace($" {ObjectID}#, Attempting to use unknown federated authentication library\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Attempting to use unknown federated authentication library"); + } + throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType); } _federatedAuthenticationAcknowledged = true; @@ -2918,14 +3013,17 @@ internal void OnFeatureExtAck(int featureId, byte[] data) Debug.Assert(newAuthenticationContextInCacheAfterAddOrUpdate != null, "newAuthenticationContextInCacheAfterAddOrUpdate should not be null."); #if DEBUG - // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. - if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) + if (_log.IsTraceEnabled()) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts. \n"); - } - else - { - SqlClientEventSource._log.Trace($" {ObjectID}#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value. \n"); + // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. + if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) + { + _log.Trace($" {ObjectID}#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts."); + } + else + { + _log.Trace($" {ObjectID}#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value."); + } } #endif } @@ -2934,19 +3032,28 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_TCE: { - - SqlClientEventSource._log.Trace($" {ObjectID}#, Received feature extension acknowledgement for TCE\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Received feature extension acknowledgement for TCE"); + } if (data.Length < 1) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Unknown version number for TCE\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Unknown version number for TCE"); + } + throw SQL.ParsingError(ParsingErrorState.TceUnknownVersion); } byte supportedTceVersion = data[0]; if (0 == supportedTceVersion || supportedTceVersion > TdsEnums.MAX_SUPPORTED_TCE_VERSION) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Invalid version number for TCE\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Invalid version number for TCE"); + } throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidVersion, supportedTceVersion); } @@ -2965,11 +3072,18 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS: { - SqlClientEventSource._log.Trace($" {ObjectID}#, Received feature extension acknowledgement for GlobalTransactions\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Received feature extension acknowledgement for GlobalTransactions"); + } if (data.Length < 1) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Unknown version number for GlobalTransactions\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Unknown version number for GlobalTransactions"); + } + throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } @@ -2983,44 +3097,63 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_AZURESQLSUPPORT: { - SqlClientEventSource._log.Trace($" {ObjectID}#, Received feature extension acknowledgement for AzureSQLSupport\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Received feature extension acknowledgement for AzureSQLSupport"); + } if (data.Length < 1) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Unknown token for AzureSQLSupport\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Unknown token for AzureSQLSupport"); + } + throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } IsAzureSQLConnection = true; // Bit 0 for RO/FP support - if ((data[0] & 1) == 1) + if ((data[0] & 1) == 1 && _log.IsTraceEnabled()) { - SqlClientEventSource._log.Trace($" {ObjectID}#, FailoverPartner enabled with Readonly intent for AzureSQL DB\n"); + _log.Trace($" {ObjectID}#, FailoverPartner enabled with Readonly intent for AzureSQL DB"); } break; } case TdsEnums.FEATUREEXT_DATACLASSIFICATION: { - - SqlClientEventSource._log.Trace($" {ObjectID}#, Received feature extension acknowledgement for DATACLASSIFICATION\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Received feature extension acknowledgement for DATACLASSIFICATION"); + } if (data.Length < 1) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION"); + } + throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte supportedDataClassificationVersion = data[0]; if ((0 == supportedDataClassificationVersion) || (supportedDataClassificationVersion > TdsEnums.MAX_SUPPORTED_DATA_CLASSIFICATION_VERSION)) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Invalid version number for DATACLASSIFICATION\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Invalid version number for DATACLASSIFICATION"); + } throw SQL.ParsingErrorValue(ParsingErrorState.DataClassificationInvalidVersion, supportedDataClassificationVersion); } if (data.Length != 2) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION"); + } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte enabled = data[1]; @@ -3030,11 +3163,17 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_UTF8SUPPORT: { - SqlClientEventSource._log.Trace($" {ObjectID}#, Received feature extension acknowledgement for UTF8 support\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Received feature extension acknowledgement for UTF8 support"); + } if (data.Length < 1) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Unknown value for UTF8 support\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Unknown value for UTF8 support"); + } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } break; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs index 73abe5368e..711b6bb8f7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -2,13 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Runtime.CompilerServices; using Microsoft.Data.Common; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -143,8 +143,8 @@ override public void Commit() SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -207,7 +207,7 @@ override public void Commit() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -268,8 +268,12 @@ override public void Rollback() { if (IsYukonPartialZombie) { - // Put something in the trace in case a customer has an issue - SqlClientEventSource._log.Trace($" {ObjectID}# partial zombie no rollback required\n"); + if (_log.IsTraceEnabled()) + { + // Put something in the trace in case a customer has an issue + _log.Trace($" {ObjectID}# partial zombie no rollback required"); + } + _internalTransaction = null; // yukon zombification } else @@ -277,8 +281,8 @@ override public void Rollback() ZombieCheck(); SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); - SqlClientEventSource._log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource._log.Guid}\n"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); + _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -329,7 +333,7 @@ override public void Rollback() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } } @@ -343,7 +347,7 @@ public void Rollback(string transactionName) SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}# transactionName='{transactionName}'"); + var scopeID = _log.ScopeEnter($" {ObjectID}# transactionName='{transactionName}'"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -394,7 +398,7 @@ public void Rollback(string transactionName) _isFromAPI = false; SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -407,7 +411,7 @@ public void Save(string savePointName) SqlStatistics statistics = null; - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}# savePointName='{savePointName}'"); + var scopeID = _log.ScopeEnter($" {ObjectID}# savePointName='{savePointName}'"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -454,7 +458,7 @@ public void Save(string savePointName) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -473,7 +477,10 @@ internal void Zombie() if (null != internalConnection && internalConnection.IsYukonOrNewer && !_isFromAPI) { - SqlClientEventSource._log.Trace($" {ObjectID}# yukon deferred zombie\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# yukon deferred zombie"); + } } else { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index 620653c481..e325c77355 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -21,6 +21,7 @@ using Microsoft.Data.SqlClient.DataClassification; using Microsoft.Data.SqlClient.Server; using Microsoft.Data.SqlTypes; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -502,26 +503,42 @@ internal void Connect(ServerInfo serverInfo, LoadSSPILibrary(); // now allocate proper length of buffer _sniSpnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength]; - SqlClientEventSource._log.Trace($" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication"); + } } else { _sniSpnBuffer = null; if (authType == SqlAuthenticationMethod.ActiveDirectoryPassword) { - SqlClientEventSource._log.Trace($" Active Directory Password authentication\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Active Directory Password authentication"); + } } else if (authType == SqlAuthenticationMethod.SqlPassword) { - SqlClientEventSource._log.Trace($" SQL Password authentication\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" SQL Password authentication"); + } } else if (authType == SqlAuthenticationMethod.ActiveDirectoryInteractive) { - SqlClientEventSource._log.Trace($" Active Directory Interactive authentication\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Active Directory Interactive authentication"); + } } else { - SqlClientEventSource._log.Trace($" SQL authentication\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" SQL authentication"); + } } } @@ -558,7 +575,12 @@ internal void Connect(ServerInfo serverInfo, // don't, the memory for the connection object might not be accurate and thus // a bad error could be returned (as it was when it was freed to early for me). _physicalStateObj.Dispose(); - SqlClientEventSource._log.Trace($" Login failure\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" Login failure"); + } + ThrowExceptionAndWarning(_physicalStateObj); Debug.Fail("SNI returned status != success, but no error thrown?"); } @@ -587,8 +609,12 @@ internal void Connect(ServerInfo serverInfo, UInt32 result = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId); Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Sending prelogin handshake"); + } + // UNDONE - send "" for instance now, need to fix later - SqlClientEventSource._log.Trace($" Sending prelogin handshake\n"); SendPreLoginHandshake(instanceName, encrypt, !string.IsNullOrEmpty(certificate), useOriginalAddressInfo); _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake); @@ -596,13 +622,20 @@ internal void Connect(ServerInfo serverInfo, _physicalStateObj.SniContext = SniContext.Snix_PreLogin; - SqlClientEventSource._log.Trace($" Consuming prelogin handshake\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Consuming prelogin handshake"); + } + PreLoginHandshakeStatus status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, out marsCapable, out _connHandler._fedAuthRequired); if (status == PreLoginHandshakeStatus.InstanceFailure) { - SqlClientEventSource._log.Trace($" Prelogin handshake unsuccessful. Reattempting prelogin handshake\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Prelogin handshake unsuccessful. Reattempting prelogin handshake"); + } _physicalStateObj.Dispose(); // Close previous connection // On Instance failure re-connect and flush SNI named instance cache. @@ -612,14 +645,21 @@ internal void Connect(ServerInfo serverInfo, if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); - SqlClientEventSource._log.Trace($" Login failure\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" Login failure"); + } ThrowExceptionAndWarning(_physicalStateObj); } UInt32 retCode = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId); Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); - SqlClientEventSource._log.Trace($" Sending prelogin handshake\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Sending prelogin handshake"); + } SendPreLoginHandshake(instanceName, encrypt, !string.IsNullOrEmpty(certificate), useOriginalAddressInfo); status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, out marsCapable, out _connHandler._fedAuthRequired); @@ -628,11 +668,18 @@ internal void Connect(ServerInfo serverInfo, // one pre-login packet and know we are connecting to Shiloh. if (status == PreLoginHandshakeStatus.InstanceFailure) { - SqlClientEventSource._log.Trace($" Prelogin handshake unsuccessful. Login failure\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Prelogin handshake unsuccessful. Login failure"); + } throw SQL.InstanceFailure(); } } - SqlClientEventSource._log.Trace($" Prelogin handshake successful\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" Prelogin handshake successful"); + } if (_fMARS && marsCapable) { @@ -725,7 +772,10 @@ internal TdsParserStateObject CreateSession() { TdsParserStateObject session = new TdsParserStateObject(this, (SNIHandle)_pMarsPhysicalConObj.Handle, true); - SqlClientEventSource._log.Trace($" {ObjectID}# created session {session.ObjectID}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# created session {session.ObjectID}"); + } return session; } @@ -741,14 +791,19 @@ internal TdsParserStateObject GetSession(object owner) session = _sessionPool.GetSession(owner); Debug.Assert(!session._pendingData, "pending data on a pooled MARS session"); - - SqlClientEventSource._log.Trace($" {ObjectID}# getting session {session.ObjectID} from pool\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# getting session {session.ObjectID} from pool"); + } } else { session = _physicalStateObj; - SqlClientEventSource._log.Trace($" {ObjectID}# getting physical session {session.ObjectID}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# getting physical session {session.ObjectID}"); + } } Debug.Assert(session._outputPacketNumber == 1, "The packet number is expected to be 1"); return session; @@ -962,7 +1017,11 @@ private void SendPreLoginHandshake(byte[] instanceName, bool encrypt, bool clien int actIdSize = GUID_SIZE + sizeof(UInt32); offset += actIdSize; optionDataSize += actIdSize; - SqlClientEventSource._log.Trace($" ClientConnectionID {_connHandler._clientConnectionId.ToString()}, ActivityID {actId.ToString()}\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" ClientConnectionID {_connHandler._clientConnectionId.ToString()}, ActivityID {actId.ToString()}"); + } break; case (int)PreLoginOptions.FEDAUTHREQUIRED: @@ -1273,7 +1332,12 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod // Only 0x00 and 0x01 are accepted values from the server. if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01) { - SqlClientEventSource._log.Trace($" {ObjectID}#, Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {(int)payload[payloadOffset]}.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, " + + $"Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {(int)payload[payloadOffset]}."); + } + throw SQL.ParsingErrorValue(ParsingErrorState.FedAuthRequiredPreLoginResponseInvalidValue, (int)payload[payloadOffset]); } @@ -1313,10 +1377,12 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod internal void Deactivate(bool connectionIsDoomed) { // Called when the connection that owns us is deactivated. + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# deactivating"); - SqlClientEventSource._log.Trace($" {ObjectID}# deactivating\n"); - - SqlClientEventSource._log.Trace($" {ObjectID}#, {TraceString()}\n"); + _log.Trace($" {ObjectID}#, {TraceString()}"); + } if (MARSOn) { @@ -1472,7 +1538,10 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle Debug.Assert(temp.Count > 0, "TdsParser::ThrowExceptionAndWarning called with no exceptions or warnings!"); if (temp.Count == 0) { - SqlClientEventSource._log.Trace($" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {ObjectID}#"); + } } Debug.Assert(_connHandler != null, "TdsParser::ThrowExceptionAndWarning called with null connectionHandler!"); @@ -2192,7 +2261,11 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead Debug.Fail($"unexpected token; token = {token,-2:X2}"); _state = TdsParserState.Broken; _connHandler.BreakConnection(); - SqlClientEventSource._log.Trace($" Potential multi-threaded misuse of connection, unexpected TDS token found {ObjectID}#\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" Potential multi-threaded misuse of connection, unexpected TDS token found {ObjectID}#"); + } throw SQL.ParsingErrorToken(ParsingErrorState.InvalidTdsTokenReceived, token); // MDAC 82443 } @@ -2514,7 +2587,10 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead } case TdsEnums.SQLLOGINACK: { - SqlClientEventSource._log.Trace($" Received login acknowledgement token\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Received login acknowledgement token"); + } SqlLoginAck ack; if (!TryProcessLoginAck(stateObj, out ack)) { @@ -2536,7 +2612,12 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead { _connHandler._federatedAuthenticationInfoReceived = true; SqlFedAuthInfo info; - SqlClientEventSource._log.Trace($" Received federated authentication info token\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" Received federated authentication info token"); + } + if (!TryProcessFedAuthInfo(stateObj, tokenLength, out info)) { return false; @@ -3948,13 +4029,18 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, SqlFedAuthInfo tempFedAuthInfo = new SqlFedAuthInfo(); // Skip reading token length, since it has already been read in caller - - SqlClientEventSource._log.Trace($" FEDAUTHINFO token stream length = {tokenLen}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" FEDAUTHINFO token stream length = {tokenLen}"); + } if (tokenLen < sizeof(uint)) { // the token must at least contain a DWORD indicating the number of info IDs - SqlClientEventSource._log.Trace($" FEDAUTHINFO token stream length too short for CountOfInfoIDs.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); + } throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen); } @@ -3962,12 +4048,18 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, uint optionsCount; if (!stateObj.TryReadUInt32(out optionsCount)) { - SqlClientEventSource._log.Trace($" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream."); + } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadCountOfInfoIds); } tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount - SqlClientEventSource._log.Trace($" CountOfInfoIDs = {optionsCount.ToString(CultureInfo.InvariantCulture)}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" CountOfInfoIDs = {optionsCount.ToString(CultureInfo.InvariantCulture)}"); + } if (tokenLen > 0) { @@ -3976,11 +4068,17 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, int totalRead = 0; bool successfulRead = stateObj.TryReadByteArray(tokenData, 0, tokenLen, out totalRead); - SqlClientEventSource._log.Trace($" Read rest of FEDAUTHINFO token stream: {BitConverter.ToString(tokenData, 0, totalRead)}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Read rest of FEDAUTHINFO token stream: {BitConverter.ToString(tokenData, 0, totalRead)}"); + } if (!successfulRead || totalRead != tokenLen) { - SqlClientEventSource._log.Trace($" Failed to read FEDAUTHINFO token stream. Attempted to read {tokenLen} bytes, actually read {totalRead}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Failed to read FEDAUTHINFO token stream. Attempted to read {tokenLen} bytes, actually read {totalRead}"); + } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadTokenStream); } @@ -4002,7 +4100,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, uint dataLen = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 1))); uint dataOffset = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 5))); - SqlClientEventSource._log.Trace($" FedAuthInfoOpt: ID={id}, DataLen={dataLen.ToString(CultureInfo.InvariantCulture)}, Offset={dataOffset.ToString(CultureInfo.InvariantCulture)}\n"); + _log.Trace($" FedAuthInfoOpt: ID={id}, DataLen={dataLen.ToString(CultureInfo.InvariantCulture)}, Offset={dataOffset.ToString(CultureInfo.InvariantCulture)}\n"); // offset is measured from optCount, so subtract to make offset measured // from the beginning of tokenData @@ -4014,7 +4112,10 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, // if dataOffset points to a region within FedAuthInfoOpt or after the end of the token, throw if (dataOffset < totalOptionsSize || dataOffset >= tokenLen) { - SqlClientEventSource._log.Trace($" FedAuthInfoDataOffset points to an invalid location.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" FedAuthInfoDataOffset points to an invalid location."); + } throw SQL.ParsingErrorOffset(ParsingErrorState.FedAuthInfoInvalidOffset, unchecked((int)dataOffset)); } @@ -4026,16 +4127,25 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } catch (ArgumentOutOfRangeException e) { - SqlClientEventSource._log.Trace($" Failed to read FedAuthInfoData.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Failed to read FedAuthInfoData."); + } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadData, e); } catch (ArgumentException e) { - SqlClientEventSource._log.Trace($" FedAuthInfoData is not in unicode format.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" FedAuthInfoData is not in unicode format."); + } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e); } - SqlClientEventSource._log.Trace($" FedAuthInfoData: {data}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" FedAuthInfoData: {data}"); + } // store data in tempFedAuthInfo switch ((TdsEnums.FedAuthInfoId)id) @@ -4047,23 +4157,35 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, tempFedAuthInfo.stsurl = data; break; default: - SqlClientEventSource._log.Trace($" Ignoring unknown federated authentication info option: {id}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Ignoring unknown federated authentication info option: {id}"); + } break; } } } else { - SqlClientEventSource._log.Trace($" FEDAUTHINFO token stream is not long enough to contain the data it claims to.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" FEDAUTHINFO token stream is not long enough to contain the data it claims to."); + } throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForData, tokenLen); } - SqlClientEventSource._log.Trace($" Processed FEDAUTHINFO token stream: {tempFedAuthInfo.ToString()}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Processed FEDAUTHINFO token stream: {tempFedAuthInfo.ToString()}"); + } - if (String.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || String.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) + if (string.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || string.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) { // We should be receiving both stsurl and spn - SqlClientEventSource._log.Trace($" FEDAUTHINFO token stream does not contain both STSURL and SPN.\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" FEDAUTHINFO token stream does not contain both STSURL and SPN."); + } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDoesNotContainStsurlAndSpn); } @@ -4491,7 +4613,10 @@ internal bool TryProcessTceCryptoMetadata(TdsParserStateObject stateObj, // validate the index (ordinal passed) if (index >= cipherTable.Value.Size) { - SqlClientEventSource._log.Trace($" Incorrect ordinal received {index}, max tab size: {cipherTable.Value.Size}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Incorrect ordinal received {index}, max tab size: {cipherTable.Value.Size}"); + } throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidOrdinalIntoCipherInfoTable, index); } } @@ -8759,7 +8884,10 @@ internal void TdsLogin(SqlLogin rec, WriteInt(log7Flags, _physicalStateObj); - SqlClientEventSource._log.Trace($" {ObjectID}#, TDS Login7 flags = {log7Flags}:\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, TDS Login7 flags = {log7Flags}:"); + } WriteInt(0, _physicalStateObj); // ClientTimeZone is not used WriteInt(0, _physicalStateObj); // LCID is unused by server @@ -8918,7 +9046,10 @@ internal void TdsLogin(SqlLogin rec, }; if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) { - SqlClientEventSource._log.Trace($" Sending federated authentication feature request\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Sending federated authentication feature request"); + } Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null."); WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true); }; @@ -8992,7 +9123,10 @@ internal void SendFedAuthToken(SqlFedAuthToken fedAuthToken) Debug.Assert(fedAuthToken != null, "fedAuthToken cannot be null"); Debug.Assert(fedAuthToken.accessToken != null, "fedAuthToken.accessToken cannot be null"); - SqlClientEventSource._log.Trace($" Sending federated authentication token\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Sending federated authentication token"); + } _physicalStateObj._outputMessageType = TdsEnums.MT_FEDAUTH; @@ -9384,7 +9518,10 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) { int old_outputPacketNumber = stateObj._outputPacketNumber; - SqlClientEventSource._log.Trace($" Exception caught on ExecuteXXX: '{e.ToString()}' \n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Exception caught on ExecuteXXX: '{e.ToString()}'"); + } if (stateObj.HasOpenResult) { // SQL BU DT 383773 - need to decrement openResultCount if operation failed. @@ -9418,7 +9555,10 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) } } - SqlClientEventSource._log.Trace($" Exception rethrown. \n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Exception rethrown."); + } } internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, bool sync, bool callerHasConnectionLock = false, byte[] enclavePackage = null) @@ -9474,7 +9614,10 @@ internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationReques stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - SqlClientEventSource._log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#"); + } } stateObj.SniContext = SniContext.Snix_Execute; @@ -9603,7 +9746,10 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - SqlClientEventSource._log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#"); + } } stateObj.SniContext = SniContext.Snix_Execute; @@ -10468,10 +10614,11 @@ private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefa var sendDefaultValue = sendDefault ? 1 : 0; - SqlClientEventSource._log.Trace($" {ObjectID}#, Sending parameter '{param.ParameterName}', default flag={sendDefaultValue}, metadata:\n"); - SqlClientEventSource._log.PutStr(metaData.TraceString(3)); - SqlClientEventSource._log.Trace("\n"); - + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, Sending parameter '{param.ParameterName}', default flag={sendDefaultValue}, metadata:{metaData.TraceString(3)}"); + } + // // Write parameter metadata // @@ -11526,7 +11673,7 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio Debug.Assert(-1 <= timeout, "Timeout"); - SqlClientEventSource._log.NotificationsTrace($" NotificationRequest: userData: '{notificationRequest.UserData}', options: '{notificationRequest.Options}', timeout: '{notificationRequest.Timeout}'\n"); + _log.NotificationsTrace($" NotificationRequest: userData: '{notificationRequest.UserData}', options: '{notificationRequest.Options}', timeout: '{notificationRequest.Timeout}'\n"); WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj); // Query notifications Type @@ -11553,7 +11700,10 @@ private void WriteTraceHeaderData(TdsParserStateObject stateObj) stateObj.WriteByteArray(actId.Id.ToByteArray(), GUID_SIZE, 0); // Id (Guid) WriteUnsignedInt(actId.Sequence, stateObj); // sequence number - SqlClientEventSource._log.Trace($" ActivityID {actId.ToString()}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" ActivityID {actId.ToString()}"); + } } private void WriteRPCBatchHeaders(TdsParserStateObject stateObj, SqlNotificationRequest notificationRequest) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index dea9ce05b2..3118813f53 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; using Microsoft.Data.Common; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -37,7 +38,10 @@ internal TdsParserSessionPool(TdsParser parser) _freeStateObjects = new TdsParserStateObject[MaxInactiveCount]; _freeStateObjectCount = 0; - SqlClientEventSource._log.Trace($" {ObjectID}# created session pool for parser {parser.ObjectID}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# created session pool for parser {parser.ObjectID}"); + } } private bool IsDisposed @@ -62,7 +66,7 @@ internal void Deactivate() // cache to make sure they're cleaned up and then we dispose of // sessions that are past what we want to keep around. - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}# deactivating cachedCount={_cachedCount}\n"); + var scopeID = _log.ScopeEnter($" {ObjectID}# deactivating cachedCount={_cachedCount}\n"); try { @@ -83,7 +87,10 @@ internal void Deactivate() { // TODO: consider adding a performance counter for the number of sessions we reclaim - SqlClientEventSource._log.Trace($" {ObjectID}# reclaiming session {session.ObjectID}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# reclaiming session {session.ObjectID}"); + } PutSession(session); } @@ -95,7 +102,7 @@ internal void Deactivate() } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -118,7 +125,10 @@ internal void BestEffortCleanup() internal void Dispose() { - SqlClientEventSource._log.Trace($" {ObjectID}# disposing cachedCount={_cachedCount}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# disposing cachedCount={_cachedCount}"); + } lock (_cache) { @@ -179,7 +189,10 @@ internal TdsParserStateObject GetSession(object owner) // No free objects, create a new one session = _parser.CreateSession(); - SqlClientEventSource._log.Trace($" {ObjectID}# adding session {session.ObjectID} to pool\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# adding session {session.ObjectID} to pool"); + } _cache.Add(session); _cachedCount = _cache.Count; @@ -188,7 +201,10 @@ internal TdsParserStateObject GetSession(object owner) session.Activate(owner); } - SqlClientEventSource._log.Trace($" {ObjectID}# using session {session.ObjectID}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# using session {session.ObjectID}"); + } return session; } @@ -211,7 +227,10 @@ internal void PutSession(TdsParserStateObject session) else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount)) { // Session is good to re-use and our cache has space - SqlClientEventSource._log.Trace($" {ObjectID}# keeping session {session.ObjectID} cachedCount={_cachedCount}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# keeping session {session.ObjectID} cachedCount={_cachedCount}"); + } Debug.Assert(!session._pendingData, "pending data on a pooled session?"); @@ -221,7 +240,10 @@ internal void PutSession(TdsParserStateObject session) else { // Either the session is bad, or we have no cache space - so dispose the session and remove it - SqlClientEventSource._log.Trace($" {ObjectID}# disposing session {session.ObjectID} cachedCount={_cachedCount}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}# disposing session {session.ObjectID} cachedCount={_cachedCount}"); + } bool removed = _cache.Remove(session); Debug.Assert(removed, "session not in pool?"); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index e3885f6818..dcf08c1e20 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -14,6 +14,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Common; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -560,8 +561,11 @@ internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount) return false; } - SqlClientEventSource._log.Trace($" {stateObj.ObjectID}#, NBCROW bitmap received, column count = {columnsCount}\n"); - SqlClientEventSource._log.TraceBin($" NBCROW bitmap data: ", _nullBitmap, (UInt16)_nullBitmap.Length); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {stateObj.ObjectID}#, NBCROW bitmap received, column count = {columnsCount}"); + } + _log.TraceBin($" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); return true; } @@ -914,11 +918,18 @@ internal void DecrementOpenResultCount() internal int DecrementPendingCallbacks(bool release) { int remaining = Interlocked.Decrement(ref _pendingCallbacks); - SqlClientEventSource._log.Trace($" {ObjectID}#, after decrementing _pendingCallbacks: { _pendingCallbacks}\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, after decrementing _pendingCallbacks: { _pendingCallbacks}"); + } if ((0 == remaining || release) && _gcHandle.IsAllocated) { - SqlClientEventSource._log.Trace($" {ObjectID}#, FREEING HANDLE!\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, FREEING HANDLE!"); + } _gcHandle.Free(); } @@ -1027,7 +1038,10 @@ internal int IncrementPendingCallbacks() { int remaining = Interlocked.Increment(ref _pendingCallbacks); - SqlClientEventSource._log.Trace($" {ObjectID}#, after incrementing _pendingCallbacks: {_pendingCallbacks}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, after incrementing _pendingCallbacks: {_pendingCallbacks}"); + } Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}"); return remaining; @@ -2161,7 +2175,10 @@ internal bool TryReadNetworkPacket() _snapshot.CheckStack(new StackTrace()); } #endif - SqlClientEventSource._log.Trace($" Async packet replay\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" Async packet replay"); + } return true; } #if DEBUG @@ -2583,7 +2600,10 @@ internal bool IsConnectionAlive(bool throwOnException) if ((error != TdsEnums.SNI_SUCCESS) && (error != TdsEnums.SNI_WAIT_TIMEOUT)) { // Connection is dead - SqlClientEventSource._log.Trace($" received error {(int)error} on idle connection\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" received error {(int)error} on idle connection"); + } isAlive = false; if (throwOnException) { @@ -2799,7 +2819,10 @@ public void ProcessSniPacket(IntPtr packet, UInt32 error) SniReadStatisticsAndTracing(); - SqlClientEventSource._log.TraceBin($" Packet read", _inBuff, (UInt16)_inBytesRead); + if (_log.IsTraceEnabled()) + { + _log.TraceBin($" Packet read", _inBuff, (UInt16)_inBytesRead); + } AssertValidState(); } @@ -2957,7 +2980,11 @@ public void WriteAsyncCallback(IntPtr key, IntPtr packet, UInt32 sniError) { if (sniError != TdsEnums.SNI_SUCCESS) { - SqlClientEventSource._log.Trace($" write async returned error code {(int)sniError}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" write async returned error code {(int)sniError}"); + } + try { AddError(_parser.ProcessSNIError(this)); @@ -3425,7 +3452,10 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr if (error != TdsEnums.SNI_SUCCESS) { - SqlClientEventSource._log.Trace($" write async returned error code {(int)error}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" write async returned error code {(int)error}"); + } AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(); } @@ -3462,7 +3492,10 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr } else { - SqlClientEventSource._log.Trace($" write async returned error code {(int)sniError}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" write async returned error code {(int)sniError}"); + } AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(callerHasConnectionLock); } @@ -3522,7 +3555,11 @@ internal void SendAttention(bool mustTakeWriteLock = false) UInt32 sniError; _parser._asyncWrite = false; // stop async write SNIWritePacket(Handle, attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false); - SqlClientEventSource._log.Trace($" Send Attention ASync .\n"); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" Send Attention ASync."); + } } finally { @@ -3545,8 +3582,12 @@ internal void SendAttention(bool mustTakeWriteLock = false) _attentionSending = false; } - SqlClientEventSource._log.TraceBin($" Packet sent", _outBuff, (UInt16)_outBytesUsed); - SqlClientEventSource._log.Trace($" Attention sent to the server.\n"); + _log.TraceBin($" Packet sent", _outBuff, (ushort)_outBytesUsed); + + if (_log.IsTraceEnabled()) + { + _log.Trace($" Attention sent to the server."); + } AssertValidState(); } @@ -3730,7 +3771,7 @@ private void SniWriteStatisticsAndTracing() _traceChangePasswordOffset = 0; _traceChangePasswordLength = 0; } - SqlClientEventSource._log.TraceBin($" Packet sent", _outBuff, (UInt16)_outBytesUsed); + _log.TraceBin($" Packet sent", _outBuff, (UInt16)_outBytesUsed); } [Conditional("DEBUG")] diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs index 5fb7aa6d47..07dcb9c1b6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Threading; using Microsoft.Data.Common; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlClient { @@ -53,8 +54,8 @@ internal SqlInternalTransaction(SqlInternalConnection innerConnection, Transacti internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction, long transactionId) { - var outerTransactionObjectId = (null != outerTransaction) ? outerTransaction.ObjectID : -1; - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Created for connection {innerConnection.ObjectID}#, outer transaction {outerTransactionObjectId}#, Type {(int)type}\n"); + + _log.PoolerTrace($" {ObjectID}#, Created for connection {innerConnection.ObjectID}#, outer transaction {((null != outerTransaction) ? outerTransaction.ObjectID : -1)}#, Type {(int)type}"); _innerConnection = innerConnection; _transactionType = type; @@ -270,7 +271,7 @@ internal void CloseFromConnection() Debug.Assert(innerConnection != null, "How can we be here if the connection is null?"); - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Closing\n"); + _log.PoolerTrace($" {ObjectID}#, Closing\n"); bool processFinallyBlock = true; try { @@ -297,7 +298,7 @@ internal void CloseFromConnection() internal void Commit() { - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); if (_innerConnection.IsLockedForBulkCopy) { @@ -342,7 +343,7 @@ internal void Commit() } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -371,7 +372,7 @@ internal void Dispose() private /*protected override*/ void Dispose(bool disposing) { - SqlClientEventSource._log.PoolerTrace($" {ObjectID}#, Disposing\n"); + _log.PoolerTrace($" {ObjectID}#, Disposing\n"); if (disposing) { if (null != _innerConnection) @@ -426,7 +427,7 @@ internal void InitParent(SqlTransaction transaction) internal void Rollback() { - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#"); + var scopeID = _log.ScopeEnter($" {ObjectID}#"); if (_innerConnection.IsLockedForBulkCopy) { @@ -467,13 +468,13 @@ internal void Rollback() } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } internal void Rollback(string transactionName) { - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#, transactionName='{transactionName}'"); + var scopeID = _log.ScopeEnter($" {ObjectID}#, transactionName='{transactionName}'"); if (_innerConnection.IsLockedForBulkCopy) { @@ -516,13 +517,13 @@ internal void Rollback(string transactionName) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } internal void Save(string savePointName) { - var scopeID = SqlClientEventSource._log.ScopeEnter($" {ObjectID}#, savePointName='{savePointName}'"); + var scopeID = _log.ScopeEnter($" {ObjectID}#, savePointName='{savePointName}'"); _innerConnection.ValidateConnectionForExecute(null); @@ -554,7 +555,7 @@ internal void Save(string savePointName) } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs index 25a8bb397d..83eb7be4b3 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs @@ -12,7 +12,7 @@ using System.Diagnostics; using System.Runtime.Versioning; using Microsoft.Data.Common; -using Microsoft.Data.SqlClient; +using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data.SqlTypes { @@ -66,7 +66,7 @@ Int64 allocationSize ) { - var scopeID = SqlClientEventSource._log.ScopeEnter($" { ObjectID}# access={(int)access} options={(int)options} path='{path}'"); + var scopeID = _log.ScopeEnter($" { ObjectID}# access={(int)access} options={(int)options} path='{path}'"); try { @@ -92,7 +92,7 @@ Int64 allocationSize } finally { - SqlClientEventSource._log.ScopeLeave(scopeID); + _log.ScopeLeave(scopeID); } } @@ -715,8 +715,11 @@ Int64 allocationSize UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode); try { - SqlClientEventSource._log.Trace($" {ObjectID}#, desiredAccess=0x{(int)nDesiredAccess}, allocationSize={allocationSize}, " + - $"fileAttributes=0x%{0}, shareAccess=0x{(int)shareAccess}, dwCreateDisposition=0x{dwCreateDisposition}, createOptions=0x{ dwCreateOptions}\n"); + if (_log.IsTraceEnabled()) + { + _log.Trace($" {ObjectID}#, desiredAccess=0x{(int)nDesiredAccess}, allocationSize={allocationSize}, " + + $"fileAttributes=0x%{0}, shareAccess=0x{(int)shareAccess}, dwCreateDisposition=0x{dwCreateDisposition}, createOptions=0x{ dwCreateOptions}"); + } retval = UnsafeNativeMethods.NtCreateFile(out hFile, nDesiredAccess, ref oa, out ioStatusBlock, ref allocationSize, From 2dd437353dcf4d3235c199e377d4ee545f9154b0 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Thu, 30 Jan 2020 14:23:28 -0800 Subject: [PATCH 04/46] EventSource NetFx to Review --- .../src/Microsoft/Data/Common/AdapterUtil.cs | 4 +- .../Data/Common/DBConnectionString.cs | 8 +- .../Data/Common/DbConnectionOptions.cs | 6 +- .../netfx/src/Microsoft/Data/DataException.cs | 8 +- .../Data/ProviderBase/DbConnectionFactory.cs | 48 ++-- .../Data/ProviderBase/DbConnectionInternal.cs | 67 +++-- .../Data/ProviderBase/DbConnectionPool.cs | 174 ++++++++---- .../ProviderBase/DbConnectionPoolGroup.cs | 12 +- .../Data/ProviderBase/SqlConnectionHelper.cs | 26 +- .../Microsoft/Data/SqlClient/LocalDBAPI.cs | 24 +- .../SqlClient/Server/SmiEventSink_Default.cs | 4 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 16 +- .../Data/SqlClient/SqlClientEventSource.cs | 91 ++++--- .../Data/SqlClient/SqlClientLogger.cs | 8 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 197 ++++++++------ .../Microsoft/Data/SqlClient/SqlCommandSet.cs | 16 +- .../Microsoft/Data/SqlClient/SqlConnection.cs | 98 ++++--- .../Data/SqlClient/SqlConnectionFactory.cs | 4 +- .../SqlConnectionPoolGroupProviderInfo.cs | 8 +- .../Data/SqlClient/SqlDataAdapter.cs | 13 +- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 40 +-- .../Data/SqlClient/SqlDataReaderSmi.cs | 38 +-- .../Data/SqlClient/SqlDelegatedTransaction.cs | 24 +- .../Microsoft/Data/SqlClient/SqlDependency.cs | 215 ++++++++++----- .../Data/SqlClient/SqlDependencyListener.cs | 255 +++++++++++------- .../Data/SqlClient/SqlDependencyUtils.cs | 107 +++++--- .../src/Microsoft/Data/SqlClient/SqlError.cs | 4 +- .../Data/SqlClient/SqlInternalConnection.cs | 27 +- .../SqlClient/SqlInternalConnectionSmi.cs | 85 +++--- .../SqlClient/SqlInternalConnectionTds.cs | 184 ++++++------- .../Data/SqlClient/SqlTransaction.cs | 32 ++- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 194 ++++++------- .../Data/SqlClient/TdsParserSessionPool.cs | 32 +-- .../Data/SqlClient/TdsParserStateObject.cs | 54 ++-- .../Data/SqlClient/sqlinternaltransaction.cs | 28 +- .../Microsoft/Data/SqlTypes/SqlFileStream.cs | 8 +- .../EventSource/EventSourceTest.cs | 100 +++++++ ....Data.SqlClient.ManualTesting.Tests.csproj | 1 + 38 files changed, 1353 insertions(+), 907 deletions(-) create mode 100644 src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index 42546f9622..a2f042d863 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -101,9 +101,9 @@ static private void TraceException( string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e && _log.IsTraceEnabled()) + if (null != e && Log.IsTraceEnabled()) { - _log.Trace(e.ToString()); // will include callstack if permission is available + Log.Trace(e.ToString()); // will include callstack if permission is available } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs index 6d9930aaa4..e3f37d5e63 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs @@ -470,9 +470,9 @@ static private string[] NoDuplicateUnion(string[] a, string[] b) private static string[] ParseRestrictions(string restrictions, Hashtable synonyms) { #if DEBUG - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Restrictions='{restrictions}'"); + Log.Trace($" Restrictions='{restrictions}'"); } #endif List restrictionValues = new List(); @@ -489,9 +489,9 @@ private static string[] ParseRestrictions(string restrictions, Hashtable synonym if (!ADP.IsEmpty(keyname)) { #if DEBUG - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" KeyName='{keyname}'"); + Log.Trace($" KeyName='{keyname}'"); } #endif string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144 diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs index ae67c7d69f..061ea12f53 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs @@ -631,17 +631,17 @@ private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hash string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) { // don't trace passwords ever! if (null != keyvalue) { - _log.Trace($" KeyName='{keyname}', KeyValue='{keyvalue}'\n"); + Log.Trace($" KeyName='{keyname}', KeyValue='{keyvalue}'\n"); } else { - _log.Trace($" KeyName='{keyname}'\n"); + Log.Trace($" KeyName='{keyname}'\n"); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs index c1ef0bce8c..6f7b13fb6c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -28,18 +28,18 @@ static private void TraceException( string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e && _log.IsTraceEnabled()) + if (null != e && Log.IsTraceEnabled()) { - _log.Trace(e.Message); + Log.Trace(e.Message); try { - _log.Trace($"{trace}, StackTrace='{Environment.StackTrace}'"); + Log.Trace($"{trace}, StackTrace='{Environment.StackTrace}'"); } catch (System.Security.SecurityException) { // if you don't have permission - you don't get the stack trace - _log.Trace("Permission Denied"); + Log.Trace("Permission Denied"); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index e96aba8d2c..7705eaf4cb 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -66,7 +66,7 @@ internal int ObjectID public void ClearAllPools() { - var scopeID = _log.ScopeEnter(" "); + var scopeID = Log.ScopeEnter(" "); try { Dictionary connectionPoolGroups = _connectionPoolGroups; @@ -81,7 +81,7 @@ public void ClearAllPools() } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -89,7 +89,7 @@ public void ClearPool(DbConnection connection) { ADP.CheckArgumentNull(connection, "connection"); - var scopeID = _log.ScopeEnter($" {GetObjectId(connection)}#"); + var scopeID = Log.ScopeEnter($" {GetObjectId(connection)}#"); try { DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); @@ -100,7 +100,7 @@ public void ClearPool(DbConnection connection) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -109,7 +109,7 @@ public void ClearPool(DbConnectionPoolKey key) Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, "key.ConnectionString"); - var scopeID = _log.ScopeEnter(" connectionString"); + var scopeID = Log.ScopeEnter(" connectionString"); try { DbConnectionPoolGroup poolGroup; @@ -121,7 +121,7 @@ public void ClearPool(DbConnectionPoolKey key) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -153,9 +153,9 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakeNonPooledObject(owningConnection, PerformanceCounters); } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Non-pooled database connection created."); + Log.Trace($" {ObjectID}#, Non-pooled database connection created."); } return newConnection; } @@ -173,9 +173,9 @@ internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbCo newConnection.MakePooledConnection(pool); } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Pooled database connection created."); + Log.Trace($" {ObjectID}#, Pooled database connection created."); } return newConnection; @@ -372,9 +372,9 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour // connection creation failed on semaphore waiting or if max pool reached if (connectionPool.IsRunning) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred."); + Log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred."); } // If GetConnection failed while the pool is running, the pool timeout occurred. @@ -394,9 +394,9 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour if (connection == null) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred and all retries were exhausted."); + Log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred and all retries were exhausted."); } // exhausted all retries or timed out - give up @@ -424,9 +424,9 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti // however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, DisabledPoolGroup={connectionPoolGroup.ObjectID}#"); + Log.Trace($" {ObjectID}#, DisabledPoolGroup={connectionPoolGroup.ObjectID}#"); } // reusing existing pool option in case user originally used SetConnectionPoolOptions @@ -557,10 +557,10 @@ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPo private void PruneConnectionPoolGroups(object state) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { // when debugging this method, expect multiple threads at the same time - _log.Trace($" {ObjectID}#"); + Log.Trace($" {ObjectID}#"); } // First, walk the pool release list and attempt to clear each @@ -582,9 +582,9 @@ private void PruneConnectionPoolGroups(object state) { _poolsToRelease.Remove(pool); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" { ObjectID}#, ReleasePool={pool.ObjectID}#"); + Log.Trace($" { ObjectID}#, ReleasePool={pool.ObjectID}#"); } PerformanceCounters.NumberOfInactiveConnectionPools.Decrement(); @@ -612,9 +612,9 @@ private void PruneConnectionPoolGroups(object state) { _poolGroupsToRelease.Remove(poolGroup); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, ReleasePoolGroup={poolGroup.ObjectID}#"); + Log.Trace($" {ObjectID}#, ReleasePoolGroup={poolGroup.ObjectID}#"); } PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Decrement(); @@ -682,9 +682,9 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { Debug.Assert(null != poolGroup, "null poolGroup?"); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, poolGroup={poolGroup.ObjectID}#"); + Log.Trace($" {ObjectID}#, poolGroup={poolGroup.ObjectID}#"); } lock (_poolGroupsToRelease) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index ed1bde3fa6..14417a2d51 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -163,8 +163,11 @@ protected internal SysTx.Transaction EnlistedTransaction if (null != value) { - int x = value.GetHashCode(); - _log.PoolerTrace($" {ObjectID}#, Transaction {x}#, Enlisting."); + if (Log.IsPoolerTraceEnabled()) + { + int x = value.GetHashCode(); + Log.PoolerTrace($" {ObjectID}#, Transaction {x}#, Enlisting."); + } TransactionOutcomeEnlist(value); } @@ -391,9 +394,9 @@ internal void ActivateConnection(SysTx.Transaction transaction) // Internal method called from the connection pooler so we don't expose // the Activate method publicly. - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.PoolerTrace($" {ObjectID}#, Activating"); + Log.PoolerTrace($" {ObjectID}#, Activating"); } #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); @@ -466,7 +469,8 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac Debug.Assert(null != owningObject, "null owningObject"); Debug.Assert(null != connectionFactory, "null connectionFactory"); - _log.PoolerTrace($" {ObjectID}# Closing."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}# Closing."); // if an exception occurs after the state change but before the try block // the connection will be stuck in OpenBusy state. The commented out try-catch @@ -571,8 +575,8 @@ internal void DeactivateConnection() { // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. - - _log.PoolerTrace($" {ObjectID}#, Deactivating"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Deactivating"); #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); Debug.Assert(0 == activateCount, "activated multiple times?"); @@ -607,9 +611,9 @@ virtual internal void DelegatedTransactionEnded() // you call this method to prevent race conditions with Clear and // ReclaimEmancipatedObjects. - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Delegated Transaction Completed."); + Log.Trace($" {ObjectID}#, Delegated Transaction Completed."); } if (1 == _pooledCount) @@ -673,7 +677,9 @@ public virtual void Dispose() protected internal void DoNotPoolThisConnection() { _cannotBePooled = true; - _log.PoolerTrace($" {ObjectID}#, Marking pooled object as non-poolable so it will be disposed"); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Marking pooled object as non-poolable so it will be disposed"); } /// Ensure that this connection cannot be put back into the pool. @@ -681,7 +687,9 @@ protected internal void DoNotPoolThisConnection() protected internal void DoomThisConnection() { _connectionIsDoomed = true; - _log.PoolerTrace($" {ObjectID}#, Dooming"); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Dooming"); } // Reset connection doomed status so it can be re-connected and pooled. @@ -813,8 +821,11 @@ internal void PrePush(object expectedOwner) { throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time } + //DbConnection x = (expectedOwner as DbConnection); - _log.PoolerTrace($" {ObjectID}#, Preparing to push into pool, owning connection {0}#, pooledCount={ _pooledCount}"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Preparing to push into pool, owning connection {0}#, pooledCount={ _pooledCount}"); + _pooledCount++; _owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2% } @@ -845,7 +856,8 @@ internal void PostPop(object newOwner) _pooledCount--; //DbConnection x = (newOwner as DbConnection); - _log.PoolerTrace($" {ObjectID}#, Preparing to pop from pool, owning connection {0}#, pooledCount={_pooledCount}"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Preparing to pop from pool, owning connection {0}#, pooledCount={_pooledCount}"); //3 // The following tests are retail assertions of things we can't allow to happen. if (null != Pool) @@ -902,9 +914,9 @@ internal void DetachCurrentTransactionIfEnded() // Detach transaction from connection. internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})"); + Log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})"); } // potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new @@ -947,9 +959,9 @@ void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) { SysTx.Transaction transaction = e.Transaction; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})"); + Log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})"); } CleanupTransactionOnCompletion(transaction); @@ -968,20 +980,27 @@ private void TransactionOutcomeEnlist(SysTx.Transaction transaction) internal void SetInStasis() { _isInStasis = true; - _log.PoolerTrace($" {ObjectID}#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose."); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose."); + PerformanceCounters.NumberOfStasisConnections.Increment(); } private void TerminateStasis(bool returningToPool) { - if (returningToPool) - { - _log.PoolerTrace($" { ObjectID}#, Delegated Transaction has ended, connection is closed. Returning to general pool."); - } - else + if (Log.IsPoolerTraceEnabled()) { - _log.PoolerTrace($" {ObjectID}#, Delegated Transaction has ended, connection is closed/leaked. Disposing."); + if (returningToPool) + { + Log.PoolerTrace($" { ObjectID}#, Delegated Transaction has ended, connection is closed. Returning to general pool."); + } + else + { + Log.PoolerTrace($" {ObjectID}#, Delegated Transaction has ended, connection is closed/leaked. Disposing."); + } } + PerformanceCounters.NumberOfStasisConnections.Decrement(); _isInStasis = false; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index 15fa154ae4..2a853d7ad1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -83,7 +83,8 @@ internal TransactedConnectionPool(DbConnectionPool pool) _pool = pool; _transactedCxns = new Dictionary(); - _log.PoolerTrace($" {ObjectID}#, Constructed for connection pool {_pool.ObjectID}#"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Constructed for connection pool {_pool.ObjectID}#"); } internal int ObjectID @@ -140,9 +141,9 @@ internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction) } } - if (null != transactedObject) + if (null != transactedObject && Log.IsPoolerTraceEnabled()) { - _log.PoolerTrace($" { ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Popped."); + Log.PoolerTrace($" { ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Popped."); } return transactedObject; } @@ -169,7 +170,9 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing."); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing."); connections.Add(transactedObject); } @@ -205,14 +208,17 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing."); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing."); connections.Add(transactedObject); } } else { - _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Adding List to transacted pool."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Adding List to transacted pool."); // add the connection/transacted object to the list newConnections.Add(transactedObject); @@ -240,7 +246,9 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt } } } - _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Added."); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Added."); } Pool.PerformanceCounters.NumberOfFreeConnections.Increment(); @@ -249,7 +257,8 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionInternal transactedObject) { - _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed"); TransactedConnectionList connections; int entry = -1; @@ -284,7 +293,8 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern // safely remove the list from the transacted pool. if (0 >= connections.Count) { - _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Removing List from transacted pool."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Removing List from transacted pool."); _transactedCxns.Remove(transaction); // we really need to dispose our connection list; it may have @@ -301,7 +311,8 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern else { //Debug.Assert ( false, "TransactionCompletedEvent fired before PutTransactedObject put the connection in the transacted pool." ); - _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transacted pool not yet created prior to transaction completing. Connection may be leaked."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transacted pool not yet created prior to transaction completing. Connection may be leaked."); } } @@ -529,7 +540,8 @@ internal DbConnectionPool( _poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback _state = State.Running; - _log.PoolerTrace($" {ObjectID}#, Constructed."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Constructed."); //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls // StartBackgroundCallbacks after pool is actually in the collection @@ -678,7 +690,8 @@ private void CleanupCallback(Object state) // With this logic, objects are pruned from the pool if unused for // at least one period but not more than two periods. - _log.PoolerTrace($" {ObjectID}#"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#"); // Destroy free objects that put us above MinPoolSize from old stack. while (Count > MinPoolSize) @@ -753,7 +766,8 @@ private void CleanupCallback(Object state) Debug.Assert(obj != null, "null connection is not expected"); - _log.PoolerTrace($" {ObjectID}#, ChangeStacks={obj.ObjectID}#"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, ChangeStacks={obj.ObjectID}#"); Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); Debug.Assert(obj.CanBePooled, "pooled object is not poolable"); @@ -769,7 +783,8 @@ private void CleanupCallback(Object state) internal void Clear() { - _log.PoolerTrace($" {ObjectID}#, Clearing."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Clearing."); DbConnectionInternal obj; @@ -807,7 +822,8 @@ internal void Clear() // it's been doomed, will cause it to be disposed of as well) ReclaimEmancipatedObjects(); - _log.PoolerTrace($" {ObjectID}#, Cleared."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Cleared."); } private Timer CreateCleanupTimer() @@ -897,7 +913,9 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio } } } - _log.PoolerTrace($" {ObjectID}#, Connection {newObj.ObjectID}#, Added to pool."); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {newObj.ObjectID}#, Added to pool."); // Reset the error wait: _errorWait = ERROR_WAIT_DEFAULT; @@ -958,7 +976,8 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio private void DeactivateObject(DbConnectionInternal obj) { - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Deactivating."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Deactivating."); obj.DeactivateConnection(); // we presume this operation is safe outside of a lock... @@ -1099,11 +1118,13 @@ internal void DestroyObject(DbConnectionInternal obj) // again. if (obj.IsTxRootWaitingForTxEnd) { - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Has Delegated Transaction, waiting to Dispose."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Has Delegated Transaction, waiting to Dispose."); } else { - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removing from pool."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removing from pool."); bool removed = false; lock (_objectList) @@ -1115,19 +1136,22 @@ internal void DestroyObject(DbConnectionInternal obj) if (removed) { - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removed from pool."); + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removed from pool."); PerformanceCounters.NumberOfPooledConnections.Decrement(); } obj.Dispose(); - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Disposed."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Disposed."); + PerformanceCounters.HardDisconnectsPerSecond.Increment(); } } private void ErrorCallback(Object state) { - _log.PoolerTrace($" {ObjectID}#, Resetting Error handling."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Resetting Error handling."); _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); @@ -1302,7 +1326,8 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource {ObjectID}#, DbConnectionInternal State != Running."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, DbConnectionInternal State != Running."); connection = null; return true; } @@ -1348,7 +1373,8 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj PerformanceCounters.SoftConnectsPerSecond.Increment(); - _log.PoolerTrace($" {ObjectID}#, Getting connection."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Getting connection."); // If automatic transaction enlistment is required, then we try to // get the connection from the transacted connection pool first. @@ -1401,19 +1427,24 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj switch (waitResult) { case WAIT_TIMEOUT: - _log.PoolerTrace($" {ObjectID}#, Wait timed out."); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Wait timed out."); + Interlocked.Decrement(ref _waitCount); connection = null; return false; case ERROR_HANDLE: // Throw the error that PoolCreateRequest stashed. - _log.PoolerTrace($" {ObjectID}#, Errors are set."); + Log.PoolerTrace($" {ObjectID}#, Errors are set."); Interlocked.Decrement(ref _waitCount); throw TryCloneCachedException(); case CREATION_HANDLE: - _log.PoolerTrace($" {ObjectID}#, Creating new connection."); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Creating new connection."); try { @@ -1467,7 +1498,9 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj if ((obj != null) && (!obj.IsConnectionAlive())) { - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); + DestroyObject(obj); obj = null; // Setting to null in case creating a new object fails @@ -1478,7 +1511,9 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj RuntimeHelpers.PrepareConstrainedRegions(); try { - _log.PoolerTrace($" {ObjectID}#, Creating new connection."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Creating new connection."); + obj = UserCreateRequest(owningObject, userOptions); } finally @@ -1489,7 +1524,9 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj else { // Timeout waiting for creation semaphore - return null - _log.PoolerTrace($" {ObjectID}#, Wait timed out."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Wait timed out."); + connection = null; return false; } @@ -1499,24 +1536,39 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case WAIT_FAILED: Debug.Assert(waitForMultipleObjectsExHR != 0, "WaitForMultipleObjectsEx failed but waitForMultipleObjectsExHR remained 0"); - _log.PoolerTrace($" {ObjectID}#, Wait failed.\n"); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Wait failed.\n"); + Interlocked.Decrement(ref _waitCount); Marshal.ThrowExceptionForHR(waitForMultipleObjectsExHR); goto default; // if ThrowExceptionForHR didn't throw for some reason case (WAIT_ABANDONED + SEMAPHORE_HANDLE): - _log.PoolerTrace($" {ObjectID}#, Semaphore handle abandonded."); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Semaphore handle abandonded."); + Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(SEMAPHORE_HANDLE, _waitHandles.PoolSemaphore); case (WAIT_ABANDONED + ERROR_HANDLE): - _log.PoolerTrace($" {ObjectID}#, Error handle abandonded."); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Error handle abandonded."); + Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(ERROR_HANDLE, _waitHandles.ErrorEvent); case (WAIT_ABANDONED + CREATION_HANDLE): - _log.PoolerTrace($" {ObjectID}#, Creation handle abandoned."); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Creation handle abandoned."); + Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(CREATION_HANDLE, _waitHandles.CreationSemaphore); default: - _log.PoolerTrace($" {ObjectID}#, WaitForMultipleObjects={waitResult}"); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, WaitForMultipleObjects={waitResult}"); + Interlocked.Decrement(ref _waitCount); throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult); } @@ -1581,7 +1633,9 @@ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal o internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) { PerformanceCounters.SoftConnectsPerSecond.Increment(); - _log.PoolerTrace($" {ObjectID}#, replacing connection."); + + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, replacing connection."); DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); @@ -1624,7 +1678,9 @@ private DbConnectionInternal GetFromGeneralPool() if (null != obj) { - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from general pool."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from general pool."); + PerformanceCounters.NumberOfFreeConnections.Decrement(); } return (obj); @@ -1641,7 +1697,9 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac if (null != obj) { - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from transacted pool."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from transacted pool."); + PerformanceCounters.NumberOfFreeConnections.Decrement(); if (obj.IsTransactionRoot) @@ -1652,14 +1710,18 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac } catch { - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); + DestroyObject(obj); throw; } } else if (!obj.IsConnectionAlive()) { - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); + DestroyObject(obj); obj = null; } @@ -1676,7 +1738,7 @@ private void PoolCreateRequest(object state) // creation mutex has not been obtained - var scopeID = _log.PoolerScopeEnter($" {ObjectID}#"); + var scopeID = Log.PoolerScopeEnter($" {ObjectID}#"); try { @@ -1762,7 +1824,8 @@ private void PoolCreateRequest(object state) else { // trace waitResult and ignore the failure - _log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called WaitForSingleObject failed {waitResult}"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called WaitForSingleObject failed {waitResult}"); } } catch (Exception e) @@ -1776,7 +1839,8 @@ private void PoolCreateRequest(object state) // Now that CreateObject can throw, we need to catch the exception and discard it. // There is no further action we can take beyond tracing. The error will be // thrown to the user the next time they request a connection. - _log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called CreateConnection which threw an exception: {e}"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called CreateConnection which threw an exception: {e}"); } finally { @@ -1796,7 +1860,7 @@ private void PoolCreateRequest(object state) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1810,7 +1874,8 @@ internal void PutNewObject(DbConnectionInternal obj) // against checked bits. // Debug.Assert(obj.CanBePooled, "non-poolable object in pool"); - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Pushing to general pool."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Pushing to general pool."); _stackNew.Push(obj); _waitHandles.PoolSemaphore.Release(1); @@ -1860,7 +1925,8 @@ internal void PutObjectFromTransactedPool(DbConnectionInternal obj) // that is using the connection, and that all pre-push logic has been // done and all transactions are ended. - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Transaction has ended."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Transaction has ended."); if (_state == State.Running && obj.CanBePooled) { @@ -1886,7 +1952,8 @@ private bool ReclaimEmancipatedObjects() { bool emancipatedObjectFound = false; - _log.PoolerTrace($" {ObjectID}#"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#"); List reclaimedObjects = new List(); int count; @@ -1940,7 +2007,9 @@ private bool ReclaimEmancipatedObjects() { DbConnectionInternal obj = reclaimedObjects[i]; - _log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Reclaiming."); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Reclaiming."); + PerformanceCounters.NumberOfReclaimedConnections.Increment(); emancipatedObjectFound = true; @@ -1953,7 +2022,8 @@ private bool ReclaimEmancipatedObjects() internal void Startup() { - _log.PoolerTrace($" {ObjectID}#, CleanupWait={_cleanupWait}"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, CleanupWait={_cleanupWait}"); _cleanupTimer = CreateCleanupTimer(); if (NeedToReplenish) @@ -1964,7 +2034,8 @@ internal void Startup() internal void Shutdown() { - _log.PoolerTrace($" {ObjectID}#\n"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#\n"); _state = State.ShuttingDown; @@ -1987,7 +2058,8 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern Debug.Assert(null != transactedObject, "null transactedObject?"); // Note: connection may still be associated with transaction due to Explicit Unbinding requirement. - _log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed"); // called by the internal connection when it get's told that the // transaction is completed. We tell the transacted pool to remove diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs index 4506ee0b14..468eb149af 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -273,9 +273,9 @@ private bool MarkPoolGroupAsActive() { _state = PoolGroupStateActive; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Active"); + Log.Trace($" {ObjectID}#, Active"); } } return (PoolGroupStateActive == _state); @@ -339,18 +339,18 @@ internal bool Prune() { _state = PoolGroupStateIdle; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Idle"); + Log.Trace($" {ObjectID}#, Idle"); } } else if (PoolGroupStateIdle == _state) { _state = PoolGroupStateDisabled; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Disabled"); + Log.Trace($" {ObjectID}#, Disabled"); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs index e00bea8807..2e83d1a72e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs @@ -87,9 +87,9 @@ internal DbConnectionOptions ConnectionOptions private string ConnectionString_Get() { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#"); + Log.Trace($" {ObjectID}#"); } bool hidePassword = InnerConnection.ShouldHidePassword; @@ -137,9 +137,9 @@ private void ConnectionString_Set(DbConnectionPoolKey key) string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, '{cstr}'"); + Log.Trace($" {ObjectID}#, '{cstr}'"); } } @@ -188,15 +188,15 @@ internal void Abort(Exception e) // NOTE: we put the tracing last, because the ToString() calls (and // the SqlClientEventSource.Log.Trace, for that matter) have no reliability contract and // will end the reliable try... - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { if (e is OutOfMemoryException) { - _log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {"OutOfMemory"}"); + Log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {"OutOfMemory"}"); } else { - _log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {e.ToString()}"); + Log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {e.ToString()}"); } } } @@ -210,7 +210,7 @@ internal void AddWeakReference(object value, int tag) override protected DbCommand CreateDbCommand() { DbCommand command = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); try { DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; @@ -219,7 +219,7 @@ override protected DbCommand CreateDbCommand() } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } return command; } @@ -256,9 +256,9 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)); permissionSet.Demand(); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Connection enlisting in a transaction."); + Log.Trace($" {ObjectID}#, Connection enlisting in a transaction."); } SysTx.Transaction indigoTransaction = null; @@ -286,9 +286,9 @@ override public void EnlistTransaction(SysTx.Transaction transaction) { SqlConnection.ExecutePermission.Demand(); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Connection enlisting in a transaction."); + Log.Trace($" {ObjectID}#, Connection enlisting in a transaction."); } // If we're currently enlisted in a transaction and we were called diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs index 4acb7407ef..299f5259b6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs @@ -74,9 +74,9 @@ static IntPtr UserInstanceDLLHandle SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle); if (s_userInstanceDLLHandle != IntPtr.Zero) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace(" LocalDB - handle obtained"); + Log.Trace(" LocalDB - handle obtained"); } } else @@ -122,9 +122,9 @@ static LocalDBCreateInstanceDelegate LocalDBCreateInstance { int hResult = Marshal.GetLastWin32Error(); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" GetProcAddress for LocalDBCreateInstance error 0x{hResult}"); + Log.Trace($" GetProcAddress for LocalDBCreateInstance error 0x{hResult}"); } throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); @@ -169,9 +169,9 @@ static LocalDBFormatMessageDelegate LocalDBFormatMessage // SNI checks for LocalDBFormatMessage during DLL loading, so it is practically impossibe to get this error. int hResult = Marshal.GetLastWin32Error(); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" GetProcAddress for LocalDBFormatMessage error 0x{hResult}"); + Log.Trace($" GetProcAddress for LocalDBFormatMessage error 0x{hResult}"); } throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); @@ -329,9 +329,9 @@ internal static void CreateLocalDBInstance(string instance) } else { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace(" No system.data.localdb section found in configuration"); + Log.Trace(" No system.data.localdb section found in configuration"); } } s_configurableInstances = tempConfigurableInstances; @@ -360,9 +360,9 @@ internal static void CreateLocalDBInstance(string instance) // LocalDBCreateInstance is thread- and cross-process safe method, it is OK to call from two threads simultaneously int hr = LocalDBCreateInstance(instanceInfo.version, instance, flags: 0); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Starting creation of instance {instance} version {instanceInfo.version}"); + Log.Trace($" Starting creation of instance {instance} version {instanceInfo.version}"); } if (hr < 0) @@ -370,9 +370,9 @@ internal static void CreateLocalDBInstance(string instance) throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_CreateFailed"), instance: instance, localDbError: hr); } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Finished creation of instance {instance}"); + Log.Trace($" Finished creation of instance {instance}"); } instanceInfo.created = true; // mark instance as created } // CreateLocalDbInstance diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs index f2e1854a88..6746f9b67f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs @@ -269,9 +269,9 @@ internal override void MessagePosted(int number, byte state, byte errorClass, st { if (null == _parent) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {0}#, number={number} state={state} errorClass={errorClass} server='{server ?? ""}' message='{message ?? ""}' procedure='{procedure ?? ""}' linenumber={lineNumber}."); + Log.Trace($" {0}#, number={number} state={state} errorClass={errorClass} server='{server ?? ""}' message='{message ?? ""}' procedure='{procedure ?? ""}' linenumber={lineNumber}."); } SqlError error = new SqlError(number, state, errorClass, server, message, procedure, lineNumber); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index bd49a6cb6c..05cbd6609c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs @@ -595,15 +595,16 @@ private Task CreateAndExecuteInitialQueryAsync(out Bulk { string TDSCommand = CreateInitialQuery(); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Initial Query: '{TDSCommand}'"); + Log.Trace($" Initial Query: '{TDSCommand}'"); } } - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls"); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); @@ -894,7 +895,8 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i // private Task SubmitUpdateBulkCommand(string TDSCommand) { - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}\n"); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); @@ -2526,9 +2528,9 @@ private void CheckAndRaiseNotification() _stateObj.BcpLock = true; abortOperation = FireRowsCopiedEvent(_rowsCopied); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace(""); + Log.Trace(""); } // just in case some pathological person closes the target connection ... diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index e9d16be506..410bd0fb36 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -5,13 +5,16 @@ using System.Text; using System.Diagnostics.Tracing; using System.Threading; +using System.Runtime.CompilerServices; +[assembly: InternalsVisibleTo("Microsoft.Data.SqlClient.ManualTesting.Tests")] namespace Microsoft.Data.SqlClient { + [EventSource(Name = "Microsoft.Data.SqlClient.EventSource")] internal class SqlClientEventSource : EventSource { - internal static readonly SqlClientEventSource _log = new SqlClientEventSource(); + internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); private static long s_nextScopeId = 0; private static long s_nextPoolerScopeId = 0; private static long s_nextNotificationScopeId = 0; @@ -30,24 +33,48 @@ internal class SqlClientEventSource : EventSource //Any Prropery added to this class should be a power of 2. public class Keywords { - internal const EventKeywords Default = (EventKeywords)0X0002; //Integer 2 - internal const EventKeywords Trace = (EventKeywords)0x0004; // Integer 4 - internal const EventKeywords Scope = (EventKeywords)0x0008; // Integer 8 - internal const EventKeywords Perf = (EventKeywords)0x0010; // Integer 16 - internal const EventKeywords Resource = (EventKeywords)0x0020; // Integer 32 - internal const EventKeywords Memory = (EventKeywords)0x0040; // Integer 64 - internal const EventKeywords Pooling = (EventKeywords)0x0080; // Integer 128 - internal const EventKeywords Dependency = (EventKeywords)0x0100; // Integer 256 - internal const EventKeywords Correlation = (EventKeywords)0x200; // Integer 512 - internal const EventKeywords NotificationScope = (EventKeywords)0x400; // Integer 1024 - internal const EventKeywords PoolerScope = (EventKeywords)0X800; // Integer 2048 - internal const EventKeywords StringPrintOut = (EventKeywords)0x1000; // Integer 4096 + internal const EventKeywords Trace = (EventKeywords)0x0001; // Integer 1 + internal const EventKeywords Scope = (EventKeywords)0x0002; // Integer 2 + internal const EventKeywords NotificationTrace = (EventKeywords)0x0004; // Integer 4 + internal const EventKeywords Pooling = (EventKeywords)0x0008; // Integer 8 + internal const EventKeywords Correlation = (EventKeywords)0x0010; // Integer 16 + internal const EventKeywords NotificationScope = (EventKeywords)0x0020; // Integer 32 + internal const EventKeywords PoolerScope = (EventKeywords)0X0040; // Integer 64 + internal const EventKeywords StringPrintOut = (EventKeywords)0x0080; // Integer 128 + internal const EventKeywords PoolerTrace = (EventKeywords)0x0200; //Integer 512 + + public static EventKeywords GetAll() + { + return Trace | Scope | NotificationTrace | Pooling | Correlation | NotificationScope | PoolerScope | StringPrintOut; + } } [NonEvent] - internal bool IsTraceEnabled() => _log.IsEnabled(EventLevel.Informational, Keywords.Trace); + internal bool IsTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Trace); + + [NonEvent] + internal bool IsScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Scope); + + [NonEvent] + internal bool IsPoolerScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerScope); + + [NonEvent] + internal bool IsCorrelationEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Correlation); + + [NonEvent] + internal bool IsNotificationScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationScope); + + [NonEvent] + internal bool IsPoolingEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Pooling); + + [NonEvent] + internal bool IsNotificationTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationTrace); + + [NonEvent] + internal bool IsPoolerTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerTrace); + - [Event(TraceEventId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] + [Event(TraceEventId, Level = EventLevel.Informational, Channel = EventChannel.Debug, Keywords = Keywords.Trace)] internal void Trace(string message) { WriteEvent(TraceEventId, message); @@ -58,7 +85,7 @@ internal long ScopeEnter(string message) { StringBuilder MsgstrBldr = new StringBuilder(message); long scopeId = 0; - if (_log.IsEnabled()) + if (Log.IsEnabled()) { scopeId = Interlocked.Increment(ref s_nextScopeId); WriteEvent(EnterScopeId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); @@ -69,7 +96,7 @@ internal long ScopeEnter(string message) [Event(ExitScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] internal void ScopeLeave(long scopeId) { - if (!_log.IsEnabled()) + if (!Log.IsEnabled()) { return; } @@ -79,7 +106,7 @@ internal void ScopeLeave(long scopeId) [Event(TraceBinId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] internal void TraceBin(string message, byte[] whereabout, int length) { - if (_log.IsEnabled(EventLevel.Informational, Keywords.Trace)) + if (Log.IsEnabled(EventLevel.Informational, Keywords.Trace)) { WriteEvent(TraceBinId, message, whereabout, length); } @@ -89,20 +116,17 @@ internal void TraceBin(string message, byte[] whereabout, int length) [Event(CorrelationTraceId, Level = EventLevel.Informational, Keywords = Keywords.Correlation, Opcode = EventOpcode.Start)] internal void CorrelationTrace(string message) { - if (!_log.IsEnabled()) - { - return; - } + WriteEvent(CorrelationTraceId, message); } [Event(NotificationsScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.NotificationScope)] internal long NotificationsScopeEnter(string message) { - StringBuilder MsgstrBldr = new StringBuilder(message); long scopeId = 0; - if (_log.IsEnabled()) + if (Log.IsEnabled()) { + StringBuilder MsgstrBldr = new StringBuilder(message); scopeId = Interlocked.Increment(ref s_nextNotificationScopeId); WriteEvent(NotificationsScopeEnterId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); } @@ -113,11 +137,10 @@ internal long NotificationsScopeEnter(string message) internal long PoolerScopeEnter(string message) { long scopeId = 0; - StringBuilder MsgstrBldr = new StringBuilder(message); - - if (_log.IsEnabled()) + if (Log.IsEnabled()) { - scopeId = Interlocked.Increment(ref s_nextPoolerScopeId); + + StringBuilder MsgstrBldr = new StringBuilder(message); WriteEvent(PoolerScopeEnterId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); } return scopeId; @@ -126,27 +149,19 @@ internal long PoolerScopeEnter(string message) [Event(NotificationsTraceId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] internal void NotificationsTrace(string message) { - if (!_log.IsEnabled(EventLevel.Informational, Keywords.Trace)) - { - return; - } WriteEvent(PoolerScopeEnterId, message); } - [Event(PoolerTraceId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] + [Event(PoolerTraceId, Level = EventLevel.Informational, Keywords = Keywords.PoolerTrace)] internal void PoolerTrace(string message) { - if (!_log.IsEnabled(EventLevel.Informational, Keywords.Trace)) - { - return; - } WriteEvent(PoolerTraceId, message); } [Event(PutStrId, Level = EventLevel.Informational, Keywords = Keywords.StringPrintOut)] internal void PutStr(string message) { - if (_log.IsEnabled(EventLevel.Informational, Keywords.StringPrintOut)) + if (Log.IsEnabled(EventLevel.Informational, Keywords.StringPrintOut)) { WriteEvent(PutStrId, message); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs index 189a518aa2..910a8bb00c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs @@ -19,18 +19,18 @@ internal enum LogLevel /// public void LogInfo(string type, string method, string message) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($"{message}"); + Log.Trace($"{message}"); } } /// public void LogError(string type, string method, string message) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($"{message}"); + Log.Trace($"{message}"); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index 676596f489..e6030ddb46 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -347,9 +347,9 @@ internal CommandEventSink(SqlCommand command) : base() internal override void StatementCompleted(int rowsAffected) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {_command.ObjectID}#, rowsAffected={rowsAffected}."); + Log.Trace($" {_command.ObjectID}#, rowsAffected={rowsAffected}."); } _command.InternalRecordsAffected = rowsAffected; @@ -363,9 +363,9 @@ internal override void StatementCompleted(int rowsAffected) internal override void BatchCompleted() { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {_command.ObjectID}#."); + Log.Trace($" {_command.ObjectID}#."); } } @@ -374,16 +374,16 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp var metaDataLength = (null != metaData) ? metaData.Length : -1; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {_command.ObjectID}# metaData.Length={metaDataLength}."); + Log.Trace($" {_command.ObjectID}# metaData.Length={metaDataLength}."); } - if (null != metaData && _log.IsTraceEnabled()) + if (null != metaData && Log.IsTraceEnabled()) { for (int i = 0; i < metaData.Length; i++) { - _log.Trace($" {_command.ObjectID}#, metaData[{i}] is {metaData[i].GetType().ToString()}{metaData[i].TraceString()}"); + Log.Trace($" {_command.ObjectID}#, metaData[{i}] is {metaData[i].GetType().ToString()}{metaData[i].TraceString()}"); } } @@ -393,9 +393,9 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter parameterValues, int ordinal) { - if (null != metaData && _log.IsTraceEnabled()) + if (null != metaData && Log.IsTraceEnabled()) { - _log.Trace($" {_command.ObjectID}#, metaData[{ordinal}] is {metaData.GetType().ToString()}{ metaData.TraceString()}"); + Log.Trace($" {_command.ObjectID}#, metaData[{ordinal}] is {metaData.GetType().ToString()}{ metaData.TraceString()}"); } Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion); @@ -584,9 +584,9 @@ private SqlCommand(SqlCommand from) : this() var _activeConnectionObjectID = (null != value) ? value.ObjectID : -1; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, {_activeConnectionObjectID}#"); + Log.Trace($" {ObjectID}#, {_activeConnectionObjectID}#"); } } } @@ -665,9 +665,9 @@ public SqlNotificationRequest Notification } set { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#"); + Log.Trace($" {ObjectID}#"); } _sqlDep = null; @@ -719,9 +719,9 @@ internal SqlStatistics Statistics } // TODO: Add objid here - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#"); + Log.Trace($" {ObjectID}#"); } _transaction = value; } @@ -757,13 +757,11 @@ override public string CommandText } set { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#"); + Log.Trace($" {ObjectID}#, String Value = '{value}'"); } - _log.PutStr(value); // Use PutStr to write out entire string - if (0 != ADP.SrcCompare(_commandText, value)) { PropertyChanging(); @@ -800,9 +798,9 @@ override public int CommandTimeout } set { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, {value}"); + Log.Trace($" {ObjectID}#, {value}"); } if (value < 0) @@ -849,9 +847,9 @@ override public CommandType CommandType } set { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, {(int)value}{_commandType}"); + Log.Trace($" {ObjectID}#, {(int)value}{_commandType}"); } if (_commandType != value) { @@ -995,9 +993,9 @@ internal void OnStatementCompleted(int recordCount) { try { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, recordCount={recordCount}"); + Log.Trace($" {ObjectID}#, recordCount={recordCount}"); } handler(this, new StatementCompletedEventArgs(recordCount)); @@ -1037,8 +1035,11 @@ override public void Prepare() } SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + statistics = SqlStatistics.StartTimer(Statistics); // only prepare if batch with parameters @@ -1139,7 +1140,7 @@ override public void Prepare() } SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } private void InternalPrepare() @@ -1203,9 +1204,9 @@ internal void Unprepare() } _cachedMetaData = null; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Command unprepared."); + Log.Trace($" {ObjectID}#, Command unprepared."); } } @@ -1216,8 +1217,10 @@ internal void Unprepare() /// override public void Cancel() { - var scopeID = _log.ScopeEnter($"< sc.SqlCommand.Cancel | API > {ObjectID}#"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}"); + var scopeID = Log.ScopeEnter($"< sc.SqlCommand.Cancel | API > {ObjectID}#"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); SqlStatistics statistics = null; try @@ -1336,7 +1339,7 @@ override public void Cancel() finally { SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1379,8 +1382,10 @@ override public object ExecuteScalar() _pendingCancel = false; SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); bool success = false; int? sqlExceptionNumber = null; @@ -1402,7 +1407,7 @@ override public object ExecuteScalar() finally { SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1447,8 +1452,11 @@ override public int ExecuteNonQuery() _pendingCancel = false; SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + if (Log.IsPoolerTraceEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + bool success = false; int? sqlExceptionNumber = null; try @@ -1468,7 +1476,7 @@ override public int ExecuteNonQuery() finally { SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1484,7 +1492,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) _pendingCancel = false; SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1494,7 +1502,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) finally { SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1510,7 +1518,9 @@ public IAsyncResult BeginExecuteNonQuery() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) { - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + SqlConnection.ExecutePermission.Demand(); return BeginExecuteNonQueryInternal(0, callback, stateObject, 0, inRetry: false); } @@ -1736,7 +1746,8 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) } finally { - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); } } @@ -1754,7 +1765,9 @@ private void ThrowIfReconnectionHasBeenCanceled() private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2015,9 +2028,9 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st { // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Command executed as RPC."); + Log.Trace($" {ObjectID}#, Command executed as RPC."); } SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, methodName, completion, timeout, out task, out usedCache, asyncWrite, inRetry); @@ -2071,8 +2084,11 @@ public XmlReader ExecuteXmlReader() _pendingCancel = false; SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + bool success = false; int? sqlExceptionNumber = null; try @@ -2095,7 +2111,7 @@ public XmlReader ExecuteXmlReader() finally { SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -2112,7 +2128,9 @@ public IAsyncResult BeginExecuteXmlReader() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) { - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + SqlConnection.ExecutePermission.Demand(); return BeginExecuteXmlReaderInternal(CommandBehavior.SequentialAccess, callback, stateObject, 0, inRetry: false); } @@ -2265,13 +2283,16 @@ public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) } finally { - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); } } private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2390,7 +2411,9 @@ public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObjec /// override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + return ExecuteReader(behavior, ADP.ExecuteReader); } @@ -2398,8 +2421,11 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) new public SqlDataReader ExecuteReader() { SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + try { statistics = SqlStatistics.StartTimer(Statistics); @@ -2408,22 +2434,25 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) finally { SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } /// new public SqlDataReader ExecuteReader(CommandBehavior behavior) { - var scopeID = _log.ScopeEnter($" {ObjectID}#, behavior={(int)behavior}"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {_log.Guid}\n"); + var scopeID = Log.ScopeEnter($" {ObjectID}#, behavior={(int)behavior}"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {Log.Guid}"); + try { return ExecuteReader(behavior, ADP.ExecuteReader); } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -2438,7 +2467,9 @@ public IAsyncResult BeginExecuteReader(CommandBehavior behavior) [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior) { - _log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {_log.Guid}\n"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {Log.Guid}"); + SqlConnection.ExecutePermission.Demand(); return BeginExecuteReaderInternal(behavior, callback, stateObject, 0, inRetry: false); } @@ -2520,13 +2551,16 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) } finally { - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); } } private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2927,8 +2961,9 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string /// public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) { + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3013,8 +3048,9 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b /// new public Task ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {Log.Guid}"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {_log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3148,8 +3184,9 @@ public Task ExecuteXmlReaderAsync() /// public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken) { + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3757,9 +3794,9 @@ private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, b // no data reader is returned // use this overload for "batch SQL" tds token type - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Command executed as SQLBATCH."); + Log.Trace($" {ObjectID}#, Command executed as SQLBATCH."); } Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(this.CommandText, timeout, this.Notification, _stateObj, sync: true); @@ -3823,9 +3860,9 @@ private void RunExecuteNonQuerySmi(bool sendToPipe) SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, cmdBehavior={(int)CommandBehavior.Default}."); + Log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, cmdBehavior={(int)CommandBehavior.Default}."); } if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) @@ -5303,9 +5340,9 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // Send over SQL Batch command if we are not a stored proc and have no parameters // MDAC BUG #'s 73776 & 72101 Debug.Assert(!IsUserPrepared, "CommandType.Text with no params should not be prepared!"); - if (returnStream && _log.IsTraceEnabled()) + if (returnStream && Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Command executed as SQLBATCH."); + Log.Trace($" {ObjectID}#, Command executed as SQLBATCH."); } string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior); @@ -5368,9 +5405,9 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // if shiloh, then set NOMETADATA_UNLESSCHANGED flag if (_activeConnection.IsShiloh) rpc.options = TdsEnums.RPC_NOMETADATA; - if (returnStream && _log.IsTraceEnabled()) + if (returnStream && Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Command executed as RPC."); + Log.Trace($" {ObjectID}#, Command executed as RPC."); } // TODO: Medusa: Unprepare only happens for SQL 7.0 which may be broken anyway (it's not re-prepared). Consider removing the reset here if we're really dropping 7.0 support. @@ -5391,9 +5428,9 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // then batch sql them over. This is inefficient (3 round trips) but the only way we can get metadata only from // a stored proc optionSettings = GetSetOptionsString(cmdBehavior); - if (returnStream && _log.IsTraceEnabled()) + if (returnStream && Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Command executed as RPC."); + Log.Trace($" {ObjectID}#, Command executed as RPC."); } // turn set options ON if (null != optionSettings) @@ -5488,9 +5525,9 @@ private SqlDataReader RunExecuteReaderSmi(CommandBehavior cmdBehavior, RunBehavi SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, commandBehavior={(int)cmdBehavior}."); + Log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, commandBehavior={(int)cmdBehavior}."); } if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) @@ -5712,9 +5749,9 @@ public SqlCommand Clone() { SqlCommand clone = new SqlCommand(this); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, clone={clone.ObjectID}#"); + Log.Trace($" {ObjectID}#, clone={clone.ObjectID}#"); } return clone; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index b543c5726d..b7641d156c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -130,9 +130,9 @@ internal int ObjectID internal void Append(SqlCommand command) { ADP.CheckArgumentNull(command, "command"); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, command={command.ObjectID}, parameterCount={command.Parameters.Count}"); + Log.Trace($" {ObjectID}#, command={command.ObjectID}, parameterCount={command.Parameters.Count}"); } string cmdText = command.CommandText; @@ -268,9 +268,9 @@ internal static void BuildStoredProcedureName(StringBuilder builder, string part internal void Clear() { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#"); + Log.Trace($" {ObjectID}#"); } DbCommand batchCommand = BatchCommand; @@ -288,9 +288,9 @@ internal void Clear() internal void Dispose() { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#"); + Log.Trace($" {ObjectID}#"); } SqlCommand command = _batchCommand; @@ -307,7 +307,7 @@ internal int ExecuteNonQuery() { SqlConnection.ExecutePermission.Demand(); - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); try { if (Connection.IsContextConnection) @@ -327,7 +327,7 @@ internal int ExecuteNonQuery() } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index 8bde1b76cd..7983c94625 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -1103,7 +1103,7 @@ public SqlTransaction BeginTransaction(string transactionName) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { - var scopeID = _log.ScopeEnter($" {ObjectID}#, isolationLevel={(int)isolationLevel}"); + var scopeID = Log.ScopeEnter($" {ObjectID}#, isolationLevel={(int)isolationLevel}"); try { @@ -1119,7 +1119,7 @@ override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLeve } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1129,7 +1129,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam WaitForPendingReconnection(); SqlStatistics statistics = null; string xactName = ADP.IsEmpty(transactionName) ? "None" : transactionName; - var scopeID = _log.ScopeEnter($" {ObjectID}#, iso={(int)iso}, transactionName='{xactName}'\n"); + var scopeID = Log.ScopeEnter($" {ObjectID}#, iso={(int)iso}, transactionName='{xactName}'"); try { @@ -1157,7 +1157,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); SqlStatistics.StopTimer(statistics); } } @@ -1167,7 +1167,10 @@ override public void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -1260,8 +1263,11 @@ void CloseInnerConnection() /// override public void Close() { - var scopeID = _log.ScopeEnter($" {ObjectID}#"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + try { SqlStatistics statistics = null; @@ -1343,7 +1349,8 @@ override public void Close() { SqlDebugContext sdc = _sdc; _sdc = null; - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); + if (sdc != null) { sdc.Dispose(); @@ -1396,8 +1403,10 @@ public void EnlistDistributedTransaction(System.EnterpriseServices.ITransaction /// override public void Open() { - var scopeID = _log.ScopeEnter($" ObjectID: {ObjectID}, ActivityID {_log.Guid}\n"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); + var scopeID = Log.ScopeEnter($" ObjectID: {ObjectID}, ActivityID {Log.Guid}"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); try { @@ -1431,7 +1440,7 @@ override public void Open() } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1465,9 +1474,9 @@ private async Task ReconnectAsync(int timeout) { if (ctoken.IsCancellationRequested) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Orginal ClientConnectionID: {_originalConnectionId.ToString()} - reconnection cancelled."); + Log.Trace($" Orginal ClientConnectionID: {_originalConnectionId.ToString()} - reconnection cancelled."); } return; } @@ -1490,24 +1499,24 @@ private async Task ReconnectAsync(int timeout) ForceNewConnection = false; } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Reconnection suceeded. ClientConnectionID {_originalConnectionId.ToString()} -> {ClientConnectionId.ToString()}"); + Log.Trace($" Reconnection suceeded. ClientConnectionID {_originalConnectionId.ToString()} -> {ClientConnectionId.ToString()}"); } return; } catch (SqlException e) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Orginal ClientConnectionID {_originalConnectionId} - reconnection attempt failed error {e.Message}"); + Log.Trace($" Orginal ClientConnectionID {_originalConnectionId} - reconnection attempt failed error {e.Message}"); } if (attempt == retryCount - 1) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Orginal ClientConnectionID {_originalConnectionId.ToString()} - give up reconnection"); + Log.Trace($" Orginal ClientConnectionID {_originalConnectionId.ToString()} - give up reconnection"); } throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); @@ -1576,9 +1585,9 @@ internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Connection ClientConnectionID {_originalConnectionId.ToString()} is invalid, reconnecting"); + Log.Trace($" Connection ClientConnectionID {_originalConnectionId.ToString()} is invalid, reconnecting"); } _recoverySessionData = cData; if (beforeDisconnect != null) @@ -1671,8 +1680,11 @@ void CancelOpenAndWait() /// public override Task OpenAsync(CancellationToken cancellationToken) { - var scopeID = _log.PoolerScopeEnter($" {ObjectID}#"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); + var scopeID = Log.PoolerScopeEnter($" {ObjectID}#"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + try { @@ -1749,7 +1761,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1770,9 +1782,9 @@ public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource retryTask) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {_parent.ObjectID}#"); + Log.Trace($" {_parent.ObjectID}#"); } _registration.Dispose(); try @@ -2120,9 +2132,9 @@ internal void OnError(SqlException exception, bool breakConnection, Action {ObjectID}#, Connection broken."); + Log.Trace($" {ObjectID}#, Connection broken."); } Close(); @@ -2133,9 +2145,9 @@ internal void OnError(SqlException exception, bool breakConnection, Action {ObjectID}#, Connection broken."); + Log.Trace($" {ObjectID}#, Connection broken."); } Close(); } @@ -2245,9 +2257,9 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) Debug.Assert(null != imevent, "null SqlInfoMessageEventArgs"); var imeventValue = (null != imevent) ? imevent.Message : ""; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Message='{imeventValue}'"); + Log.Trace($" {ObjectID}#, Message='{imeventValue}'"); } SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage]; @@ -2462,8 +2474,11 @@ private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, s /// public static void ChangePassword(string connectionString, string newPassword) { - var scopeID = _log.ScopeEnter(""); - _log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); + var scopeID = Log.ScopeEnter(""); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + try { if (ADP.IsEmpty(connectionString)) @@ -2502,15 +2517,18 @@ public static void ChangePassword(string connectionString, string newPassword) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } /// public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { - var scopeID = _log.ScopeEnter(""); - _log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}\n"); + var scopeID = Log.ScopeEnter(""); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + try { if (ADP.IsEmpty(connectionString)) @@ -2572,7 +2590,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -2678,9 +2696,9 @@ private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) Debug.Assert(TypeSystemAssemblyVersion != null, "TypeSystemAssembly should be set !"); if (string.Compare(asmRef.Name, "Microsoft.SqlServer.Types", StringComparison.OrdinalIgnoreCase) == 0) { - if (asmRef.Version != TypeSystemAssemblyVersion && _log.IsTraceEnabled()) + if (asmRef.Version != TypeSystemAssemblyVersion && Log.IsTraceEnabled()) { - _log.Trace($" SQL CLR type version change: Server sent {asmRef.Version.ToString()}, client will instantiate {TypeSystemAssemblyVersion.ToString()}"); + Log.Trace($" SQL CLR type version change: Server sent {asmRef.Version.ToString()}, client will instantiate {TypeSystemAssemblyVersion.ToString()}"); } asmRef.Version = TypeSystemAssemblyVersion; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs index 807959fa02..bcba61d1ba 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs @@ -194,9 +194,9 @@ override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions connectionTimeout *= 10; } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($"Set connection pool CreateTimeout={connectionTimeout} when AD Interactive is in use."); + Log.Trace($"Set connection pool CreateTimeout={connectionTimeout} when AD Interactive is in use."); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs index 3af5b4261e..7dd791afcd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs @@ -56,9 +56,9 @@ internal void AliasCheck(string server) } else if (_alias != server) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" alias change detected. Clearing PoolGroup"); + Log.Trace($" alias change detected. Clearing PoolGroup"); } base.PoolGroup.Clear(); @@ -104,9 +104,9 @@ internal void FailoverCheck(SqlInternalConnection connection, bool actualUseFail if (UseFailoverPartner != actualUseFailoverPartner) { // TODO: will connections in progress somehow be active for two different datasources? - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Failover detected. failover partner='{actualFailoverPartner}'. Clearing PoolGroup"); + Log.Trace($" Failover detected. failover partner='{actualFailoverPartner}'. Clearing PoolGroup"); } base.PoolGroup.Clear(); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index 660ce00c4d..0b3adfa9ee 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -144,9 +144,9 @@ override public int UpdateBatchSize } _updateBatchSize = value; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, {value}"); + Log.Trace($" {ObjectID}#, {value}"); } } } @@ -254,7 +254,10 @@ override protected RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, override protected int ExecuteBatch() { Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls"); + return _commandSet.ExecuteNonQuery(); } @@ -277,9 +280,9 @@ override protected bool GetBatchedRecordsAffected(int commandIdentifier, out int /// override protected void InitializeBatching() { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#"); + Log.Trace($" {ObjectID}#"); } _commandSet = new SqlCommandSet(); SqlCommand command = SelectCommand; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs index 37433bc318..7f6f08aa32 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -940,7 +940,7 @@ private void CleanPartialReadReliable() override public void Close() { SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1026,7 +1026,7 @@ override public void Close() finally { SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1670,7 +1670,7 @@ override public int GetProviderSpecificValues(object[] values) override public DataTable GetSchemaTable() { SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1693,7 +1693,7 @@ override public DataTable GetSchemaTable() finally { SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -3601,7 +3601,7 @@ override public bool NextResult() private bool TryNextResult(out bool more) { SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -3779,7 +3779,7 @@ private bool TryNextResult(out bool more) finally { SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -3807,7 +3807,7 @@ override public bool Read() private bool TryReadInternal(bool setTimeout, out bool more) { SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -4009,7 +4009,7 @@ private bool TryReadInternal(bool setTimeout, out bool more) finally { SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -4474,7 +4474,9 @@ private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateO // broken connection, so check state first. if (parser.State == TdsParserState.OpenLoggedIn) { - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls\n"); + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID '{Log.Guid}'"); + Task executeTask = parser.TdsExecuteSQLBatch(_resetOptionsString, (_command != null) ? _command.CommandTimeout : 0, null, stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -4786,7 +4788,7 @@ private void AssertReaderState(bool requireData, bool permitAsync, int? columnIn /// public override Task NextResultAsync(CancellationToken cancellationToken) { - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); try { @@ -4832,9 +4834,9 @@ public override Task NextResultAsync(CancellationToken cancellationToken) { if (t != null) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" attempt retry {ObjectID}#"); + Log.Trace($" attempt retry {ObjectID}#"); } PrepareForAsyncContinuation(); } @@ -4853,7 +4855,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -4917,9 +4919,9 @@ internal Task GetBytesAsync(int i, byte[] buffer, int index, int length, in { if (t != null) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" attempt retry {ObjectID}#"); + Log.Trace($" attempt retry {ObjectID}#"); } PrepareForAsyncContinuation(); @@ -5092,7 +5094,7 @@ private Task GetBytesAsyncReadDataStage(int i, byte[] buffer, int index, in /// public override Task ReadAsync(CancellationToken cancellationToken) { - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); try { @@ -5213,9 +5215,9 @@ public override Task ReadAsync(CancellationToken cancellationToken) { if (t != null) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" attempt retry {ObjectID}#"); + Log.Trace($" attempt retry {ObjectID}#"); } PrepareForAsyncContinuation(); @@ -5256,7 +5258,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs index c91a1dbdc6..77771e2898 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs @@ -376,7 +376,7 @@ public override void Close() private void CloseInternal(bool closeConnection) { - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); bool processFinallyBlock = true; try { @@ -412,7 +412,7 @@ private void CloseInternal(bool closeConnection) Connection.Close(); } - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } } @@ -435,7 +435,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) { - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); try { _hasRows = false; @@ -468,7 +468,7 @@ internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -488,7 +488,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) internal unsafe bool InternalRead(bool ignoreNonFatalErrors) { - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); try { // Don't move unless currently in results. @@ -527,7 +527,7 @@ internal unsafe bool InternalRead(bool ignoreNonFatalErrors) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1319,16 +1319,16 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs { var mdLength = (null != md) ? md.Length : -1; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {reader.ObjectID}#, md.Length={mdLength} nextEventIsRow={nextEventIsRow}."); + Log.Trace($" {reader.ObjectID}#, md.Length={mdLength} nextEventIsRow={nextEventIsRow}."); if (null != md) { for (int i = 0; i < md.Length; i++) { - _log.Trace($" {reader.ObjectID}#, metaData[{i}] is {md[i].GetType().ToString()}{md[i].TraceString()}"); + Log.Trace($" {reader.ObjectID}#, metaData[{i}] is {md[i].GetType().ToString()}{md[i].TraceString()}"); } } } @@ -1338,36 +1338,36 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs // Obsolete V2- method internal override void RowAvailable(ITypedGetters row) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {reader.ObjectID}# (v2)."); + Log.Trace($" {reader.ObjectID}# (v2)."); } this.reader.RowAvailable(row); } internal override void RowAvailable(ITypedGettersV3 row) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {reader.ObjectID}# (ITypedGettersV3)."); + Log.Trace($" {reader.ObjectID}# (ITypedGettersV3)."); } this.reader.RowAvailable(row); } internal override void RowAvailable(SmiTypedGetterSetter rowData) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {reader.ObjectID}# (SmiTypedGetterSetter)."); + Log.Trace($" {reader.ObjectID}# (SmiTypedGetterSetter)."); } this.reader.RowAvailable(rowData); } internal override void StatementCompleted(int recordsAffected) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {reader.ObjectID}# recordsAffected= {recordsAffected}."); + Log.Trace($" {reader.ObjectID}# recordsAffected= {recordsAffected}."); } // devnote: relies on SmiEventSink_Default to pass event to parent @@ -1379,9 +1379,9 @@ internal override void StatementCompleted(int recordsAffected) internal override void BatchCompleted() { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {reader.ObjectID}#."); + Log.Trace($" {reader.ObjectID}#."); } // devnote: relies on SmiEventSink_Default to pass event to parent diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs index d789ff5afd..e69977d465 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs @@ -89,9 +89,9 @@ public void Initialize() // transaction. SqlInternalConnection connection = _connection; SqlConnection usersConnection = connection.Connection; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, delegating transaction."); + Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, delegating transaction."); } RuntimeHelpers.PrepareConstrainedRegions(); @@ -108,9 +108,9 @@ public void Initialize() #endif //DEBUG if (connection.IsEnlistedInTransaction) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, was enlisted, now defecting."); + Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, was enlisted, now defecting."); } // defect first @@ -173,9 +173,9 @@ public Byte[] Promote() byte[] returnValue = null; SqlConnection usersConnection = connection.Connection; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, promoting transaction."); + Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, promoting transaction."); } RuntimeHelpers.PrepareConstrainedRegions(); @@ -275,9 +275,9 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) SqlInternalConnection connection = GetValidConnection(); SqlConnection usersConnection = connection.Connection; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, aborting transaction."); + Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, aborting transaction."); } RuntimeHelpers.PrepareConstrainedRegions(); @@ -371,9 +371,9 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) SqlInternalConnection connection = GetValidConnection(); SqlConnection usersConnection = connection.Connection; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, committing transaction."); + Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, committing transaction."); } RuntimeHelpers.PrepareConstrainedRegions(); @@ -504,9 +504,9 @@ internal void TransactionEnded(SysTx.Transaction transaction) if (connection != null) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, transaction completed externally."); + Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, transaction completed externally."); } lock (connection) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs index c8e046ec23..22522a6d2f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -317,7 +317,7 @@ public SqlDependency(SqlCommand command) : this(command, null, SQL.SqlDependency [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public SqlDependency(SqlCommand command, string options, int timeout) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, options: '{options}', timeout: '{timeout}'"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, options: '{options}', timeout: '{timeout}'"); try { if (InOutOfProcHelper.InProc) @@ -340,7 +340,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -437,7 +437,7 @@ public event OnChangeEventHandler OnChange // EventHandlers to be fired when dependency is notified. add { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { if (null != value) @@ -447,13 +447,18 @@ public event OnChangeEventHandler OnChange lock (_eventHandlerLock) { if (_dependencyFired) - { // If fired, fire the new event immediately. - _log.NotificationsTrace($" Dependency already fired, firing new event.\n"); + { + // If fired, fire the new event immediately. + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Dependency already fired, firing new event."); + sqlNotificationEvent = new SqlNotificationEventArgs(SqlNotificationType.Subscribe, SqlNotificationInfo.AlreadyChanged, SqlNotificationSource.Client); } else { - _log.NotificationsTrace($" Dependency has not fired, adding new event.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Dependency has not fired, adding new event."); + EventContextPair pair = new EventContextPair(value, this); if (!_eventList.Contains(pair)) { @@ -474,12 +479,12 @@ public event OnChangeEventHandler OnChange } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } remove { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { if (null != value) @@ -497,7 +502,7 @@ public event OnChangeEventHandler OnChange } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } } @@ -514,7 +519,7 @@ public void AddCommandDependency(SqlCommand command) { // Adds command to dependency collection so we automatically create the SqlNotificationsRequest object // and listen for a notification for the added commands. - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { if (command == null) @@ -526,7 +531,7 @@ public void AddCommandDependency(SqlCommand command) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -552,9 +557,12 @@ private static void ObtainProcessDispatcher() if (nativeStorage == null) { - _log.NotificationsTrace($" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher."); + #if DEBUG // Possibly expensive, limit to debug. - _log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); #endif _AppDomain masterDomain = SNINativeMethodWrapper.GetDefaultAppDomain(); @@ -579,32 +587,43 @@ private static void ObtainProcessDispatcher() } else { - _log.NotificationsTrace($" ERROR - ObjectHandle.Unwrap returned null!\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" ERROR - ObjectHandle.Unwrap returned null!"); + throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyObtainProcessDispatcherFailureObjectHandle); } } else { - _log.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!"); + throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureCreateInstance); } } else { - _log.NotificationsTrace(" ERROR - unable to obtain default AppDomain!\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - unable to obtain default AppDomain!"); + throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureAppDomain); } } else { - _log.NotificationsTrace(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher."); + #if DEBUG // Possibly expensive, limit to debug. - _log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); #endif BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(nativeStorage); _processDispatcher = GetDeserializedObject(formatter, stream); // Deserialize and set for appdomain. - _log.NotificationsTrace($" processDispatcher obtained, ID: {_processDispatcher.ObjectID}\n"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" processDispatcher obtained, ID: {_processDispatcher.ObjectID}"); } } @@ -651,7 +670,7 @@ public static bool Start(string connectionString, string queue) internal static bool Start(string connectionString, string queue, bool useDefaults) { - var scopeID = _log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); + var scopeID = Log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -724,7 +743,8 @@ internal static bool Start(string connectionString, string queue, bool useDefaul SqlDependencyPerAppDomainDispatcher.SingletonInstance, out errorOccurred, out appDomainStart); - _log.NotificationsTrace($" Start (defaults) returned: '{result}', with service: '{service}', server: '{server}', database: '{database}'\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Start (defaults) returned: '{result}', with service: '{service}', server: '{server}', database: '{database}'"); } finally { @@ -746,7 +766,9 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - _log.NotificationsTrace(" Exception occurred from Stop() after duplicate was found on Start().\n"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" Exception occurred from Stop() after duplicate was found on Start()."); } throw SQL.SqlDependencyDuplicateStart(); } @@ -759,7 +781,9 @@ internal static bool Start(string connectionString, string queue, bool useDefaul queue, _appDomainKey, SqlDependencyPerAppDomainDispatcher.SingletonInstance); - _log.NotificationsTrace($" Start (user provided queue) returned: '{result}'\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Start (user provided queue) returned: '{result}'"); + // No need to call AddToServerDatabaseHash since if not using default queue user is required // to provide options themselves. } @@ -773,7 +797,9 @@ internal static bool Start(string connectionString, string queue, bool useDefaul ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - _log.NotificationsTrace($" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...).\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); + throw; } } @@ -782,7 +808,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -802,7 +828,7 @@ public static bool Stop(string connectionString, string queue) internal static bool Stop(string connectionString, string queue, bool useDefaults, bool startFailed) { - var scopeID = _log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); + var scopeID = Log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -912,7 +938,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -922,7 +948,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault private static bool AddToServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - var scopeID = _log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); + var scopeID = Log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); try { bool result = false; @@ -933,7 +959,9 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!_serverUserHash.ContainsKey(server)) { - _log.NotificationsTrace(" Hash did not contain server, adding.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" Hash did not contain server, adding."); + identityDatabaseHash = new Dictionary>(); _serverUserHash.Add(server, identityDatabaseHash); } @@ -946,7 +974,9 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!identityDatabaseHash.ContainsKey(identityUser)) { - _log.NotificationsTrace(" Hash contained server but not user, adding user.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" Hash contained server but not user, adding user."); + databaseServiceList = new List(); identityDatabaseHash.Add(identityUser, databaseServiceList); } @@ -957,13 +987,14 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!databaseServiceList.Contains(databaseService)) { - _log.NotificationsTrace(" Adding database.\n"); + Log.NotificationsTrace(" Adding database.\n"); databaseServiceList.Add(databaseService); result = true; } else { - _log.NotificationsTrace(" ERROR - hash already contained server, user, and database - we will throw!.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - hash already contained server, user, and database - we will throw!."); } } @@ -971,13 +1002,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } private static void RemoveFromServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - var scopeID = _log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); + var scopeID = Log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); try { lock (_serverUserHash) @@ -997,43 +1028,55 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair int index = databaseServiceList.IndexOf(databaseService); if (index >= 0) { - _log.NotificationsTrace(" Hash contained server, user, and database - removing database.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" Hash contained server, user, and database - removing database."); + databaseServiceList.RemoveAt(index); if (databaseServiceList.Count == 0) { - _log.NotificationsTrace(" databaseServiceList count 0, removing the list for this server and user.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" databaseServiceList count 0, removing the list for this server and user."); + identityDatabaseHash.Remove(identityUser); if (identityDatabaseHash.Count == 0) { - _log.NotificationsTrace(" identityDatabaseHash count 0, removing the hash for this server.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" identityDatabaseHash count 0, removing the hash for this server."); + _serverUserHash.Remove(server); } } } else { - _log.NotificationsTrace(" ERROR - hash contained server and user but not database!\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - hash contained server and user but not database!"); + Debug.Assert(false, "Unexpected state - hash did not contain database!"); } } else { - _log.NotificationsTrace(" ERROR - hash contained server but not user!\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - hash contained server but not user!"); + Debug.Assert(false, "Unexpected state - hash did not contain user!"); } } else { - _log.NotificationsTrace(" ERROR - hash did not contain server!\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - hash did not contain server!"); + Debug.Assert(false, "Unexpected state - hash did not contain server!"); } } } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1041,7 +1084,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { // Server must be an exact match, but user and database only needs to match exactly if there is more than one // for the given user or database passed. That is ambiguious and we must fail. - var scopeID = _log.NotificationsScopeEnter($" server: '{server}', failoverServer: '{failoverServer}', database: '{database}'"); + var scopeID = Log.NotificationsScopeEnter($" server: '{server}', failoverServer: '{failoverServer}', database: '{database}'"); try { string result; @@ -1051,18 +1094,22 @@ internal static string GetDefaultComposedOptions(string server, string failoverS if (!_serverUserHash.ContainsKey(server)) { if (0 == _serverUserHash.Count) - { // Special error for no calls to start. - _log.NotificationsTrace(" ERROR - no start calls have been made, about to throw.\n"); + { + // Special error for no calls to start. + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - no start calls have been made, about to throw."); + throw SQL.SqlDepDefaultOptionsButNoStart(); } else if (!ADP.IsEmpty(failoverServer) && _serverUserHash.ContainsKey(failoverServer)) { - _log.NotificationsTrace(" using failover server instead\n"); + Log.NotificationsTrace(" using failover server instead\n"); server = failoverServer; } else { - _log.NotificationsTrace(" ERROR - not listening to this server, about to throw.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - not listening to this server, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } } @@ -1075,7 +1122,9 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { if (identityDatabaseHash.Count > 1) { - _log.NotificationsTrace(" ERROR - not listening for this user, but listening to more than one other user, about to throw.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - not listening for this user, " + + "but listening to more than one other user, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } else @@ -1120,20 +1169,25 @@ internal static string GetDefaultComposedOptions(string server, string failoverS result = "Service=" + quotedService + ";Local Database=" + quotedDatabase; } else - { // More than one database for given server, ambiguous - fail the default case! - _log.NotificationsTrace(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database.\n"); + { + // More than one database for given server, ambiguous - fail the default case! + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); + throw SQL.SqlDependencyNoMatchingServerDatabaseStart(); } } } Debug.Assert(!ADP.IsEmpty(result), "GetDefaultComposedOptions should never return null or empty string!"); - _log.NotificationsTrace($" resulting options: '{result}'.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" resulting options: '{result}'."); + return result; } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1145,7 +1199,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS // use this list for a reverse lookup based on server. internal void AddToServerList(string server) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); try { lock (_serverList) @@ -1153,7 +1207,9 @@ internal void AddToServerList(string server) int index = _serverList.BinarySearch(server, StringComparer.OrdinalIgnoreCase); if (0 > index) { // If less than 0, item was not found in list. - _log.NotificationsTrace($" Server not present in hashtable, adding server: '{server}'.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Server not present in hashtable, adding server: '{server}'."); + index = ~index; // BinarySearch returns the 2's compliment of where the item should be inserted to preserver a sorted list after insertion. _serverList.Insert(index, server); @@ -1162,7 +1218,7 @@ internal void AddToServerList(string server) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1176,7 +1232,7 @@ internal bool ContainsServer(string server) internal string ComputeHashAndAddToDispatcher(SqlCommand command) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); try { // Create a string representing the concatenation of the connection string, command text and .ToString on all parameter values. @@ -1191,18 +1247,19 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) string commandHash = ComputeCommandHash(command.Connection.ConnectionString, command); // calculate the string representation of command string idString = SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddCommandEntry(commandHash, this); // Add to map. - _log.NotificationsTrace($" computed id string: '{idString}'.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" computed id string: '{idString}'."); return idString; } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { List eventList = null; @@ -1220,12 +1277,15 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql // raises Timeout event but before removing this event from the list. If notification is received from // server in this case, we will hit this code path. // It is safe to ignore this race condition because no event is sent to user and no leak happens. - _log.NotificationsTrace(" ignore notification received after timeout!"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ignore notification received after timeout!"); } else { Debug.Assert(false, "Received notification twice - we should never enter this state!"); - _log.NotificationsTrace(" ERROR - notification received twice - we should never enter this state!"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - notification received twice - we should never enter this state!"); } } else @@ -1239,7 +1299,9 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (eventList != null) { - _log.NotificationsTrace(" Firing events.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" Firing events."); + foreach (EventContextPair pair in eventList) { pair.Invoke(new SqlNotificationEventArgs(type, info, source)); @@ -1248,19 +1310,20 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } // This method is used by SqlCommand. internal void StartTimer(SqlNotificationRequest notificationRequest) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { if (_expirationTime == DateTime.MaxValue) { - _log.NotificationsTrace(" We've timed out, executing logic.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" We've timed out, executing logic."); int seconds = SQL.SqlDependencyServerTimeout; if (0 != _timeout) @@ -1279,7 +1342,7 @@ internal void StartTimer(SqlNotificationRequest notificationRequest) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1292,7 +1355,7 @@ private void AddCommandInternal(SqlCommand cmd) if (cmd != null) { // Don't bother with BID if command null. - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {cmd.ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {cmd.ObjectID}#"); try { SqlConnection connection = cmd.Connection; @@ -1302,7 +1365,9 @@ private void AddCommandInternal(SqlCommand cmd) // Fail if cmd has notification that is not already associated with this dependency. if (cmd._sqlDep == null || cmd._sqlDep != this) { - _log.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception."); + throw SQL.SqlCommandHasExistingSqlNotificationRequest(); } } @@ -1332,8 +1397,10 @@ private void AddCommandInternal(SqlCommand cmd) // an event to fire in the event list once we've fired. Debug.Assert(0 == _eventList.Count, "How can we have an event at this point?"); if (0 == _eventList.Count) - { // Keep logic just in case. - _log.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point.\n"); + { + // Keep logic just in case. + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point."); needToInvalidate = true; // Delay invalidation until outside of lock. } } @@ -1347,14 +1414,14 @@ private void AddCommandInternal(SqlCommand cmd) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } } private string ComputeCommandHash(string connectionString, SqlCommand command) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); try { // Create a string representing the concatenation of the connection string, the command text and .ToString on all its parameter values. @@ -1412,12 +1479,14 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) string result = builder.ToString(); - _log.NotificationsTrace($" ComputeCommandHash result: '{result}'.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" ComputeCommandHash result: '{result}'."); + return result; } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index ac126a5303..066341dc85 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -80,7 +80,7 @@ internal int ObjectID internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, queue: '{hashHelper.Queue}'"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, queue: '{hashHelper.Queue}'"); bool setupCompleted = false; @@ -104,7 +104,9 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(_hashHelper.ConnectionStringBuilder.ConnectionString); - _log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); #endif // Always use ConnectionStringBuilder since in default case it is different from the @@ -219,7 +221,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -279,7 +281,7 @@ internal string Server // SqlDependencyProcessDispatcher.QueueAppDomainUnload on AppDomain.Unload. internal bool AppDomainUnload(string appDomainKey) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, AppDomainKey: '{ appDomainKey}'"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, AppDomainKey: '{ appDomainKey}'"); try { Debug.Assert(!ADP.IsEmpty(appDomainKey), "Unexpected empty appDomainKey!"); @@ -289,10 +291,16 @@ internal bool AppDomainUnload(string appDomainKey) lock (_appDomainKeyHash) { if (_appDomainKeyHash.ContainsKey(appDomainKey)) - { // Do nothing if AppDomain did not call Start! - _log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}'."); + { + // Do nothing if AppDomain did not call Start! + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}'."); + int value = _appDomainKeyHash[appDomainKey]; - _log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{appDomainKey}' count: '{value}'."); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{appDomainKey}' count: '{value}'."); + Debug.Assert(value > 0, "Why is value 0 or less?"); bool ignored = false; @@ -309,27 +317,31 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { - _log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{appDomainKey}' entry not removed from hash. Count: {_appDomainKeyHash[appDomainKey]}'"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{appDomainKey}' entry not removed from hash. Count: {_appDomainKeyHash[appDomainKey]}'"); } } else { - _log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}'."); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}'."); } } - _log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{_stopped}'."); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{_stopped}'."); + return _stopped; } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } private void AsynchronouslyQueryServiceBrokerQueue() { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { AsyncCallback callback = new AsyncCallback(AsyncResultCallback); @@ -337,13 +349,13 @@ private void AsynchronouslyQueryServiceBrokerQueue() } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } private void AsyncResultCallback(IAsyncResult asyncResult) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { using (SqlDataReader reader = _com.EndExecuteReader(asyncResult)) @@ -370,7 +382,9 @@ private void AsyncResultCallback(IAsyncResult asyncResult) throw; } - _log.NotificationsTrace($" Exception occurred."); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Exception occurred."); + if (!_stop) { // Only assert if not in cancel path. ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. @@ -389,13 +403,13 @@ private void AsyncResultCallback(IAsyncResult asyncResult) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } private void CreateQueueAndService(bool restart) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { SqlCommand com = new SqlCommand(); @@ -525,18 +539,20 @@ private void CreateQueueAndService(bool restart) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { appDomainStart = false; // Reset out param. int result = Interlocked.Increment(ref _startCount); // Add to refCount. - _log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> {_staticInstance.ObjectID}#, incremented _startCount: {result}"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> {_staticInstance.ObjectID}#, incremented _startCount: {result}"); // Dictionary used to track how many times start has been called per app domain. // For each increment, add to count, and create entry if not present. @@ -545,25 +561,29 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { _appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1; - _log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', incremented count: '{_appDomainKeyHash[appDomainKey]}'."); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', incremented count: '{_appDomainKeyHash[appDomainKey]}'."); } else { _appDomainKeyHash[appDomainKey] = 1; appDomainStart = true; - _log.NotificationsTrace($" _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}', added to hashtable and value set to 1."); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}', added to hashtable and value set to 1."); } } } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } private void ProcessNotificationResults(SqlDataReader reader) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { Guid handle = Guid.Empty; // Conversation_handle. Always close this! @@ -573,15 +593,21 @@ private void ProcessNotificationResults(SqlDataReader reader) { while (reader.Read()) { - _log.NotificationsTrace($" Row read."); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Row read."); #if DEBUG for (int i = 0; i < reader.FieldCount; i++) { - _log.NotificationsTrace($" column: {reader.GetName(i)}, value: {reader.GetValue(i).ToString()}"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" column: {reader.GetName(i)}, value: {reader.GetValue(i).ToString()}"); } #endif string msgType = reader.GetString(0); - _log.NotificationsTrace($" msgType: '{ msgType}'"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" msgType: '{ msgType}'"); + handle = reader.GetGuid(1); // SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.ProcessNotificationResults(SqlDataReader)|DEP> conversationHandle: '%p(GUID)'", conversationHandle); @@ -595,7 +621,10 @@ private void ProcessNotificationResults(SqlDataReader reader) if (null != notification) { string key = notification.Key; - _log.NotificationsTrace($" Key: '{key}'"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Key: '{key}'"); + int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash" if (index >= 0) @@ -624,25 +653,33 @@ private void ProcessNotificationResults(SqlDataReader reader) else { Debug.Assert(false, "Received notification but do not have an associated PerAppDomainDispatcher!"); - _log.NotificationsTrace($" Received notification but do not have an associated PerAppDomainDispatcher!"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Received notification but do not have an associated PerAppDomainDispatcher!"); } } else { Debug.Assert(false, "Unexpected ID format received!"); - _log.NotificationsTrace($" Unexpected ID format received!"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Unexpected ID format received!"); } } else { Debug.Assert(false, "Null notification returned from ProcessMessage!"); - _log.NotificationsTrace($" Null notification returned from ProcessMessage!"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Null notification returned from ProcessMessage!"); } } else { Debug.Assert(false, "Null payload for QN notification type!"); - _log.NotificationsTrace($" Null payload for QN notification type!"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Null payload for QN notification type!"); } } else @@ -650,7 +687,9 @@ private void ProcessNotificationResults(SqlDataReader reader) handle = Guid.Empty; // VSDD 546707: this assert was hit by SQL Notification fuzzing tests, disable it to let these tests run on Debug bits // Debug.Assert(false, "Unexpected message format received!"); - _log.NotificationsTrace($" Unexpected message format received!"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Unexpected message format received!"); } } } @@ -682,7 +721,7 @@ private void ProcessNotificationResults(SqlDataReader reader) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -693,7 +732,7 @@ private void ProcessNotificationResults(SqlDataReader reader) private void Restart(object unused) { // Unused arg required by TimerCallback. - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { try @@ -855,13 +894,13 @@ private void Restart(object unused) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } internal bool Stop(string appDomainKey, out bool appDomainStop) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { appDomainStop = false; @@ -882,14 +921,18 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) Debug.Assert(value > 0, "Unexpected count for appDomainKey"); - _log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', pre-decrement Count: '{value}'."); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', pre-decrement Count: '{value}'."); + if (value > 0) { _appDomainKeyHash[appDomainKey] = value - 1; } else { - _log.NotificationsTrace($" ERROR pre-decremented count <= 0!"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" ERROR pre-decremented count <= 0!"); + Debug.Assert(false, "Unexpected AppDomainKey count in Stop()"); } @@ -901,7 +944,9 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - _log.NotificationsTrace($" ERROR appDomainKey not null and not found in hash!"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" ERROR appDomainKey not null and not found in hash!"); + Debug.Assert(false, "Unexpected state on Stop() - no AppDomainKey entry in hashtable!"); } } @@ -912,8 +957,11 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) if (0 == result) { // If we've reached refCount 0, destroy. - // Lock to ensure Cancel() complete prior to other thread calling TearDown. - _log.NotificationsTrace($" Reached 0 count, cancelling and waiting."); + // Lock to ensure Cancel() complete prior to other thread calling TearDown. + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Reached 0 count, cancelling and waiting."); + lock (this) { try @@ -956,7 +1004,8 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) // TearDownAndDispose in the maximum retry period case as well as in the _errorState case. if (_errorState || retryStopwatch.Elapsed.Seconds >= 30) { - _log.NotificationsTrace($" forcing cleanup. elapsedSeconds: '{retryStopwatch.Elapsed.Seconds}', _errorState: '{_errorState}'."); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" forcing cleanup. elapsedSeconds: '{retryStopwatch.Elapsed.Seconds}', _errorState: '{_errorState}'."); Timer retryTimer = _retryTimer; _retryTimer = null; @@ -976,7 +1025,8 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - _log.NotificationsTrace($" _startCount not 0 after decrement. _startCount: '{_startCount}'."); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" _startCount not 0 after decrement. _startCount: '{_startCount}'."); } Debug.Assert(0 <= _startCount, "Invalid start count state"); @@ -985,13 +1035,13 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } private void SynchronouslyQueryServiceBrokerQueue() { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { using (SqlDataReader reader = _com.ExecuteReader()) @@ -1001,14 +1051,14 @@ private void SynchronouslyQueryServiceBrokerQueue() } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } [SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")] private void TearDownAndDispose() { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { lock (this) @@ -1081,7 +1131,7 @@ private void TearDownAndDispose() } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } } @@ -1226,9 +1276,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) { ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace. - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Exception thrown - Enum.Parse failed to parse the value '{xmlReader.Value}' of the attribute '{xmlReader.LocalName}'."); + Log.Trace($" Exception thrown - Enum.Parse failed to parse the value '{xmlReader.Value}' of the attribute '{xmlReader.LocalName}'."); } return null; } @@ -1236,9 +1286,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) if (MessageAttributes.All != messageAttributes) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Not all expected attributes in Message; messageAttributes = '{(int)messageAttributes}'."); + Log.Trace($" Not all expected attributes in Message; messageAttributes = '{(int)messageAttributes}'."); } return null; } @@ -1246,9 +1296,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the "Message" node. if (!xmlReader.Read()) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1256,9 +1306,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Verify state after Read(). if ((XmlNodeType.Element != xmlReader.NodeType) || (0 != string.Compare(xmlReader.LocalName, MessageNode, StringComparison.OrdinalIgnoreCase))) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1266,9 +1316,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the Text Node. if (!xmlReader.Read()) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1276,9 +1326,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Verify state after Read(). if (xmlReader.NodeType != XmlNodeType.Text) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1289,9 +1339,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the Text Node. if (!xmlMessageReader.Read()) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1303,9 +1353,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1315,9 +1365,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; // failure } @@ -1498,19 +1548,20 @@ internal int ObjectID private SqlDependencyProcessDispatcher(object dummyVariable) { Debug.Assert(null == _staticInstance, "Real constructor called with static instance already created!"); - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { #if DEBUG // Possibly expensive, limit to debug. - _log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); #endif _connectionContainers = new Dictionary(); _sqlDependencyPerAppDomainDispatchers = new Dictionary(); } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1518,18 +1569,19 @@ private SqlDependencyProcessDispatcher(object dummyVariable) // Required to be public, even on internal class, for Remoting infrastructure. public SqlDependencyProcessDispatcher() { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { // Empty constructor and object - dummy to obtain singleton. #if DEBUG // Possibly expensive, limit to debug. - _log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); #endif } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1555,7 +1607,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS out string user, string queue) { - var scopeID = _log.NotificationsScopeEnter($" {_staticInstance.ObjectID}#, queue: {queue}"); + var scopeID = Log.NotificationsScopeEnter($" {_staticInstance.ObjectID}#, queue: {queue}"); try { // Force certain connection string properties to be used by SqlDependencyProcessDispatcher. @@ -1588,7 +1640,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1600,7 +1652,7 @@ public override object InitializeLifetimeService() private void Invalidate(string server, SqlNotification sqlNotification) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, server: {server}"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, server: {server}"); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1632,7 +1684,7 @@ private void Invalidate(string server, SqlNotification sqlNotification) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1649,7 +1701,7 @@ internal void QueueAppDomainUnloading(string appDomainKey) // This method is only called by queued work-items from the method above. private void AppDomainUnloading(object state) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { string appDomainKey = (string)state; @@ -1681,7 +1733,7 @@ private void AppDomainUnloading(object state) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1748,7 +1800,7 @@ private bool Start(string connectionString, out bool appDomainStart, bool useDefaults) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, queue: '{ queueService}', appDomainKey: '{appDomainKey}', perAppDomainDispatcher ID: '{dispatcher.ObjectID}'"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, queue: '{ queueService}', appDomainKey: '{appDomainKey}', perAppDomainDispatcher ID: '{dispatcher.ObjectID}'"); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1775,7 +1827,9 @@ private bool Start(string connectionString, queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - _log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); #endif bool started = false; @@ -1785,7 +1839,9 @@ private bool Start(string connectionString, { if (!_connectionContainers.ContainsKey(hashHelper)) { - _log.NotificationsTrace($" {ObjectID}#, hashtable miss, creating new container."); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" {ObjectID}#, hashtable miss, creating new container."); + container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults); _connectionContainers.Add(hashHelper, container); started = true; @@ -1794,10 +1850,12 @@ private bool Start(string connectionString, else { container = _connectionContainers[hashHelper]; - _log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}"); + Log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}"); if (container.InErrorState) { - _log.NotificationsTrace($" {ObjectID}#, container: {container.ObjectID} is in error state!"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" {ObjectID}#, container: {container.ObjectID} is in error state!"); + errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start(). } else @@ -1812,16 +1870,19 @@ private bool Start(string connectionString, server = container.Server; database = container.Database; queueService = container.Queue; - _log.NotificationsTrace($" {ObjectID}#, default service: '{queueService}', server: '{server}', database: '{database}'"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" {ObjectID}#, default service: '{queueService}', server: '{server}', database: '{database}'"); } - _log.NotificationsTrace($" {ObjectID}#, started: {started}"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" {ObjectID}#, started: {started}"); return started; } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -1838,7 +1899,7 @@ internal bool Stop(string connectionString, string appDomainKey, out bool appDomainStop) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, queue: '{queueService}'"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, queue: '{queueService}'"); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1856,7 +1917,9 @@ internal bool Stop(string connectionString, queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - _log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); #endif bool stopped = false; @@ -1866,7 +1929,10 @@ internal bool Stop(string connectionString, if (_connectionContainers.ContainsKey(hashHelper)) { SqlConnectionContainer container = _connectionContainers[hashHelper]; - _log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}"); + + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}"); + server = container.Server; // Return server, database, and queue info for use by calling SqlDependency. database = container.Database; queueService = container.Queue; @@ -1878,16 +1944,19 @@ internal bool Stop(string connectionString, } else { - _log.NotificationsTrace($" {ObjectID}#, hashtable miss."); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" {ObjectID}#, hashtable miss."); } } - _log.NotificationsTrace($" %d#, stopped: {stopped}"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" %d#, stopped: {stopped}"); + return stopped; } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs index 1f99347239..58e87b7b75 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs @@ -93,7 +93,7 @@ internal int ObjectID private SqlDependencyPerAppDomainDispatcher() { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { _dependencyIdToDependencyHash = new Dictionary(); @@ -107,7 +107,7 @@ private SqlDependencyPerAppDomainDispatcher() } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -125,7 +125,7 @@ public override object InitializeLifetimeService() private void UnloadEventHandler(object sender, EventArgs e) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); try { // Make non-blocking call to ProcessDispatcher to ThreadPool.QueueUserWorkItem to complete @@ -140,7 +140,7 @@ private void UnloadEventHandler(object sender, EventArgs e) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -151,7 +151,7 @@ private void UnloadEventHandler(object sender, EventArgs e) // This method is called upon SqlDependency constructor. internal void AddDependencyEntry(SqlDependency dep) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); try { lock (this) @@ -161,7 +161,7 @@ internal void AddDependencyEntry(SqlDependency dep) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -170,14 +170,16 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) { string notificationId = string.Empty; - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{commandHash}', SqlDependency: {dep.ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{commandHash}', SqlDependency: {dep.ObjectID}#"); try { lock (this) { if (!_dependencyIdToDependencyHash.ContainsKey(dep.Id)) - { // Determine if depId->dep hashtable contains dependency. If not, it's been invalidated. - _log.NotificationsTrace($" Dependency not present in depId->dep hash, must have been invalidated.\n"); + { + // Determine if depId->dep hashtable contains dependency. If not, it's been invalidated. + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Dependency not present in depId->dep hash, must have been invalidated."); } else { @@ -198,12 +200,15 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // join the new dependency to the list if (!dependencyList.Contains(dep)) { - _log.NotificationsTrace($" Dependency not present for commandHash, adding.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Dependency not present for commandHash, adding."); + dependencyList.Add(dep); } else { - _log.NotificationsTrace($" Dependency already present for commandHash.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Dependency already present for commandHash."); } } else @@ -218,7 +223,9 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) Guid.NewGuid().ToString("D", System.Globalization.CultureInfo.InvariantCulture) ); - _log.NotificationsTrace($" Creating new Dependencies list for commandHash.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Creating new Dependencies list for commandHash."); + DependencyList dependencyList = new DependencyList(commandHash); dependencyList.Add(dep); @@ -240,7 +247,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } return notificationId; @@ -249,7 +256,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // This method is called by the ProcessDispatcher upon a notification for this AppDomain. internal void InvalidateCommandID(SqlNotification sqlNotification) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{sqlNotification.Key}'"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{sqlNotification.Key}'"); try { List dependencyList = null; @@ -260,7 +267,8 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) if (null != dependencyList) { - _log.NotificationsTrace($" commandHash found in hashtable.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" commandHash found in hashtable."); foreach (SqlDependency dependency in dependencyList) { @@ -273,7 +281,8 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } else { - _log.NotificationsTrace($" commandHash NOT found in hashtable.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" commandHash NOT found in hashtable."); } } @@ -282,7 +291,8 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) // After removal from hashtables, invalidate. foreach (SqlDependency dependency in dependencyList) { - _log.NotificationsTrace($" Dependency found in commandHash dependency ArrayList - calling invalidate.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Dependency found in commandHash dependency ArrayList - calling invalidate."); try { @@ -304,14 +314,14 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } // This method is called when a connection goes down or other unknown error occurs in the ProcessDispatcher. internal void InvalidateServer(string server, SqlNotification sqlNotification) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); try { List dependencies = new List(); @@ -358,14 +368,14 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } // This method is called by SqlCommand to enable ASP.NET scenarios - map from ID to Dependency. internal SqlDependency LookupDependencyEntry(string id) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, Key: '{id}'"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, Key: '{id}'"); try { if (null == id) @@ -387,7 +397,8 @@ internal SqlDependency LookupDependencyEntry(string id) } else { - _log.NotificationsTrace($" ERROR - dependency ID mismatch - not throwing.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" ERROR - dependency ID mismatch - not throwing."); } } @@ -395,21 +406,23 @@ internal SqlDependency LookupDependencyEntry(string id) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } // Remove the dependency from the hashtable with the passed id. private void LookupDependencyEntryWithRemove(string id) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, id: '{id}'"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, id: '{id}'"); try { lock (this) { if (_dependencyIdToDependencyHash.ContainsKey(id)) { - _log.NotificationsTrace($" Entry found in hashtable - removing.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Entry found in hashtable - removing."); + _dependencyIdToDependencyHash.Remove(id); // if there are no more dependencies then we can dispose the timer. @@ -421,20 +434,21 @@ private void LookupDependencyEntryWithRemove(string id) } else { - _log.NotificationsTrace($" Entry NOT found in hashtable.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Entry NOT found in hashtable."); } } } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } // Find and return arraylist, and remove passed hash value. private List LookupCommandEntryWithRemove(string notificationId) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{notificationId}'"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{notificationId}'"); try { DependencyList entry = null; @@ -443,7 +457,8 @@ private List LookupCommandEntryWithRemove(string notificationId) { if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry)) { - _log.NotificationsTrace($" Entries found in hashtable - removing.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Entries found in hashtable - removing."); // update the tables - do it inside finally block to avoid ThreadAbort exception interrupt this operation try @@ -457,7 +472,8 @@ private List LookupCommandEntryWithRemove(string notificationId) } else { - _log.NotificationsTrace($" Entries NOT found in hashtable.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Entries NOT found in hashtable."); } Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!"); @@ -467,14 +483,14 @@ private List LookupCommandEntryWithRemove(string notificationId) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } // Remove from commandToDependenciesHash all references to the passed dependency. private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency dependency) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dependency.ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dependency.ObjectID}#"); try { lock (this) @@ -487,7 +503,9 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende DependencyList dependencies = entry.Value; if (dependencies.Remove(dependency)) { - _log.NotificationsTrace($" Removed SqlDependency: {dependency.ObjectID}#, with ID: '{dependency.Id}'.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Removed SqlDependency: {dependency.ObjectID}#, with ID: '{dependency.Id}'."); + if (dependencies.Count == 0) { // this dependency was the last associated with this notification ID, remove the entry @@ -520,7 +538,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -530,7 +548,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende internal void StartTimer(SqlDependency dep) { - var scopeID = _log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); + var scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); try { // If this dependency expires sooner than the current next timeout, change @@ -541,7 +559,8 @@ internal void StartTimer(SqlDependency dep) // Enable the timer if needed (disable when empty, enable on the first addition). if (!_SqlDependencyTimeOutTimerStarted) { - _log.NotificationsTrace($" Timer not yet started, starting.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Timer not yet started, starting."); _timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */); @@ -551,7 +570,8 @@ internal void StartTimer(SqlDependency dep) } else if (_nextTimeout > dep.ExpirationTime) { - _log.NotificationsTrace($" Timer already started, resetting time.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" Timer already started, resetting time."); // Save this as the earlier timeout to come. _nextTimeout = dep.ExpirationTime; @@ -560,13 +580,13 @@ internal void StartTimer(SqlDependency dep) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } private static void TimeoutTimerCallback(object state) { - var scopeID = _log.NotificationsScopeEnter($" AppDomainKey: '{SqlDependency.AppDomainKey}'"); + var scopeID = Log.NotificationsScopeEnter($" AppDomainKey: '{SqlDependency.AppDomainKey}'"); try { SqlDependency[] dependencies; @@ -579,12 +599,15 @@ private static void TimeoutTimerCallback(object state) if (0 == SingletonInstance._dependencyIdToDependencyHash.Count) { // Nothing to check. - _log.NotificationsTrace($" No dependencies, exiting.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" No dependencies, exiting."); return; } if (SingletonInstance._nextTimeout > DateTime.UtcNow) { - _log.NotificationsTrace($" No timeouts expired, exiting.\n"); + if (Log.IsNotificationTraceEnabled()) + Log.NotificationsTrace($" No timeouts expired, exiting."); + // No dependency timed-out yet. return; } @@ -654,7 +677,7 @@ private static void TimeoutTimerCallback(object state) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs index a2142e14a6..de8c84486d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs @@ -42,9 +42,9 @@ internal SqlError(int infoNumber, byte errorState, byte errorClass, string serve this.lineNumber = lineNumber; if (errorClass != 0) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" infoNumber={infoNumber}, errorState={(int)errorState}, errorClass={(int)errorClass}, errorMessage='{errorMessage}', procedure='{procedure ?? "None"}', lineNumber={(int)lineNumber}"); + Log.Trace($" infoNumber={infoNumber}, errorState={(int)errorState}, errorClass={(int)errorClass}, errorMessage='{errorMessage}', procedure='{procedure ?? "None"}', lineNumber={(int)lineNumber}"); } } this.win32ErrorCode = 0; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index 6883f75610..24b7f3ecd7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -315,7 +315,9 @@ override protected DbReferenceCollection CreateReferenceCollection() override protected void Deactivate() { - _log.Trace($" {ObjectID}# deactivating\n"); + if (Log.IsTraceEnabled()) + Log.Trace($" {ObjectID}# deactivating"); + TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -438,13 +440,15 @@ private void EnlistNonNull(SysTx.Transaction tx) { Debug.Assert(null != tx, "null transaction?"); - _log.Trace($" {ObjectID}#, transaction {tx.GetHashCode()}#.\n"); + if (Log.IsTraceEnabled()) + Log.Trace($" {ObjectID}#, transaction {tx.GetHashCode()}#."); bool hasDelegatedTransaction = false; if (IsYukonOrNewer) { - _log.Trace($" {ObjectID}#, attempting to delegate\n"); + if (Log.IsTraceEnabled()) + Log.Trace($" {ObjectID}#, attempting to delegate"); // Promotable transactions are only supported on Yukon // servers or newer. @@ -520,7 +524,9 @@ private void EnlistNonNull(SysTx.Transaction tx) transactionId = CurrentTransaction.TransactionId; transactionObjectID = CurrentTransaction.ObjectID; } - _log.Trace($" {ObjectID}#, delegated to transaction {transactionObjectID}# with transactionId=0x{transactionId}\n"); + + if (Log.IsTraceEnabled()) + Log.Trace($" {ObjectID}#, delegated to transaction {transactionObjectID}# with transactionId=0x{transactionId}"); } } catch (SqlException e) @@ -553,7 +559,8 @@ private void EnlistNonNull(SysTx.Transaction tx) if (!hasDelegatedTransaction) { - _log.Trace($" {ObjectID}#, delegation not possible, enlisting.\n"); + if (Log.IsTraceEnabled()) + Log.Trace($" {ObjectID}#, delegation not possible, enlisting."); byte[] cookie = null; @@ -593,7 +600,9 @@ private void EnlistNonNull(SysTx.Transaction tx) transactionId = CurrentTransaction.TransactionId; transactionObjectID = CurrentTransaction.ObjectID; } - _log.Trace($" {ObjectID}#, enlisted with transaction {transactionObjectID}# with transactionId=0x{transactionId}\n"); + + if (Log.IsTraceEnabled()) + Log.Trace($" {ObjectID}#, enlisted with transaction {transactionObjectID}# with transactionId=0x{transactionId}"); } EnlistedTransaction = tx; // Tell the base class about our enlistment @@ -617,7 +626,8 @@ private void EnlistNonNull(SysTx.Transaction tx) internal void EnlistNull() { - _log.Trace($" {ObjectID}#, unenlisting.\n"); + if (Log.IsTraceEnabled()) + Log.Trace($" {ObjectID}#, unenlisting."); // We were in a transaction, but now we are not - so send // message to server with empty transaction - confirmed proper @@ -636,7 +646,8 @@ internal void EnlistNull() _isEnlistedInTransaction = false; EnlistedTransaction = null; // Tell the base class about our enlistment - _log.Trace($" {ObjectID}#, unenlisted.\n"); + if (Log.IsTraceEnabled()) + Log.Trace($" {ObjectID}#, unenlisted."); // The EnlistTransaction above will return an TransactionEnded event, // which causes the TdsParser or SmiEventSink should to clear the diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs index 2960ac038a..9c59f4a2cf 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs @@ -67,54 +67,54 @@ internal EventSink(SqlInternalConnectionSmi connection) internal override void DefaultDatabaseChanged(string databaseName) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {_connection.ObjectID}#, databaseName='{databaseName}'."); + Log.Trace($" {_connection.ObjectID}#, databaseName='{databaseName}'."); } _connection.CurrentDatabase = databaseName; } internal override void TransactionCommitted(long transactionId) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); + Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); } _connection.TransactionEnded(transactionId, TransactionState.Committed); } internal override void TransactionDefected(long transactionId) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); + Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); } _connection.TransactionEnded(transactionId, TransactionState.Unknown); } internal override void TransactionEnlisted(long transactionId) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); + Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); } _connection.TransactionStarted(transactionId, true); // distributed; } internal override void TransactionEnded(long transactionId) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); + Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); } _connection.TransactionEndedByServer(transactionId, TransactionState.Unknown); } internal override void TransactionRolledBack(long transactionId) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); + Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); } // Dev11 1066: ensure delegated transaction is rolled back @@ -123,9 +123,9 @@ internal override void TransactionRolledBack(long transactionId) internal override void TransactionStarted(long transactionId) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); + Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); } _connection.TransactionStarted(transactionId, false); // not distributed; } @@ -143,9 +143,9 @@ internal SqlInternalConnectionSmi(SqlConnectionString connectionOptions, SmiCont _smiEventSink = new EventSink(this); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, constructed new SMI internal connection"); + Log.Trace($" {ObjectID}#, constructed new SMI internal connection"); } } @@ -296,12 +296,10 @@ internal void AutomaticEnlistment() SysTx.Transaction currentSystemTransaction = ADP.GetCurrentTransaction(); // NOTE: Must be first to ensure _smiContext.ContextTransaction is set! SysTx.Transaction contextTransaction = _smiContext.ContextTransaction; // returns the transaction that was handed to SysTx that wraps the ContextTransactionId. long contextTransactionId = _smiContext.ContextTransactionId; - var contextTransactionValue = (null != contextTransaction) ? contextTransaction.GetHashCode() : 0; - var currentSystemTransactionValue = (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, contextTransactionId=0x{contextTransactionId}, contextTransaction={contextTransactionValue}#, currentSystemTransaction={currentSystemTransactionValue}#."); + Log.Trace($" {ObjectID}#, contextTransactionId=0x{contextTransactionId}, contextTransaction={((null != contextTransaction) ? contextTransaction.GetHashCode() : 0)}#, currentSystemTransaction={((null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0)}#."); } if (SqlInternalTransaction.NullTransactionId != contextTransactionId) @@ -311,9 +309,9 @@ internal void AutomaticEnlistment() throw SQL.NestedTransactionScopesNotSupported(); // can't use TransactionScope(RequiresNew) inside a Sql Transaction. } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, using context transaction with transactionId=0x{contextTransactionId}"); + Log.Trace($" {ObjectID}#, using context transaction with transactionId=0x{contextTransactionId}"); } _currentTransaction = new SqlInternalTransaction(this, TransactionType.Context, null, contextTransactionId); ContextTransaction = contextTransaction; @@ -322,16 +320,16 @@ internal void AutomaticEnlistment() { _currentTransaction = null; // there really isn't a transaction. - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, no transaction."); + Log.Trace($" {ObjectID}#, no transaction."); } } else { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, using current System.Transaction."); + Log.Trace($" {ObjectID}#, using current System.Transaction."); } base.Enlist(currentSystemTransaction); } @@ -345,9 +343,9 @@ override protected void ChangeDatabaseInternal(string database) override protected void InternalDeactivate() { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Deactivating."); + Log.Trace($" {ObjectID}#, Deactivating."); } // When we put this to bed, we should not hold on to the transaction @@ -378,9 +376,9 @@ override internal void DelegatedTransactionEnded() { base.DelegatedTransactionEnded(); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, cleaning up after Delegated Transaction Completion"); + Log.Trace($" {ObjectID}#, cleaning up after Delegated Transaction Completion"); } _currentTransaction = null; // clean up our current transaction too @@ -388,9 +386,9 @@ override internal void DelegatedTransactionEnded() override internal void DisconnectTransaction(SqlInternalTransaction internalTransaction) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Disconnecting Transaction {internalTransaction.ObjectID}#."); + Log.Trace($" {ObjectID}#, Disconnecting Transaction {internalTransaction.ObjectID}#."); } // VSTS 215465/15029: allow _currentTransaction to be null - it can be cleared before by server's callback @@ -416,12 +414,11 @@ override internal void ExecuteTransaction( bool isDelegateControlRequest) { var transactionNameValue = (null != transactionName) ? transactionName : "null"; - var internalTransactionValue = (null != internalTransaction) ? internalTransaction.ObjectID : 0; - var internalTransactionIdValue = (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, transactionRequest={transactionRequest.ToString()}, transactionName='{transactionNameValue}', isolationLevel={iso.ToString()}, internalTransaction=#{internalTransactionIdValue} transactionId=0x{internalTransactionIdValue}."); + Log.Trace($" {ObjectID}#, transactionRequest={transactionRequest.ToString()}, " + + $"transactionName='{transactionNameValue}', isolationLevel={iso.ToString()}, internalTransaction=#{((null != internalTransaction) ? internalTransaction.ObjectID : 0)} transactionId=0x{((null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId)}."); } switch (transactionRequest) @@ -477,15 +474,15 @@ override protected byte[] GetDTCAddress() _smiEventSink.ProcessMessagesAndThrow(); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { if (null != whereAbouts) { - _log.TraceBin($" whereAbouts", whereAbouts, (ushort)whereAbouts.Length); + Log.TraceBin($" whereAbouts", whereAbouts, (ushort)whereAbouts.Length); } else { - _log.Trace($" whereAbouts=null"); + Log.Trace($" whereAbouts=null"); } } return whereAbouts; @@ -511,9 +508,9 @@ private void OnOutOfScope(object s, EventArgs e) // Called whenever the context goes out of scope, we need to make // sure that we close the connection, or the next person that uses // the context may appear to have the connection in use. - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# context is out of scope"); + Log.Trace($" {ObjectID}# context is out of scope"); } // TODO: This is suspect to me -- if I go out of scope, who will commit the transaction? @@ -542,15 +539,15 @@ private void OnOutOfScope(object s, EventArgs e) override protected void PropagateTransactionCookie(byte[] transactionCookie) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { if (null != transactionCookie) { - _log.TraceBin($" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); + Log.TraceBin($" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); } else { - _log.Trace($" null"); + Log.Trace($" null"); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs index f83dc4d71e..781f3951f6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs @@ -516,9 +516,9 @@ internal SqlInternalConnectionTds( ThreadHasParserLockForClose = false; _parserLock.Release(); } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, constructed new TDS internal connection"); + Log.Trace($" {ObjectID}#, constructed new TDS internal connection"); } } @@ -774,9 +774,9 @@ override protected void ChangeDatabaseInternal(string database) override public void Dispose() { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# disposing"); + Log.Trace($" {ObjectID}# disposing"); } try @@ -1369,18 +1369,18 @@ private void CompleteLogin(bool enlistOK) { // ROR should not affect state of connection recovery if (_federatedAuthenticationRequested && !_federatedAuthenticationAcknowledged) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Server did not acknowledge the federated authentication request"); + Log.Trace($" {ObjectID}#, Server did not acknowledge the federated authentication request"); } throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged); } if (_federatedAuthenticationInfoRequested && !_federatedAuthenticationInfoReceived) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Server never sent the requested federated authentication info"); + Log.Trace($" {ObjectID}#, Server never sent the requested federated authentication info"); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoNotReceived); } @@ -1420,9 +1420,9 @@ private void CompleteLogin(bool enlistOK) _fConnectionOpen = true; // mark connection as open - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Post-Login Phase: Server connection obtained."); + Log.Trace($" Post-Login Phase: Server connection obtained."); } // for non-pooled connections, enlist in a distributed transaction @@ -1552,9 +1552,9 @@ private void Login(ServerInfo server, TimeoutTimer timeout, string newPassword, private void LoginFailure() { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#"); + Log.Trace($" {ObjectID}#"); } // If the parser was allocated and we failed, then we must have failed on @@ -1681,9 +1681,9 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt int routingAttempts = 0; ServerInfo originalServerInfo = serverInfo; // serverInfo may end up pointing to new object due to routing, original object is used to set CurrentDatasource - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, host={serverInfo.UserServerName}"); + Log.Trace($" {ObjectID}#, host={serverInfo.UserServerName}"); } int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. @@ -1790,9 +1790,9 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt if (_routingInfo != null) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Routed to {serverInfo.ExtendedServerName}"); + Log.Trace($" Routed to {serverInfo.ExtendedServerName}"); } if (routingAttempts > _maxNumberOfRedirectRoute) @@ -1882,9 +1882,9 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt // Sleep for a bit to prevent clogging the network with requests, // then update sleep interval for next iteration (max 1 second interval) - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]"); + Log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]"); } Thread.Sleep(sleepInterval); @@ -1968,9 +1968,9 @@ TimeoutTimer timeout Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used"); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, useFailover={useFailoverHost}[bool], primary={primaryServerInfo.UserServerName}, failover={failoverHost}"); + Log.Trace($" {ObjectID}#, useFailover={useFailoverHost}[bool], primary={primaryServerInfo.UserServerName}, failover={failoverHost}"); } int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. @@ -2039,9 +2039,9 @@ TimeoutTimer timeout // Primary server may give us a different failover partner than the connection string indicates. Update it if (null != ServerProvidedFailOverPartner && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, new failover partner={ServerProvidedFailOverPartner}"); + Log.Trace($" {ObjectID}#, new failover partner={ServerProvidedFailOverPartner}"); } failoverServerInfo.SetDerivedNames(protocol, ServerProvidedFailOverPartner); } @@ -2075,9 +2075,9 @@ TimeoutTimer timeout } routingAttempts++; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Routed to {_routingInfo.ServerName}"); + Log.Trace($" Routed to {_routingInfo.ServerName}"); } if (_parser != null) @@ -2147,9 +2147,9 @@ TimeoutTimer timeout // the network with requests, then update sleep interval for next iteration (max 1 second interval) if (1 == attemptNumber % 2) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]"); + Log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]"); } Thread.Sleep(sleepInterval); @@ -2226,9 +2226,9 @@ private void ResolveExtendedServerName(ServerInfo serverInfo, bool aliasLookup, // Common code path for making one attempt to establish a connection and log in to server. private void AttemptOneLogin(ServerInfo serverInfo, string newPassword, SecureString newSecurePassword, bool ignoreSniOpenTimeout, TimeoutTimer timeout, bool withFailover = false, bool isFirstTransparentAttempt = true, bool disableTnir = false) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, timout={timeout.MillisecondsRemaining}[msec], server={serverInfo.ExtendedServerName}"); + Log.Trace($" {ObjectID}#, timout={timeout.MillisecondsRemaining}[msec], server={serverInfo.ExtendedServerName}"); } _routingInfo = null; // forget routing information @@ -2382,9 +2382,9 @@ internal void BreakConnection() { var connection = Connection; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Breaking connection."); + Log.Trace($" {ObjectID}#, Breaking connection."); } DoomThisConnection(); // Mark connection as unusable, so it will be destroyed if (null != connection) @@ -2477,9 +2477,9 @@ internal void OnEnvChange(SqlEnvChange rec) case TdsEnums.ENV_ROUTING: - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Received routing info"); + Log.Trace($" {ObjectID}#, Received routing info"); } if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0) @@ -2526,9 +2526,9 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) Debug.Assert(fedAuthInfo != null, "info should not be null."); Debug.Assert(_dbConnectionPoolAuthenticationContextKey == null, "_dbConnectionPoolAuthenticationContextKey should be null."); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Generating federated authentication token"); + Log.Trace($" {ObjectID}#, Generating federated authentication token"); } DbConnectionPoolAuthenticationContext dbConnectionPoolAuthenticationContext = null; @@ -2561,9 +2561,9 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // And on successful login, try to update the cache with the new token. if (contextValidity <= _dbAuthenticationContextUnLockedRefreshTimeSpan) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, " + + Log.Trace($" {ObjectID}#, " + $"The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + $"The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. Current Time is {DateTime.UtcNow.ToLongTimeString()}."); } @@ -2587,9 +2587,9 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // If a thread is already doing the refresh, just use the existing token in the cache and proceed. else if (contextValidity <= _dbAuthenticationContextLockedRefreshTimeSpan) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, " + + Log.Trace($" {ObjectID}#, " + $"The authentication context needs a refresh.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. " + $"Current Time is {DateTime.UtcNow.ToLongTimeString()}."); } @@ -2606,16 +2606,16 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // Indicate in Bid Trace that we are successful with the update. if (attemptRefreshTokenLocked) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" %d#, The attempt to get a new access token succeeded under the locked mode."); + Log.Trace($" %d#, The attempt to get a new access token succeeded under the locked mode."); } } } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token."); + Log.Trace($" {ObjectID}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token."); } } } @@ -2676,9 +2676,9 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP // Else some other thread is already updating it, so just proceed forward with the existing token in the cache. if (dbConnectionPoolAuthenticationContext.LockToUpdate()) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, " + + Log.Trace($" {ObjectID}#, " + $"Acquired the lock to update the authentication context.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. " + $"Current Time is {DateTime.UtcNow.ToLongTimeString()}."); } @@ -2687,9 +2687,9 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP } else { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Refreshing the context is already in progress by another thread."); + Log.Trace($" {ObjectID}#, Refreshing the context is already in progress by another thread."); } } @@ -2848,9 +2848,9 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) || _timeout.IsExpired || _timeout.MillisecondsRemaining <= sleepInterval) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {msalException.ErrorCode}#"); + Log.Trace($" {msalException.ErrorCode}#"); } // Error[0] @@ -2870,10 +2870,10 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) throw exc; } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, sleeping {sleepInterval}[Milliseconds]"); - _log.Trace($" {ObjectID}#, remaining {_timeout.MillisecondsRemaining}[Milliseconds]"); + Log.Trace($" {ObjectID}#, sleeping {sleepInterval}[Milliseconds]"); + Log.Trace($" {ObjectID}#, remaining {_timeout.MillisecondsRemaining}[Milliseconds]"); } Thread.Sleep(sleepInterval); @@ -2891,9 +2891,9 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) _newDbConnectionPoolAuthenticationContext = new DbConnectionPoolAuthenticationContext(fedAuthToken.accessToken, expirationTime); } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Finished generating federated authentication token."); + Log.Trace($" {ObjectID}#, Finished generating federated authentication token."); } return fedAuthToken; @@ -2958,16 +2958,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_FEDAUTH: { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Received feature extension acknowledgement for federated authentication"); + Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for federated authentication"); } if (!_federatedAuthenticationRequested) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Did not request federated authentication"); + Log.Trace($" {ObjectID}#, Did not request federated authentication"); } throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); @@ -2982,9 +2982,9 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // The server shouldn't have sent any additional data with the ack (like a nonce) if (data.Length != 0) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, " + + Log.Trace($" {ObjectID}#, " + $"Federated authentication feature extension ack for MSAL and Security Token includes extra data"); } throw SQL.ParsingError(ParsingErrorState.FedAuthFeatureAckContainsExtraData); @@ -2993,9 +2993,9 @@ internal void OnFeatureExtAck(int featureId, byte[] data) default: Debug.Fail("Unknown _fedAuthLibrary type"); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Attempting to use unknown federated authentication library"); + Log.Trace($" {ObjectID}#, Attempting to use unknown federated authentication library"); } throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType); @@ -3013,16 +3013,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) Debug.Assert(newAuthenticationContextInCacheAfterAddOrUpdate != null, "newAuthenticationContextInCacheAfterAddOrUpdate should not be null."); #if DEBUG - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) { - _log.Trace($" {ObjectID}#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts."); + Log.Trace($" {ObjectID}#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts."); } else { - _log.Trace($" {ObjectID}#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value."); + Log.Trace($" {ObjectID}#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value."); } } #endif @@ -3032,16 +3032,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_TCE: { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Received feature extension acknowledgement for TCE"); + Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for TCE"); } if (data.Length < 1) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Unknown version number for TCE"); + Log.Trace($" {ObjectID}#, Unknown version number for TCE"); } throw SQL.ParsingError(ParsingErrorState.TceUnknownVersion); @@ -3050,9 +3050,9 @@ internal void OnFeatureExtAck(int featureId, byte[] data) byte supportedTceVersion = data[0]; if (0 == supportedTceVersion || supportedTceVersion > TdsEnums.MAX_SUPPORTED_TCE_VERSION) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Invalid version number for TCE"); + Log.Trace($" {ObjectID}#, Invalid version number for TCE"); } throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidVersion, supportedTceVersion); } @@ -3072,16 +3072,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS: { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Received feature extension acknowledgement for GlobalTransactions"); + Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for GlobalTransactions"); } if (data.Length < 1) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Unknown version number for GlobalTransactions"); + Log.Trace($" {ObjectID}#, Unknown version number for GlobalTransactions"); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); @@ -3097,16 +3097,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_AZURESQLSUPPORT: { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Received feature extension acknowledgement for AzureSQLSupport"); + Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for AzureSQLSupport"); } if (data.Length < 1) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Unknown token for AzureSQLSupport"); + Log.Trace($" {ObjectID}#, Unknown token for AzureSQLSupport"); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); @@ -3115,25 +3115,25 @@ internal void OnFeatureExtAck(int featureId, byte[] data) IsAzureSQLConnection = true; // Bit 0 for RO/FP support - if ((data[0] & 1) == 1 && _log.IsTraceEnabled()) + if ((data[0] & 1) == 1 && Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, FailoverPartner enabled with Readonly intent for AzureSQL DB"); + Log.Trace($" {ObjectID}#, FailoverPartner enabled with Readonly intent for AzureSQL DB"); } break; } case TdsEnums.FEATUREEXT_DATACLASSIFICATION: { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Received feature extension acknowledgement for DATACLASSIFICATION"); + Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for DATACLASSIFICATION"); } if (data.Length < 1) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION"); + Log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION"); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); @@ -3141,18 +3141,18 @@ internal void OnFeatureExtAck(int featureId, byte[] data) byte supportedDataClassificationVersion = data[0]; if ((0 == supportedDataClassificationVersion) || (supportedDataClassificationVersion > TdsEnums.MAX_SUPPORTED_DATA_CLASSIFICATION_VERSION)) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Invalid version number for DATACLASSIFICATION"); + Log.Trace($" {ObjectID}#, Invalid version number for DATACLASSIFICATION"); } throw SQL.ParsingErrorValue(ParsingErrorState.DataClassificationInvalidVersion, supportedDataClassificationVersion); } if (data.Length != 2) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION"); + Log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION"); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } @@ -3163,16 +3163,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_UTF8SUPPORT: { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Received feature extension acknowledgement for UTF8 support"); + Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for UTF8 support"); } if (data.Length < 1) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Unknown value for UTF8 support"); + Log.Trace($" {ObjectID}#, Unknown value for UTF8 support"); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs index 711b6bb8f7..09f81fc8af 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -143,8 +143,10 @@ override public void Commit() SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -207,7 +209,7 @@ override public void Commit() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -268,10 +270,10 @@ override public void Rollback() { if (IsYukonPartialZombie) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { // Put something in the trace in case a customer has an issue - _log.Trace($" {ObjectID}# partial zombie no rollback required"); + Log.Trace($" {ObjectID}# partial zombie no rollback required"); } _internalTransaction = null; // yukon zombification @@ -281,8 +283,10 @@ override public void Rollback() ZombieCheck(); SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}#"); - _log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {_log.Guid}\n"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + if (Log.IsCorrelationEnabled()) + Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -333,7 +337,7 @@ override public void Rollback() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } } @@ -347,7 +351,7 @@ public void Rollback(string transactionName) SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}# transactionName='{transactionName}'"); + var scopeID = Log.ScopeEnter($" {ObjectID}# transactionName='{transactionName}'"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -398,7 +402,7 @@ public void Rollback(string transactionName) _isFromAPI = false; SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -411,7 +415,7 @@ public void Save(string savePointName) SqlStatistics statistics = null; - var scopeID = _log.ScopeEnter($" {ObjectID}# savePointName='{savePointName}'"); + var scopeID = Log.ScopeEnter($" {ObjectID}# savePointName='{savePointName}'"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -458,7 +462,7 @@ public void Save(string savePointName) finally { SqlStatistics.StopTimer(statistics); - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -477,9 +481,9 @@ internal void Zombie() if (null != internalConnection && internalConnection.IsYukonOrNewer && !_isFromAPI) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# yukon deferred zombie"); + Log.Trace($" {ObjectID}# yukon deferred zombie"); } } else diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index e325c77355..7da7549947 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -504,9 +504,9 @@ internal void Connect(ServerInfo serverInfo, // now allocate proper length of buffer _sniSpnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength]; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication"); + Log.Trace($" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication"); } } else @@ -514,30 +514,30 @@ internal void Connect(ServerInfo serverInfo, _sniSpnBuffer = null; if (authType == SqlAuthenticationMethod.ActiveDirectoryPassword) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Active Directory Password authentication"); + Log.Trace($" Active Directory Password authentication"); } } else if (authType == SqlAuthenticationMethod.SqlPassword) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" SQL Password authentication"); + Log.Trace($" SQL Password authentication"); } } else if (authType == SqlAuthenticationMethod.ActiveDirectoryInteractive) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Active Directory Interactive authentication"); + Log.Trace($" Active Directory Interactive authentication"); } } else { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" SQL authentication"); + Log.Trace($" SQL authentication"); } } } @@ -576,9 +576,9 @@ internal void Connect(ServerInfo serverInfo, // a bad error could be returned (as it was when it was freed to early for me). _physicalStateObj.Dispose(); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Login failure"); + Log.Trace($" Login failure"); } ThrowExceptionAndWarning(_physicalStateObj); @@ -609,9 +609,9 @@ internal void Connect(ServerInfo serverInfo, UInt32 result = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId); Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Sending prelogin handshake"); + Log.Trace($" Sending prelogin handshake"); } // UNDONE - send "" for instance now, need to fix later @@ -622,9 +622,9 @@ internal void Connect(ServerInfo serverInfo, _physicalStateObj.SniContext = SniContext.Snix_PreLogin; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Consuming prelogin handshake"); + Log.Trace($" Consuming prelogin handshake"); } PreLoginHandshakeStatus status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, @@ -632,9 +632,9 @@ internal void Connect(ServerInfo serverInfo, if (status == PreLoginHandshakeStatus.InstanceFailure) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Prelogin handshake unsuccessful. Reattempting prelogin handshake"); + Log.Trace($" Prelogin handshake unsuccessful. Reattempting prelogin handshake"); } _physicalStateObj.Dispose(); // Close previous connection @@ -646,9 +646,9 @@ internal void Connect(ServerInfo serverInfo, { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Login failure"); + Log.Trace($" Login failure"); } ThrowExceptionAndWarning(_physicalStateObj); } @@ -656,9 +656,9 @@ internal void Connect(ServerInfo serverInfo, UInt32 retCode = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId); Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Sending prelogin handshake"); + Log.Trace($" Sending prelogin handshake"); } SendPreLoginHandshake(instanceName, encrypt, !string.IsNullOrEmpty(certificate), useOriginalAddressInfo); status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, out marsCapable, @@ -668,17 +668,17 @@ internal void Connect(ServerInfo serverInfo, // one pre-login packet and know we are connecting to Shiloh. if (status == PreLoginHandshakeStatus.InstanceFailure) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Prelogin handshake unsuccessful. Login failure"); + Log.Trace($" Prelogin handshake unsuccessful. Login failure"); } throw SQL.InstanceFailure(); } } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Prelogin handshake successful"); + Log.Trace($" Prelogin handshake successful"); } if (_fMARS && marsCapable) @@ -772,9 +772,9 @@ internal TdsParserStateObject CreateSession() { TdsParserStateObject session = new TdsParserStateObject(this, (SNIHandle)_pMarsPhysicalConObj.Handle, true); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# created session {session.ObjectID}"); + Log.Trace($" {ObjectID}# created session {session.ObjectID}"); } return session; @@ -791,18 +791,18 @@ internal TdsParserStateObject GetSession(object owner) session = _sessionPool.GetSession(owner); Debug.Assert(!session._pendingData, "pending data on a pooled MARS session"); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# getting session {session.ObjectID} from pool"); + Log.Trace($" {ObjectID}# getting session {session.ObjectID} from pool"); } } else { session = _physicalStateObj; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# getting physical session {session.ObjectID}"); + Log.Trace($" {ObjectID}# getting physical session {session.ObjectID}"); } } Debug.Assert(session._outputPacketNumber == 1, "The packet number is expected to be 1"); @@ -1018,9 +1018,9 @@ private void SendPreLoginHandshake(byte[] instanceName, bool encrypt, bool clien offset += actIdSize; optionDataSize += actIdSize; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" ClientConnectionID {_connHandler._clientConnectionId.ToString()}, ActivityID {actId.ToString()}"); + Log.Trace($" ClientConnectionID {_connHandler._clientConnectionId.ToString()}, ActivityID {actId.ToString()}"); } break; @@ -1332,9 +1332,9 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod // Only 0x00 and 0x01 are accepted values from the server. if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, " + + Log.Trace($" {ObjectID}#, " + $"Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {(int)payload[payloadOffset]}."); } @@ -1377,11 +1377,11 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod internal void Deactivate(bool connectionIsDoomed) { // Called when the connection that owns us is deactivated. - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# deactivating"); + Log.Trace($" {ObjectID}# deactivating"); - _log.Trace($" {ObjectID}#, {TraceString()}"); + Log.Trace($" {ObjectID}#, {TraceString()}"); } if (MARSOn) @@ -1538,9 +1538,9 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle Debug.Assert(temp.Count > 0, "TdsParser::ThrowExceptionAndWarning called with no exceptions or warnings!"); if (temp.Count == 0) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {ObjectID}#"); + Log.Trace($" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {ObjectID}#"); } } Debug.Assert(_connHandler != null, "TdsParser::ThrowExceptionAndWarning called with null connectionHandler!"); @@ -2262,9 +2262,9 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead _state = TdsParserState.Broken; _connHandler.BreakConnection(); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Potential multi-threaded misuse of connection, unexpected TDS token found {ObjectID}#"); + Log.Trace($" Potential multi-threaded misuse of connection, unexpected TDS token found {ObjectID}#"); } throw SQL.ParsingErrorToken(ParsingErrorState.InvalidTdsTokenReceived, token); // MDAC 82443 } @@ -2587,9 +2587,9 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead } case TdsEnums.SQLLOGINACK: { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Received login acknowledgement token"); + Log.Trace($" Received login acknowledgement token"); } SqlLoginAck ack; if (!TryProcessLoginAck(stateObj, out ack)) @@ -2613,9 +2613,9 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead _connHandler._federatedAuthenticationInfoReceived = true; SqlFedAuthInfo info; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Received federated authentication info token"); + Log.Trace($" Received federated authentication info token"); } if (!TryProcessFedAuthInfo(stateObj, tokenLength, out info)) @@ -4029,17 +4029,17 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, SqlFedAuthInfo tempFedAuthInfo = new SqlFedAuthInfo(); // Skip reading token length, since it has already been read in caller - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" FEDAUTHINFO token stream length = {tokenLen}"); + Log.Trace($" FEDAUTHINFO token stream length = {tokenLen}"); } if (tokenLen < sizeof(uint)) { // the token must at least contain a DWORD indicating the number of info IDs - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); + Log.Trace($" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); } throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen); } @@ -4048,17 +4048,17 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, uint optionsCount; if (!stateObj.TryReadUInt32(out optionsCount)) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream."); + Log.Trace($" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream."); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadCountOfInfoIds); } tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" CountOfInfoIDs = {optionsCount.ToString(CultureInfo.InvariantCulture)}"); + Log.Trace($" CountOfInfoIDs = {optionsCount.ToString(CultureInfo.InvariantCulture)}"); } if (tokenLen > 0) @@ -4068,16 +4068,16 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, int totalRead = 0; bool successfulRead = stateObj.TryReadByteArray(tokenData, 0, tokenLen, out totalRead); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Read rest of FEDAUTHINFO token stream: {BitConverter.ToString(tokenData, 0, totalRead)}"); + Log.Trace($" Read rest of FEDAUTHINFO token stream: {BitConverter.ToString(tokenData, 0, totalRead)}"); } if (!successfulRead || totalRead != tokenLen) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Failed to read FEDAUTHINFO token stream. Attempted to read {tokenLen} bytes, actually read {totalRead}"); + Log.Trace($" Failed to read FEDAUTHINFO token stream. Attempted to read {tokenLen} bytes, actually read {totalRead}"); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadTokenStream); } @@ -4100,7 +4100,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, uint dataLen = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 1))); uint dataOffset = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 5))); - _log.Trace($" FedAuthInfoOpt: ID={id}, DataLen={dataLen.ToString(CultureInfo.InvariantCulture)}, Offset={dataOffset.ToString(CultureInfo.InvariantCulture)}\n"); + Log.Trace($" FedAuthInfoOpt: ID={id}, DataLen={dataLen.ToString(CultureInfo.InvariantCulture)}, Offset={dataOffset.ToString(CultureInfo.InvariantCulture)}\n"); // offset is measured from optCount, so subtract to make offset measured // from the beginning of tokenData @@ -4112,9 +4112,9 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, // if dataOffset points to a region within FedAuthInfoOpt or after the end of the token, throw if (dataOffset < totalOptionsSize || dataOffset >= tokenLen) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" FedAuthInfoDataOffset points to an invalid location."); + Log.Trace($" FedAuthInfoDataOffset points to an invalid location."); } throw SQL.ParsingErrorOffset(ParsingErrorState.FedAuthInfoInvalidOffset, unchecked((int)dataOffset)); } @@ -4127,24 +4127,24 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } catch (ArgumentOutOfRangeException e) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Failed to read FedAuthInfoData."); + Log.Trace($" Failed to read FedAuthInfoData."); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadData, e); } catch (ArgumentException e) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" FedAuthInfoData is not in unicode format."); + Log.Trace($" FedAuthInfoData is not in unicode format."); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e); } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" FedAuthInfoData: {data}"); + Log.Trace($" FedAuthInfoData: {data}"); } // store data in tempFedAuthInfo @@ -4157,9 +4157,9 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, tempFedAuthInfo.stsurl = data; break; default: - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Ignoring unknown federated authentication info option: {id}"); + Log.Trace($" Ignoring unknown federated authentication info option: {id}"); } break; } @@ -4167,24 +4167,24 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } else { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" FEDAUTHINFO token stream is not long enough to contain the data it claims to."); + Log.Trace($" FEDAUTHINFO token stream is not long enough to contain the data it claims to."); } throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForData, tokenLen); } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Processed FEDAUTHINFO token stream: {tempFedAuthInfo.ToString()}"); + Log.Trace($" Processed FEDAUTHINFO token stream: {tempFedAuthInfo.ToString()}"); } if (string.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || string.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) { // We should be receiving both stsurl and spn - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" FEDAUTHINFO token stream does not contain both STSURL and SPN."); + Log.Trace($" FEDAUTHINFO token stream does not contain both STSURL and SPN."); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDoesNotContainStsurlAndSpn); } @@ -4613,9 +4613,9 @@ internal bool TryProcessTceCryptoMetadata(TdsParserStateObject stateObj, // validate the index (ordinal passed) if (index >= cipherTable.Value.Size) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Incorrect ordinal received {index}, max tab size: {cipherTable.Value.Size}"); + Log.Trace($" Incorrect ordinal received {index}, max tab size: {cipherTable.Value.Size}"); } throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidOrdinalIntoCipherInfoTable, index); } @@ -8884,9 +8884,9 @@ internal void TdsLogin(SqlLogin rec, WriteInt(log7Flags, _physicalStateObj); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, TDS Login7 flags = {log7Flags}:"); + Log.Trace($" {ObjectID}#, TDS Login7 flags = {log7Flags}:"); } WriteInt(0, _physicalStateObj); // ClientTimeZone is not used @@ -9046,9 +9046,9 @@ internal void TdsLogin(SqlLogin rec, }; if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Sending federated authentication feature request"); + Log.Trace($" Sending federated authentication feature request"); } Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null."); WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true); @@ -9123,9 +9123,9 @@ internal void SendFedAuthToken(SqlFedAuthToken fedAuthToken) Debug.Assert(fedAuthToken != null, "fedAuthToken cannot be null"); Debug.Assert(fedAuthToken.accessToken != null, "fedAuthToken.accessToken cannot be null"); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Sending federated authentication token"); + Log.Trace($" Sending federated authentication token"); } _physicalStateObj._outputMessageType = TdsEnums.MT_FEDAUTH; @@ -9518,9 +9518,9 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) { int old_outputPacketNumber = stateObj._outputPacketNumber; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Exception caught on ExecuteXXX: '{e.ToString()}'"); + Log.Trace($" Exception caught on ExecuteXXX: '{e.ToString()}'"); } if (stateObj.HasOpenResult) @@ -9555,9 +9555,9 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) } } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Exception rethrown."); + Log.Trace($" Exception rethrown."); } } @@ -9614,9 +9614,9 @@ internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationReques stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#"); + Log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#"); } } stateObj.SniContext = SniContext.Snix_Execute; @@ -9746,9 +9746,9 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#"); + Log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#"); } } stateObj.SniContext = SniContext.Snix_Execute; @@ -10614,9 +10614,9 @@ private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefa var sendDefaultValue = sendDefault ? 1 : 0; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, Sending parameter '{param.ParameterName}', default flag={sendDefaultValue}, metadata:{metaData.TraceString(3)}"); + Log.Trace($" {ObjectID}#, Sending parameter '{param.ParameterName}', default flag={sendDefaultValue}, metadata:{metaData.TraceString(3)}"); } // @@ -11673,7 +11673,7 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio Debug.Assert(-1 <= timeout, "Timeout"); - _log.NotificationsTrace($" NotificationRequest: userData: '{notificationRequest.UserData}', options: '{notificationRequest.Options}', timeout: '{notificationRequest.Timeout}'\n"); + Log.NotificationsTrace($" NotificationRequest: userData: '{notificationRequest.UserData}', options: '{notificationRequest.Options}', timeout: '{notificationRequest.Timeout}'\n"); WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj); // Query notifications Type @@ -11700,9 +11700,9 @@ private void WriteTraceHeaderData(TdsParserStateObject stateObj) stateObj.WriteByteArray(actId.Id.ToByteArray(), GUID_SIZE, 0); // Id (Guid) WriteUnsignedInt(actId.Sequence, stateObj); // sequence number - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" ActivityID {actId.ToString()}"); + Log.Trace($" ActivityID {actId.ToString()}"); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index 3118813f53..eb1cf171bf 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -38,9 +38,9 @@ internal TdsParserSessionPool(TdsParser parser) _freeStateObjects = new TdsParserStateObject[MaxInactiveCount]; _freeStateObjectCount = 0; - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# created session pool for parser {parser.ObjectID}"); + Log.Trace($" {ObjectID}# created session pool for parser {parser.ObjectID}"); } } @@ -66,7 +66,7 @@ internal void Deactivate() // cache to make sure they're cleaned up and then we dispose of // sessions that are past what we want to keep around. - var scopeID = _log.ScopeEnter($" {ObjectID}# deactivating cachedCount={_cachedCount}\n"); + var scopeID = Log.ScopeEnter($" {ObjectID}# deactivating cachedCount={_cachedCount}\n"); try { @@ -87,9 +87,9 @@ internal void Deactivate() { // TODO: consider adding a performance counter for the number of sessions we reclaim - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# reclaiming session {session.ObjectID}"); + Log.Trace($" {ObjectID}# reclaiming session {session.ObjectID}"); } PutSession(session); @@ -102,7 +102,7 @@ internal void Deactivate() } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -125,9 +125,9 @@ internal void BestEffortCleanup() internal void Dispose() { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# disposing cachedCount={_cachedCount}"); + Log.Trace($" {ObjectID}# disposing cachedCount={_cachedCount}"); } lock (_cache) @@ -189,9 +189,9 @@ internal TdsParserStateObject GetSession(object owner) // No free objects, create a new one session = _parser.CreateSession(); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# adding session {session.ObjectID} to pool"); + Log.Trace($" {ObjectID}# adding session {session.ObjectID} to pool"); } _cache.Add(session); @@ -201,9 +201,9 @@ internal TdsParserStateObject GetSession(object owner) session.Activate(owner); } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# using session {session.ObjectID}"); + Log.Trace($" {ObjectID}# using session {session.ObjectID}"); } return session; @@ -227,9 +227,9 @@ internal void PutSession(TdsParserStateObject session) else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount)) { // Session is good to re-use and our cache has space - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# keeping session {session.ObjectID} cachedCount={_cachedCount}"); + Log.Trace($" {ObjectID}# keeping session {session.ObjectID} cachedCount={_cachedCount}"); } Debug.Assert(!session._pendingData, "pending data on a pooled session?"); @@ -240,9 +240,9 @@ internal void PutSession(TdsParserStateObject session) else { // Either the session is bad, or we have no cache space - so dispose the session and remove it - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}# disposing session {session.ObjectID} cachedCount={_cachedCount}"); + Log.Trace($" {ObjectID}# disposing session {session.ObjectID} cachedCount={_cachedCount}"); } bool removed = _cache.Remove(session); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index dcf08c1e20..868bf185de 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -561,11 +561,11 @@ internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount) return false; } - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {stateObj.ObjectID}#, NBCROW bitmap received, column count = {columnsCount}"); + Log.Trace($" {stateObj.ObjectID}#, NBCROW bitmap received, column count = {columnsCount}"); } - _log.TraceBin($" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); + Log.TraceBin($" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); return true; } @@ -919,16 +919,16 @@ internal int DecrementPendingCallbacks(bool release) { int remaining = Interlocked.Decrement(ref _pendingCallbacks); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, after decrementing _pendingCallbacks: { _pendingCallbacks}"); + Log.Trace($" {ObjectID}#, after decrementing _pendingCallbacks: { _pendingCallbacks}"); } if ((0 == remaining || release) && _gcHandle.IsAllocated) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, FREEING HANDLE!"); + Log.Trace($" {ObjectID}#, FREEING HANDLE!"); } _gcHandle.Free(); } @@ -1038,9 +1038,9 @@ internal int IncrementPendingCallbacks() { int remaining = Interlocked.Increment(ref _pendingCallbacks); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, after incrementing _pendingCallbacks: {_pendingCallbacks}"); + Log.Trace($" {ObjectID}#, after incrementing _pendingCallbacks: {_pendingCallbacks}"); } Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}"); @@ -2175,9 +2175,9 @@ internal bool TryReadNetworkPacket() _snapshot.CheckStack(new StackTrace()); } #endif - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Async packet replay"); + Log.Trace($" Async packet replay"); } return true; } @@ -2600,9 +2600,9 @@ internal bool IsConnectionAlive(bool throwOnException) if ((error != TdsEnums.SNI_SUCCESS) && (error != TdsEnums.SNI_WAIT_TIMEOUT)) { // Connection is dead - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" received error {(int)error} on idle connection"); + Log.Trace($" received error {(int)error} on idle connection"); } isAlive = false; if (throwOnException) @@ -2819,9 +2819,9 @@ public void ProcessSniPacket(IntPtr packet, UInt32 error) SniReadStatisticsAndTracing(); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.TraceBin($" Packet read", _inBuff, (UInt16)_inBytesRead); + Log.TraceBin($" Packet read", _inBuff, (UInt16)_inBytesRead); } AssertValidState(); @@ -2980,9 +2980,9 @@ public void WriteAsyncCallback(IntPtr key, IntPtr packet, UInt32 sniError) { if (sniError != TdsEnums.SNI_SUCCESS) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" write async returned error code {(int)sniError}"); + Log.Trace($" write async returned error code {(int)sniError}"); } try @@ -3452,9 +3452,9 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr if (error != TdsEnums.SNI_SUCCESS) { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" write async returned error code {(int)error}"); + Log.Trace($" write async returned error code {(int)error}"); } AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(); @@ -3492,9 +3492,9 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr } else { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" write async returned error code {(int)sniError}"); + Log.Trace($" write async returned error code {(int)sniError}"); } AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(callerHasConnectionLock); @@ -3556,9 +3556,9 @@ internal void SendAttention(bool mustTakeWriteLock = false) _parser._asyncWrite = false; // stop async write SNIWritePacket(Handle, attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Send Attention ASync."); + Log.Trace($" Send Attention ASync."); } } finally @@ -3582,11 +3582,11 @@ internal void SendAttention(bool mustTakeWriteLock = false) _attentionSending = false; } - _log.TraceBin($" Packet sent", _outBuff, (ushort)_outBytesUsed); + Log.TraceBin($" Packet sent", _outBuff, (ushort)_outBytesUsed); - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" Attention sent to the server."); + Log.Trace($" Attention sent to the server."); } AssertValidState(); @@ -3771,7 +3771,7 @@ private void SniWriteStatisticsAndTracing() _traceChangePasswordOffset = 0; _traceChangePasswordLength = 0; } - _log.TraceBin($" Packet sent", _outBuff, (UInt16)_outBytesUsed); + Log.TraceBin($" Packet sent", _outBuff, (UInt16)_outBytesUsed); } [Conditional("DEBUG")] diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs index 07dcb9c1b6..dcdeb14d5c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs @@ -54,8 +54,8 @@ internal SqlInternalTransaction(SqlInternalConnection innerConnection, Transacti internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction, long transactionId) { - - _log.PoolerTrace($" {ObjectID}#, Created for connection {innerConnection.ObjectID}#, outer transaction {((null != outerTransaction) ? outerTransaction.ObjectID : -1)}#, Type {(int)type}"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Created for connection {innerConnection.ObjectID}#, outer transaction {((null != outerTransaction) ? outerTransaction.ObjectID : -1)}#, Type {(int)type}"); _innerConnection = innerConnection; _transactionType = type; @@ -271,7 +271,9 @@ internal void CloseFromConnection() Debug.Assert(innerConnection != null, "How can we be here if the connection is null?"); - _log.PoolerTrace($" {ObjectID}#, Closing\n"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Closing"); + bool processFinallyBlock = true; try { @@ -298,7 +300,7 @@ internal void CloseFromConnection() internal void Commit() { - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); if (_innerConnection.IsLockedForBulkCopy) { @@ -343,7 +345,7 @@ internal void Commit() } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -372,7 +374,9 @@ internal void Dispose() private /*protected override*/ void Dispose(bool disposing) { - _log.PoolerTrace($" {ObjectID}#, Disposing\n"); + if (Log.IsPoolerTraceEnabled()) + Log.PoolerTrace($" {ObjectID}#, Disposing"); + if (disposing) { if (null != _innerConnection) @@ -427,7 +431,7 @@ internal void InitParent(SqlTransaction transaction) internal void Rollback() { - var scopeID = _log.ScopeEnter($" {ObjectID}#"); + var scopeID = Log.ScopeEnter($" {ObjectID}#"); if (_innerConnection.IsLockedForBulkCopy) { @@ -468,13 +472,13 @@ internal void Rollback() } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } internal void Rollback(string transactionName) { - var scopeID = _log.ScopeEnter($" {ObjectID}#, transactionName='{transactionName}'"); + var scopeID = Log.ScopeEnter($" {ObjectID}#, transactionName='{transactionName}'"); if (_innerConnection.IsLockedForBulkCopy) { @@ -517,13 +521,13 @@ internal void Rollback(string transactionName) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } internal void Save(string savePointName) { - var scopeID = _log.ScopeEnter($" {ObjectID}#, savePointName='{savePointName}'"); + var scopeID = Log.ScopeEnter($" {ObjectID}#, savePointName='{savePointName}'"); _innerConnection.ValidateConnectionForExecute(null); @@ -555,7 +559,7 @@ internal void Save(string savePointName) } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs index 83eb7be4b3..8d2fdef1e5 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs @@ -66,7 +66,7 @@ Int64 allocationSize ) { - var scopeID = _log.ScopeEnter($" { ObjectID}# access={(int)access} options={(int)options} path='{path}'"); + var scopeID = Log.ScopeEnter($" { ObjectID}# access={(int)access} options={(int)options} path='{path}'"); try { @@ -92,7 +92,7 @@ Int64 allocationSize } finally { - _log.ScopeLeave(scopeID); + Log.ScopeLeave(scopeID); } } @@ -715,9 +715,9 @@ Int64 allocationSize UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode); try { - if (_log.IsTraceEnabled()) + if (Log.IsTraceEnabled()) { - _log.Trace($" {ObjectID}#, desiredAccess=0x{(int)nDesiredAccess}, allocationSize={allocationSize}, " + + Log.Trace($" {ObjectID}#, desiredAccess=0x{(int)nDesiredAccess}, allocationSize={allocationSize}, " + $"fileAttributes=0x%{0}, shareAccess=0x{(int)shareAccess}, dwCreateDisposition=0x{dwCreateDisposition}, createOptions=0x{ dwCreateOptions}"); } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs new file mode 100644 index 0000000000..66950c104e --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs @@ -0,0 +1,100 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Diagnostics.Tracing; +using System.Linq; +using System.Threading.Tasks; +using Xunit; +using static Microsoft.Data.SqlClient.SqlClientEventSource; + +namespace Microsoft.Data.SqlClient.ManualTesting.Tests.EventSourceTest +{ + public class EventSourceListenerGeneral : EventListener + { + public EventLevel Level { get; set; } + public EventKeywords Keyword { get; set; } + + public List events = new List(); + + protected override void OnEventWritten(EventWrittenEventArgs eventData) + { + events = eventData.Payload.ToList(); + } + } + + public class SqlClientEventSourceTest + { + [Fact] + public void TestSqlClientEventSourceName() + { + Assert.Equal("Microsoft.Data.SqlClient.EventSource", SqlClientEventSource.Log.Name); + } + + //The values are equivilant to Keywords value inside SqlClientEventSource + [Theory] + [InlineData(new int[] { 1, 2, 4, 8, 16 })] + public async void TestEventKeywords(int[] values) + { + using (EventSourceListenerGeneral listener = new EventSourceListenerGeneral()) + { + listener.Keyword = (EventKeywords)values[0]; + listener.Level = EventLevel.Informational; + bool status = false; + + //Events should be disabled by default + Assert.False(Log.IsEnabled()); + + //We try to Enable events. + //Since we have to have 2 arguments in EnableEvents Informational is selected arbitrary. + //If we do not wait for tasks to be completed Assert.True will run before other calls and will return false. + var task1 = Task.Run(() => + { + listener.EnableEvents(Log, EventLevel.Informational); + }); + await task1.ContinueWith((t) => + { + status = Log.IsEnabled(); + }); + Assert.True(status); + + //check if we are able to disable all the events + var task2 = Task.Run(() => + { + listener.DisableEvents(Log); + }); + await task2.ContinueWith((t) => + { + status = Log.IsEnabled(); + }); + Assert.False(status); + + //Check if we are able to enable specific Event keyword Trace + var task3 = Task.Run(() => + { + listener.EnableEvents(Log, listener.Level, listener.Keyword); + }); + await task3.ContinueWith((t) => + { + //(EventKeywords)1 is Trace which is defined in SqlClientEventSource Keywords class + status = Log.IsEnabled(EventLevel.Informational, SqlClientEventSource.Keywords.Trace); + }); + Assert.True(status); + + //Check if we are able to enable specific Event keyword. Scope + listener.Keyword = (EventKeywords)values[1]; + var task4 = Task.Run(() => + { + listener.EnableEvents(Log, listener.Level, listener.Keyword); + }); + await task4.ContinueWith((t) => + { + //(EventKeywords)1 is Trace which is defined in SqlClientEventSource Keywords class + status = Log.IsEnabled(EventLevel.Informational, SqlClientEventSource.Keywords.Scope); + }); + Assert.True(status); + } + } + } +} diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj index d48c72e562..eb483ed228 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj @@ -56,6 +56,7 @@ + From ebca24354fd70ddd6b22b0dce1fc60d268c5f6ce Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Thu, 30 Jan 2020 14:30:34 -0800 Subject: [PATCH 05/46] Taking unused variable out --- .../netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 410bd0fb36..d7355c8315 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -16,7 +16,6 @@ internal class SqlClientEventSource : EventSource { internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); private static long s_nextScopeId = 0; - private static long s_nextPoolerScopeId = 0; private static long s_nextNotificationScopeId = 0; private const int TraceEventId = 1; From c4d9289c7f2820a8dd6451895fc941dc8c9b8b14 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Thu, 30 Jan 2020 14:55:32 -0800 Subject: [PATCH 06/46] Ignore on .NetCore --- .../src/Microsoft.Data.SqlClient.csproj | 1 + .../Data/SqlClient/SqlClientEventSource.cs | 170 ++++++++++++++++++ .../EventSource/EventSourceTest.cs | 5 +- 3 files changed, 175 insertions(+), 1 deletion(-) create mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj index 481308bd83..f3f2f919aa 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj @@ -577,6 +577,7 @@ + True True diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs new file mode 100644 index 0000000000..d7355c8315 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -0,0 +1,170 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Text; +using System.Diagnostics.Tracing; +using System.Threading; +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Microsoft.Data.SqlClient.ManualTesting.Tests")] +namespace Microsoft.Data.SqlClient +{ + + [EventSource(Name = "Microsoft.Data.SqlClient.EventSource")] + internal class SqlClientEventSource : EventSource + { + internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); + private static long s_nextScopeId = 0; + private static long s_nextNotificationScopeId = 0; + + private const int TraceEventId = 1; + private const int EnterScopeId = 2; + private const int ExitScopeId = 3; + private const int TraceBinId = 4; + private const int CorrelationTraceId = 5; + private const int NotificationsScopeEnterId = 6; + private const int NotificationsTraceId = 7; + private const int PoolerScopeEnterId = 8; + private const int PoolerTraceId = 9; + private const int PutStrId = 10; + + //Any Prropery added to this class should be a power of 2. + public class Keywords + { + internal const EventKeywords Trace = (EventKeywords)0x0001; // Integer 1 + internal const EventKeywords Scope = (EventKeywords)0x0002; // Integer 2 + internal const EventKeywords NotificationTrace = (EventKeywords)0x0004; // Integer 4 + internal const EventKeywords Pooling = (EventKeywords)0x0008; // Integer 8 + internal const EventKeywords Correlation = (EventKeywords)0x0010; // Integer 16 + internal const EventKeywords NotificationScope = (EventKeywords)0x0020; // Integer 32 + internal const EventKeywords PoolerScope = (EventKeywords)0X0040; // Integer 64 + internal const EventKeywords StringPrintOut = (EventKeywords)0x0080; // Integer 128 + internal const EventKeywords PoolerTrace = (EventKeywords)0x0200; //Integer 512 + + public static EventKeywords GetAll() + { + return Trace | Scope | NotificationTrace | Pooling | Correlation | NotificationScope | PoolerScope | StringPrintOut; + } + } + + [NonEvent] + internal bool IsTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Trace); + + [NonEvent] + internal bool IsScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Scope); + + [NonEvent] + internal bool IsPoolerScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerScope); + + [NonEvent] + internal bool IsCorrelationEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Correlation); + + [NonEvent] + internal bool IsNotificationScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationScope); + + [NonEvent] + internal bool IsPoolingEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Pooling); + + [NonEvent] + internal bool IsNotificationTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationTrace); + + [NonEvent] + internal bool IsPoolerTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerTrace); + + + [Event(TraceEventId, Level = EventLevel.Informational, Channel = EventChannel.Debug, Keywords = Keywords.Trace)] + internal void Trace(string message) + { + WriteEvent(TraceEventId, message); + } + + [Event(EnterScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] + internal long ScopeEnter(string message) + { + StringBuilder MsgstrBldr = new StringBuilder(message); + long scopeId = 0; + if (Log.IsEnabled()) + { + scopeId = Interlocked.Increment(ref s_nextScopeId); + WriteEvent(EnterScopeId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); + } + return scopeId; + } + + [Event(ExitScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] + internal void ScopeLeave(long scopeId) + { + if (!Log.IsEnabled()) + { + return; + } + WriteEvent(ExitScopeId, scopeId); + } + + [Event(TraceBinId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] + internal void TraceBin(string message, byte[] whereabout, int length) + { + if (Log.IsEnabled(EventLevel.Informational, Keywords.Trace)) + { + WriteEvent(TraceBinId, message, whereabout, length); + } + + } + + [Event(CorrelationTraceId, Level = EventLevel.Informational, Keywords = Keywords.Correlation, Opcode = EventOpcode.Start)] + internal void CorrelationTrace(string message) + { + + WriteEvent(CorrelationTraceId, message); + } + + [Event(NotificationsScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.NotificationScope)] + internal long NotificationsScopeEnter(string message) + { + long scopeId = 0; + if (Log.IsEnabled()) + { + StringBuilder MsgstrBldr = new StringBuilder(message); + scopeId = Interlocked.Increment(ref s_nextNotificationScopeId); + WriteEvent(NotificationsScopeEnterId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); + } + return scopeId; + } + + [Event(PoolerScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.PoolerScope)] + internal long PoolerScopeEnter(string message) + { + long scopeId = 0; + if (Log.IsEnabled()) + { + + StringBuilder MsgstrBldr = new StringBuilder(message); + WriteEvent(PoolerScopeEnterId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); + } + return scopeId; + } + + [Event(NotificationsTraceId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] + internal void NotificationsTrace(string message) + { + WriteEvent(PoolerScopeEnterId, message); + } + + [Event(PoolerTraceId, Level = EventLevel.Informational, Keywords = Keywords.PoolerTrace)] + internal void PoolerTrace(string message) + { + WriteEvent(PoolerTraceId, message); + } + + [Event(PutStrId, Level = EventLevel.Informational, Keywords = Keywords.StringPrintOut)] + internal void PutStr(string message) + { + if (Log.IsEnabled(EventLevel.Informational, Keywords.StringPrintOut)) + { + WriteEvent(PutStrId, message); + + } + } + } +} diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs index 66950c104e..dfbebe5f0d 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs @@ -9,6 +9,7 @@ using Xunit; using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient.ManualTesting.Tests.EventSourceTest { public class EventSourceListenerGeneral : EventListener @@ -23,16 +24,18 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData) events = eventData.Payload.ToList(); } } + [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "Not Implemented")] public class SqlClientEventSourceTest { + [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp,"Not Implemented")] [Fact] public void TestSqlClientEventSourceName() { Assert.Equal("Microsoft.Data.SqlClient.EventSource", SqlClientEventSource.Log.Name); } - //The values are equivilant to Keywords value inside SqlClientEventSource + [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "Not Implemented")] [Theory] [InlineData(new int[] { 1, 2, 4, 8, 16 })] public async void TestEventKeywords(int[] values) From 7a747b4b76882c36205ceedb1e041495151e192a Mon Sep 17 00:00:00 2001 From: Javad Date: Thu, 30 Jan 2020 23:38:49 -0800 Subject: [PATCH 07/46] Update EventSourceTest.cs --- .../EventSource/EventSourceTest.cs | 49 ------------------- 1 file changed, 49 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs index dfbebe5f0d..3628f1cab0 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs @@ -48,55 +48,6 @@ public async void TestEventKeywords(int[] values) //Events should be disabled by default Assert.False(Log.IsEnabled()); - - //We try to Enable events. - //Since we have to have 2 arguments in EnableEvents Informational is selected arbitrary. - //If we do not wait for tasks to be completed Assert.True will run before other calls and will return false. - var task1 = Task.Run(() => - { - listener.EnableEvents(Log, EventLevel.Informational); - }); - await task1.ContinueWith((t) => - { - status = Log.IsEnabled(); - }); - Assert.True(status); - - //check if we are able to disable all the events - var task2 = Task.Run(() => - { - listener.DisableEvents(Log); - }); - await task2.ContinueWith((t) => - { - status = Log.IsEnabled(); - }); - Assert.False(status); - - //Check if we are able to enable specific Event keyword Trace - var task3 = Task.Run(() => - { - listener.EnableEvents(Log, listener.Level, listener.Keyword); - }); - await task3.ContinueWith((t) => - { - //(EventKeywords)1 is Trace which is defined in SqlClientEventSource Keywords class - status = Log.IsEnabled(EventLevel.Informational, SqlClientEventSource.Keywords.Trace); - }); - Assert.True(status); - - //Check if we are able to enable specific Event keyword. Scope - listener.Keyword = (EventKeywords)values[1]; - var task4 = Task.Run(() => - { - listener.EnableEvents(Log, listener.Level, listener.Keyword); - }); - await task4.ContinueWith((t) => - { - //(EventKeywords)1 is Trace which is defined in SqlClientEventSource Keywords class - status = Log.IsEnabled(EventLevel.Informational, SqlClientEventSource.Keywords.Scope); - }); - Assert.True(status); } } } From 5b73edb1c7cd51fd759fcf9adf66d2e0494a9d6b Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Fri, 31 Jan 2020 13:14:36 -0800 Subject: [PATCH 08/46] Adding if blocks --- src/Microsoft.Data.SqlClient.sln | 4 +- .../src/Microsoft.Data.SqlClient.csproj | 1 - .../Data/ProviderBase/DbConnectionFactory.cs | 21 +++++- .../Data/ProviderBase/DbConnectionInternal.cs | 3 +- .../Data/ProviderBase/DbConnectionPool.cs | 7 +- .../Data/ProviderBase/SqlConnectionHelper.cs | 8 ++- .../Data/SqlClient/SqlClientEventSource.cs | 3 + .../Data/SqlClient/SqlClientLogger.cs | 3 + .../Microsoft/Data/SqlClient/SqlCommand.cs | 43 ++++++++---- .../Microsoft/Data/SqlClient/SqlCommandSet.cs | 5 +- .../Microsoft/Data/SqlClient/SqlConnection.cs | 31 ++++++--- .../EventSource/EventSourceTest.cs | 69 +++++-------------- 12 files changed, 115 insertions(+), 83 deletions(-) diff --git a/src/Microsoft.Data.SqlClient.sln b/src/Microsoft.Data.SqlClient.sln index 41fd6c1986..81a76eea93 100644 --- a/src/Microsoft.Data.SqlClient.sln +++ b/src/Microsoft.Data.SqlClient.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 15 -VisualStudioVersion = 15.0.27004.2010 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Data.SqlClient", "Microsoft.Data.SqlClient\netfx\src\Microsoft.Data.SqlClient.csproj", "{407890AC-9876-4FEF-A6F1-F36A876BAADE}" EndProject diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj index f3f2f919aa..481308bd83 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj @@ -577,7 +577,6 @@ - True True diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index 7705eaf4cb..2659a01efd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -66,7 +66,12 @@ internal int ObjectID public void ClearAllPools() { - var scopeID = Log.ScopeEnter(" "); + long scopeID = 0; + if (Log.IsEnabled()) + { + scopeID = Log.ScopeEnter(""); + } + try { Dictionary connectionPoolGroups = _connectionPoolGroups; @@ -89,7 +94,12 @@ public void ClearPool(DbConnection connection) { ADP.CheckArgumentNull(connection, "connection"); - var scopeID = Log.ScopeEnter($" {GetObjectId(connection)}#"); + long scopeID = 0; + if (Log.IsEnabled()) + { + scopeID = Log.ScopeEnter($" {GetObjectId(connection)}#"); + } + try { DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); @@ -109,7 +119,12 @@ public void ClearPool(DbConnectionPoolKey key) Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, "key.ConnectionString"); - var scopeID = Log.ScopeEnter(" connectionString"); + long scopeID=0; + if (Log.IsEnabled()) + { + scopeID = Log.ScopeEnter(" connectionString"); + } + try { DbConnectionPoolGroup poolGroup; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index 14417a2d51..5ce6caf3b8 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -165,8 +165,7 @@ protected internal SysTx.Transaction EnlistedTransaction { if (Log.IsPoolerTraceEnabled()) { - int x = value.GetHashCode(); - Log.PoolerTrace($" {ObjectID}#, Transaction {x}#, Enlisting."); + Log.PoolerTrace($" {ObjectID}#, Transaction {value.GetHashCode()}#, Enlisting."); } TransactionOutcomeEnlist(value); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index 2a853d7ad1..007703e385 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -1737,8 +1737,11 @@ private void PoolCreateRequest(object state) // called by pooler to ensure pool requests are currently being satisfied - // creation mutex has not been obtained - - var scopeID = Log.PoolerScopeEnter($" {ObjectID}#"); + long scopeID = 0; + if (Log.IsEnabled()) + { + scopeID = Log.PoolerScopeEnter($" {ObjectID}#"); + } try { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs index 2e83d1a72e..7a553a05b6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs @@ -210,7 +210,13 @@ internal void AddWeakReference(object value, int tag) override protected DbCommand CreateDbCommand() { DbCommand command = null; - var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + long scopeID = 0; + if (Log.IsEnabled()) + { + scopeID = Log.ScopeEnter($" {ObjectID}#"); + } + try { DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index d7355c8315..b4156063dd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -72,6 +72,9 @@ public static EventKeywords GetAll() [NonEvent] internal bool IsPoolerTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerTrace); + [NonEvent] + internal bool IsAdvanceTraceOn() => Log.IsEnabled(EventLevel.LogAlways, EventKeywords.All); + [Event(TraceEventId, Level = EventLevel.Informational, Channel = EventChannel.Debug, Keywords = Keywords.Trace)] internal void Trace(string message) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs index 910a8bb00c..678ae209aa 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs @@ -34,6 +34,9 @@ public void LogError(string type, string method, string message) } } + /// + public bool IsLoggingEnabled => Log.IsEnabled(); + /// public bool LogAssert(bool value, string type, string method, string message) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index e6030ddb46..dea51616e3 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -372,11 +372,9 @@ internal override void BatchCompleted() internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 parameterValues) { - var metaDataLength = (null != metaData) ? metaData.Length : -1; - if (Log.IsTraceEnabled()) { - Log.Trace($" {_command.ObjectID}# metaData.Length={metaDataLength}."); + Log.Trace($" {_command.ObjectID}# metaData.Length={((null != metaData) ? metaData.Length : -1)}."); } if (null != metaData && Log.IsTraceEnabled()) @@ -582,11 +580,9 @@ private SqlCommand(SqlCommand from) : this() _activeConnection = value; // UNDONE: Designers need this setter. Should we block other scenarios? - var _activeConnectionObjectID = (null != value) ? value.ObjectID : -1; - if (Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, {_activeConnectionObjectID}#"); + Log.Trace($" {ObjectID}#, {((null != value) ? value.ObjectID : -1)}#"); } } } @@ -1035,7 +1031,10 @@ override public void Prepare() } SqlStatistics statistics = null; - var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter($" {ObjectID}#"); if (Log.IsCorrelationEnabled()) Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); @@ -1217,7 +1216,9 @@ internal void Unprepare() /// override public void Cancel() { - var scopeID = Log.ScopeEnter($"< sc.SqlCommand.Cancel | API > {ObjectID}#"); + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter($"< sc.SqlCommand.Cancel | API > {ObjectID}#"); if (Log.IsCorrelationEnabled()) Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); @@ -1382,7 +1383,10 @@ override public object ExecuteScalar() _pendingCancel = false; SqlStatistics statistics = null; - var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter($" {ObjectID}#"); if (Log.IsCorrelationEnabled()) Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); @@ -1452,7 +1456,10 @@ override public int ExecuteNonQuery() _pendingCancel = false; SqlStatistics statistics = null; - var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter($" {ObjectID}#"); if (Log.IsPoolerTraceEnabled()) Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); @@ -1492,7 +1499,11 @@ internal void ExecuteToPipe(SmiContext pipeContext) _pendingCancel = false; SqlStatistics statistics = null; - var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter($" {ObjectID}#"); + try { statistics = SqlStatistics.StartTimer(Statistics); @@ -2084,7 +2095,10 @@ public XmlReader ExecuteXmlReader() _pendingCancel = false; SqlStatistics statistics = null; - var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter($" {ObjectID}#"); if (Log.IsCorrelationEnabled()) Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); @@ -2421,7 +2435,10 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) new public SqlDataReader ExecuteReader() { SqlStatistics statistics = null; - var scopeID = Log.ScopeEnter($" {ObjectID}#"); + + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter($" {ObjectID}#"); if (Log.IsCorrelationEnabled()) Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index b7641d156c..8f770267ca 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -307,7 +307,10 @@ internal int ExecuteNonQuery() { SqlConnection.ExecutePermission.Demand(); - var scopeID = Log.ScopeEnter($" {ObjectID}#"); + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter($" {ObjectID}#"); + try { if (Connection.IsContextConnection) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index 7983c94625..0c2da41cfc 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -1103,7 +1103,10 @@ public SqlTransaction BeginTransaction(string transactionName) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { - var scopeID = Log.ScopeEnter($" {ObjectID}#, isolationLevel={(int)isolationLevel}"); + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter($" {ObjectID}#, isolationLevel={(int)isolationLevel}"); + try { @@ -1128,8 +1131,10 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam { WaitForPendingReconnection(); SqlStatistics statistics = null; - string xactName = ADP.IsEmpty(transactionName) ? "None" : transactionName; - var scopeID = Log.ScopeEnter($" {ObjectID}#, iso={(int)iso}, transactionName='{xactName}'"); + + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter($" {ObjectID}#, iso={(int)iso}, transactionName='{(ADP.IsEmpty(transactionName) ? "None" : transactionName)}'"); try { @@ -1263,7 +1268,9 @@ void CloseInnerConnection() /// override public void Close() { - var scopeID = Log.ScopeEnter($" {ObjectID}#"); + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter($" {ObjectID}#"); if (Log.IsCorrelationEnabled()) Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); @@ -1403,7 +1410,9 @@ public void EnlistDistributedTransaction(System.EnterpriseServices.ITransaction /// override public void Open() { - var scopeID = Log.ScopeEnter($" ObjectID: {ObjectID}, ActivityID {Log.Guid}"); + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter($" ObjectID: {ObjectID}, ActivityID {Log.Guid}"); if (Log.IsCorrelationEnabled()) Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); @@ -1680,7 +1689,9 @@ void CancelOpenAndWait() /// public override Task OpenAsync(CancellationToken cancellationToken) { - var scopeID = Log.PoolerScopeEnter($" {ObjectID}#"); + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.PoolerScopeEnter($" {ObjectID}#"); if (Log.IsCorrelationEnabled()) Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); @@ -2474,7 +2485,9 @@ private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, s /// public static void ChangePassword(string connectionString, string newPassword) { - var scopeID = Log.ScopeEnter(""); + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter(""); if (Log.IsCorrelationEnabled()) Log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); @@ -2524,7 +2537,9 @@ public static void ChangePassword(string connectionString, string newPassword) /// public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { - var scopeID = Log.ScopeEnter(""); + long scopeID = 0; + if (Log.IsEnabled()) + scopeID = Log.ScopeEnter(""); if (Log.IsCorrelationEnabled()) Log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs index dfbebe5f0d..c0a8e91475 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs @@ -2,8 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; using System.Collections.Generic; using System.Diagnostics.Tracing; +using System.IO; using System.Linq; using System.Threading.Tasks; using Xunit; @@ -14,89 +16,56 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests.EventSourceTest { public class EventSourceListenerGeneral : EventListener { + TextWriter Out = Console.Out; public EventLevel Level { get; set; } public EventKeywords Keyword { get; set; } - public List events = new List(); + List events = new List(); protected override void OnEventWritten(EventWrittenEventArgs eventData) { - events = eventData.Payload.ToList(); + + events= eventData.Payload != null ? eventData.Payload.Select(o => o.ToString()).ToList() : null; } } - [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "Not Implemented")] public class SqlClientEventSourceTest { - [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp,"Not Implemented")] + [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "Not Implemented")] [Fact] public void TestSqlClientEventSourceName() { Assert.Equal("Microsoft.Data.SqlClient.EventSource", SqlClientEventSource.Log.Name); } - [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "Not Implemented")] [Theory] [InlineData(new int[] { 1, 2, 4, 8, 16 })] - public async void TestEventKeywords(int[] values) + public void TestEventKeywords(int[] values) { using (EventSourceListenerGeneral listener = new EventSourceListenerGeneral()) { listener.Keyword = (EventKeywords)values[0]; listener.Level = EventLevel.Informational; - bool status = false; + //Check if Log is disabled by default + Assert.True(!Log.IsEnabled()); - //Events should be disabled by default - Assert.False(Log.IsEnabled()); + listener.EnableEvents(Log, EventLevel.Informational); - //We try to Enable events. - //Since we have to have 2 arguments in EnableEvents Informational is selected arbitrary. - //If we do not wait for tasks to be completed Assert.True will run before other calls and will return false. - var task1 = Task.Run(() => + //Check if Enabling Log is able. + var task = Task.Run(() => { listener.EnableEvents(Log, EventLevel.Informational); }); - await task1.ContinueWith((t) => - { - status = Log.IsEnabled(); - }); - Assert.True(status); - - //check if we are able to disable all the events - var task2 = Task.Run(() => + task.ContinueWith((t) => { - listener.DisableEvents(Log); + Assert.True(Log.IsEnabled()); }); - await task2.ContinueWith((t) => - { - status = Log.IsEnabled(); - }); - Assert.False(status); - //Check if we are able to enable specific Event keyword Trace - var task3 = Task.Run(() => - { - listener.EnableEvents(Log, listener.Level, listener.Keyword); - }); - await task3.ContinueWith((t) => - { - //(EventKeywords)1 is Trace which is defined in SqlClientEventSource Keywords class - status = Log.IsEnabled(EventLevel.Informational, SqlClientEventSource.Keywords.Trace); - }); - Assert.True(status); + //Check if enabling Log for Eventkeyword Trace returns true. + listener.EnableEvents(Log, EventLevel.Informational, SqlClientEventSource.Keywords.NotificationTrace); - //Check if we are able to enable specific Event keyword. Scope - listener.Keyword = (EventKeywords)values[1]; - var task4 = Task.Run(() => - { - listener.EnableEvents(Log, listener.Level, listener.Keyword); - }); - await task4.ContinueWith((t) => - { - //(EventKeywords)1 is Trace which is defined in SqlClientEventSource Keywords class - status = Log.IsEnabled(EventLevel.Informational, SqlClientEventSource.Keywords.Scope); - }); - Assert.True(status); + Assert.True(Log.IsEnabled()); + } } } From 5198d2194f9451af4c7a605ec0507061d3fbdf25 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Fri, 31 Jan 2020 14:41:14 -0800 Subject: [PATCH 09/46] EventSource --- .../Data/SqlClient/SqlClientEventSource.cs | 1 - .../EventSource/EventSourceTest.cs | 72 ------------------- 2 files changed, 73 deletions(-) delete mode 100644 src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 2715c8f83e..11cf90ea5e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -7,7 +7,6 @@ using System.Threading; using System.Runtime.CompilerServices; -[assembly: InternalsVisibleTo("Microsoft.Data.SqlClient.ManualTesting.Tests")] namespace Microsoft.Data.SqlClient { /// diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs deleted file mode 100644 index 3c9efa63bb..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Diagnostics.Tracing; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Xunit; -using static Microsoft.Data.SqlClient.SqlClientEventSource; - - -namespace Microsoft.Data.SqlClient.ManualTesting.Tests.EventSourceTest -{ - public class EventSourceListenerGeneral : EventListener - { - TextWriter Out = Console.Out; - public EventLevel Level { get; set; } - public EventKeywords Keyword { get; set; } - - List events = new List(); - - protected override void OnEventWritten(EventWrittenEventArgs eventData) - { - - events= eventData.Payload != null ? eventData.Payload.Select(o => o.ToString()).ToList() : null; - } - } - - public class SqlClientEventSourceTest - { - [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "Not Implemented")] - [Fact] - public void TestSqlClientEventSourceName() - { - Assert.Equal("Microsoft.Data.SqlClient.EventSource", SqlClientEventSource.Log.Name); - } - - [Theory] - [InlineData(new int[] { 1, 2, 4, 8, 16 })] - public void TestEventKeywords(int[] values) - { - using (EventSourceListenerGeneral listener = new EventSourceListenerGeneral()) - { - listener.Keyword = (EventKeywords)values[0]; - listener.Level = EventLevel.Informational; - //Check if Log is disabled by default - Assert.True(!Log.IsEnabled()); - - listener.EnableEvents(Log, EventLevel.Informational); - - //Check if Enabling Log is able. - var task = Task.Run(() => - { - listener.EnableEvents(Log, EventLevel.Informational); - }); - task.ContinueWith((t) => - { - Assert.True(Log.IsEnabled()); - }); - - //Check if enabling Log for Eventkeyword Trace returns true. - listener.EnableEvents(Log, EventLevel.Informational, SqlClientEventSourceKeywords.NotificationTrace); - - Assert.True(Log.IsEnabled()); - - } - } - } -} From 9fb8af859aaeb7eb18f63801f6f5c62545decd09 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Sun, 2 Feb 2020 23:08:38 -0800 Subject: [PATCH 10/46] Documentation --- .../SqlClientEventSourceKeywords.xml | 46 +++++++++++++++++ .../Data/SqlClient/SqlClientEventSource.cs | 50 ++++++++++++------- ....Data.SqlClient.ManualTesting.Tests.csproj | 1 - 3 files changed, 77 insertions(+), 20 deletions(-) create mode 100644 doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSourceKeywords.xml diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSourceKeywords.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSourceKeywords.xml new file mode 100644 index 0000000000..2536e2a62c --- /dev/null +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSourceKeywords.xml @@ -0,0 +1,46 @@ + + + + + Specifies a value for SqlClientEventSource. . + + + + Logs all Trace events. + 1 + + + To be added. + 2 + + + To be added. + 4 + + + To be added. + 8 + + + To be added. + 16 + + + To be added. + 32 + + + To be added. + 64 + + + To be added. + 128 + + + To be added. + 512 + + Returns All values of SqlClientEventSourceKeywords. + + diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 11cf90ea5e..28d1668064 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -9,25 +9,37 @@ namespace Microsoft.Data.SqlClient { - /// - /// - /// + /// public class SqlClientEventSourceKeywords { - internal const EventKeywords Trace = (EventKeywords)0x0001; // Integer 1 - internal const EventKeywords Scope = (EventKeywords)0x0002; // Integer 2 - internal const EventKeywords NotificationTrace = (EventKeywords)0x0004; // Integer 4 - internal const EventKeywords Pooling = (EventKeywords)0x0008; // Integer 8 - internal const EventKeywords Correlation = (EventKeywords)0x0010; // Integer 16 - internal const EventKeywords NotificationScope = (EventKeywords)0x0020; // Integer 32 - internal const EventKeywords PoolerScope = (EventKeywords)0X0040; // Integer 64 - internal const EventKeywords StringPrintOut = (EventKeywords)0x0080; // Integer 128 - internal const EventKeywords PoolerTrace = (EventKeywords)0x0200; //Integer 512 - - /// - /// - /// - /// + /// + internal const EventKeywords Trace = (EventKeywords)1; + + /// + internal const EventKeywords Scope = (EventKeywords)2; + + /// + internal const EventKeywords NotificationTrace = (EventKeywords)4; + + /// + internal const EventKeywords Pooling = (EventKeywords)8; + + /// + internal const EventKeywords Correlation = (EventKeywords)16; + + /// + internal const EventKeywords NotificationScope = (EventKeywords)32; + + /// + internal const EventKeywords PoolerScope = (EventKeywords)64; + + /// + internal const EventKeywords StringPrintOut = (EventKeywords)128; + + /// + internal const EventKeywords PoolerTrace = (EventKeywords)512; + + /// public static EventKeywords GetAll() { return Trace | Scope | NotificationTrace | Pooling | Correlation | NotificationScope | PoolerScope | StringPrintOut; @@ -109,7 +121,7 @@ internal void ScopeLeave(long scopeId) { WriteEvent(ExitScopeId, scopeId); } - + } [Event(TraceBinId, Level = EventLevel.Informational, Keywords = SqlClientEventSourceKeywords.Trace)] @@ -123,7 +135,7 @@ internal void TraceBin(string message, byte[] whereabout, int length) [Event(CorrelationTraceId, Level = EventLevel.Informational, Keywords = SqlClientEventSourceKeywords.Correlation, Opcode = EventOpcode.Start)] internal void CorrelationTrace(string message) - { + { WriteEvent(CorrelationTraceId, message); } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj index eb483ed228..d48c72e562 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj @@ -56,7 +56,6 @@ - From d373dd1fffe859a33a658c0b8e891771278e0bdb Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Mon, 3 Feb 2020 17:07:25 -0800 Subject: [PATCH 11/46] Adding Tests and documentation --- .../SqlClientEventSource_EventLogger.cs | 57 ++++++++ .../SqlClientEventSource.xml | 53 +++++++ .../Data/Common/DBConnectionString.cs | 4 +- .../netfx/src/Microsoft/Data/DataException.cs | 2 +- .../Data/ProviderBase/DbConnectionFactory.cs | 6 +- .../SqlClient/Server/SmiEventSink_Default.cs | 2 +- .../Data/SqlClient/SqlClientEventSource.cs | 131 ++++++++---------- .../Data/SqlClient/SqlDataReaderSmi.cs | 22 +-- .../Data/SqlClient/SqlInternalConnection.cs | 26 ++-- .../SqlClient/SqlInternalConnectionSmi.cs | 38 ++--- .../Data/SqlClient/SqlTransaction.cs | 4 +- .../Data/SqlClient/TdsParserSessionPool.cs | 14 +- .../Microsoft.Data.SqlClient.Tests.csproj | 1 + .../SqlClientEventSourceTest.cs | 58 ++++++++ 14 files changed, 283 insertions(+), 135 deletions(-) create mode 100644 doc/samples/SqlClientEventSource_EventLogger.cs create mode 100644 doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml create mode 100644 src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlClientEventSourceTest.cs diff --git a/doc/samples/SqlClientEventSource_EventLogger.cs b/doc/samples/SqlClientEventSource_EventLogger.cs new file mode 100644 index 0000000000..ca8bbcd289 --- /dev/null +++ b/doc/samples/SqlClientEventSource_EventLogger.cs @@ -0,0 +1,57 @@ +using System; +using System.Data; +using System.Diagnostics.Tracing; +using Microsoft.Data.SqlClient; + +// +class Program +{ + static void Main() + { + static void Main(string[] args) + { + using (var listener = new SampleEventListener()) + { + //This Enables events for Keywords.Tracing + //We also can select EventKeywords.All to get all possible available events. + listener.EnableEvents(SqlClientEventSource.Log, EventLevel.Informational, SqlClientEventSource.Keywords.Trace); + using (SqlConnection connection = new SqlConnection("Data Source=tcp:localhost;Database=Northwind;Integrated Security=SSIP;")) + { + connection.Open(); + using (SqlCommand command = new SqlCommand("SELECT * From [Customers]", connection)) + { + command.ExecuteNonQuery(); + } + } + } + } + } + +} + +public class SampleEventListener : EventListenr +{ + static TextWriter Out = Console.Out; + + /// + /// We override this method to get a callback on every event. + /// + /// + protected override void OnEventWritten(EventWrittenEventArgs eventData) + { + // report all event information + Out.Write(" Event {0} ", eventData.EventName); + + + // Events can have formatting strings 'the Message property on the 'Event' attribute. + // If the event has a formatted message, print that, otherwise print out argument values. + if (eventData.Message != null) + Out.WriteLine(eventData.Message, eventData.Payload.ToArray()); + else + { + string[] sargs = eventData.Payload != null ? eventData.Payload.Select(o => o.ToString()).ToArray() : null; + Out.WriteLine("({0}).", sargs != null ? string.Join(", ", sargs) : ""); + } + } +} +// diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml new file mode 100644 index 0000000000..8d536f1ab4 --- /dev/null +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml @@ -0,0 +1,53 @@ + + + + + This class implements parent class. + + + + this is the singleton instantiation of the SqlClientEventSource class. + + + + This class defines the nested class of Keywords for . + + + Representing possible group of events for Tracing. + + 1 + + Reperesnting possible group of events for Scope. + 2 + + + Representing possible froup of events for Notofocation Trace. + 4 + + + Representing possible group of events for Pooling. + 8 + + + Representing possible group of events for Correlation. + 16 + + + Representing possible group of events for NotificationScope + 32 + + + Representing possible group of events for PoolerScope. + 64 + + + Representing possible group of events for PoolerTrace. + 128 + + + + + + + + diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs index e3f37d5e63..968c5a71fa 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs @@ -470,7 +470,7 @@ static private string[] NoDuplicateUnion(string[] a, string[] b) private static string[] ParseRestrictions(string restrictions, Hashtable synonyms) { #if DEBUG - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" Restrictions='{restrictions}'"); } @@ -489,7 +489,7 @@ private static string[] ParseRestrictions(string restrictions, Hashtable synonym if (!ADP.IsEmpty(keyname)) { #if DEBUG - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" KeyName='{keyname}'"); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs index 6f7b13fb6c..c9a2e45ccd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -28,7 +28,7 @@ static private void TraceException( string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e && Log.IsTraceEnabled()) + if (null != e && Log.IsAdvanceTraceOn()) { Log.Trace(e.Message); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index 2659a01efd..9f003f5bf7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -572,7 +572,7 @@ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPo private void PruneConnectionPoolGroups(object state) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { // when debugging this method, expect multiple threads at the same time Log.Trace($" {ObjectID}#"); @@ -597,7 +597,7 @@ private void PruneConnectionPoolGroups(object state) { _poolsToRelease.Remove(pool); - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" { ObjectID}#, ReleasePool={pool.ObjectID}#"); } @@ -627,7 +627,7 @@ private void PruneConnectionPoolGroups(object state) { _poolGroupsToRelease.Remove(poolGroup); - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}#, ReleasePoolGroup={poolGroup.ObjectID}#"); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs index 6746f9b67f..3756721a4f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs @@ -269,7 +269,7 @@ internal override void MessagePosted(int number, byte state, byte errorClass, st { if (null == _parent) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {0}#, number={number} state={state} errorClass={errorClass} server='{server ?? ""}' message='{message ?? ""}' procedure='{procedure ?? ""}' linenumber={lineNumber}."); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 28d1668064..6fab3db478 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -9,47 +9,12 @@ namespace Microsoft.Data.SqlClient { - /// - public class SqlClientEventSourceKeywords - { - /// - internal const EventKeywords Trace = (EventKeywords)1; - - /// - internal const EventKeywords Scope = (EventKeywords)2; - - /// - internal const EventKeywords NotificationTrace = (EventKeywords)4; - - /// - internal const EventKeywords Pooling = (EventKeywords)8; - - /// - internal const EventKeywords Correlation = (EventKeywords)16; - - /// - internal const EventKeywords NotificationScope = (EventKeywords)32; - - /// - internal const EventKeywords PoolerScope = (EventKeywords)64; - - /// - internal const EventKeywords StringPrintOut = (EventKeywords)128; - - /// - internal const EventKeywords PoolerTrace = (EventKeywords)512; - - /// - public static EventKeywords GetAll() - { - return Trace | Scope | NotificationTrace | Pooling | Correlation | NotificationScope | PoolerScope | StringPrintOut; - } - } - + /// [EventSource(Name = "Microsoft.Data.SqlClient.EventSource")] - internal class SqlClientEventSource : EventSource + public class SqlClientEventSource : EventSource { - internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); + /// + public static readonly SqlClientEventSource Log = new SqlClientEventSource(); private static long s_nextScopeId = 0; private static long s_nextNotificationScopeId = 0; @@ -64,82 +29,111 @@ internal class SqlClientEventSource : EventSource private const int PoolerTraceId = 9; private const int PutStrId = 10; - //Any Prropery added to this class should be a power of 2. + /// + public class Keywords + { + /// + public const EventKeywords Trace = (EventKeywords)0x0001; + + /// + public const EventKeywords Scope = (EventKeywords)0x0002; + + /// + public const EventKeywords NotificationTrace = (EventKeywords)4; + + /// + public const EventKeywords Pooling = (EventKeywords)8; + + /// + public const EventKeywords Correlation = (EventKeywords)16; + + /// + public const EventKeywords NotificationScope = (EventKeywords)32; + + /// + public const EventKeywords PoolerScope = (EventKeywords)64; + + /// + public const EventKeywords PoolerTrace = (EventKeywords)128; + + /// + public static EventKeywords GetAll() + { + return Trace | Scope | NotificationTrace | Pooling | Correlation | NotificationScope | PoolerScope; + } + } [NonEvent] - internal bool IsTraceEnabled() => Log.IsEnabled(EventLevel.Informational, SqlClientEventSourceKeywords.Trace); + internal bool IsTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Trace); [NonEvent] - internal bool IsScopeEnabled() => Log.IsEnabled(EventLevel.Informational, SqlClientEventSourceKeywords.Scope); + internal bool IsScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Scope); [NonEvent] - internal bool IsPoolerScopeEnabled() => Log.IsEnabled(EventLevel.Informational, SqlClientEventSourceKeywords.PoolerScope); + internal bool IsPoolerScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerScope); [NonEvent] - internal bool IsCorrelationEnabled() => Log.IsEnabled(EventLevel.Informational, SqlClientEventSourceKeywords.Correlation); + internal bool IsCorrelationEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Correlation); [NonEvent] - internal bool IsNotificationScopeEnabled() => Log.IsEnabled(EventLevel.Informational, SqlClientEventSourceKeywords.NotificationScope); + internal bool IsNotificationScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationScope); [NonEvent] - internal bool IsPoolingEnabled() => Log.IsEnabled(EventLevel.Informational, SqlClientEventSourceKeywords.Pooling); + internal bool IsPoolingEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Pooling); [NonEvent] - internal bool IsNotificationTraceEnabled() => Log.IsEnabled(EventLevel.Informational, SqlClientEventSourceKeywords.NotificationTrace); + internal bool IsNotificationTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationTrace); [NonEvent] - internal bool IsPoolerTraceEnabled() => Log.IsEnabled(EventLevel.Informational, SqlClientEventSourceKeywords.PoolerTrace); + internal bool IsPoolerTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerTrace); [NonEvent] internal bool IsAdvanceTraceOn() => Log.IsEnabled(EventLevel.LogAlways, EventKeywords.All); - - [Event(TraceEventId, Level = EventLevel.Informational, Channel = EventChannel.Debug, Keywords = SqlClientEventSourceKeywords.Trace)] + [Event(TraceEventId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] internal void Trace(string message) { WriteEvent(TraceEventId, message); } - [Event(EnterScopeId, Level = EventLevel.Verbose, Keywords = SqlClientEventSourceKeywords.Scope)] + [Event(EnterScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] internal long ScopeEnter(string message) { - StringBuilder MsgstrBldr = new StringBuilder(message); long scopeId = 0; - if (Log.IsEnabled()) { + StringBuilder MsgstrBldr = new StringBuilder(message); scopeId = Interlocked.Increment(ref s_nextScopeId); WriteEvent(EnterScopeId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); } return scopeId; } - [Event(ExitScopeId, Level = EventLevel.Verbose, Keywords = SqlClientEventSourceKeywords.Scope)] + [Event(ExitScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] internal void ScopeLeave(long scopeId) { - if (!Log.IsEnabled()) + if (Log.IsEnabled()) { WriteEvent(ExitScopeId, scopeId); } - } - [Event(TraceBinId, Level = EventLevel.Informational, Keywords = SqlClientEventSourceKeywords.Trace)] + [Event(TraceBinId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] internal void TraceBin(string message, byte[] whereabout, int length) { - if (Log.IsEnabled(EventLevel.Informational, SqlClientEventSourceKeywords.Trace)) + if (Log.IsEnabled(EventLevel.Informational, Keywords.Trace)) { WriteEvent(TraceBinId, message, whereabout, length); } } - [Event(CorrelationTraceId, Level = EventLevel.Informational, Keywords = SqlClientEventSourceKeywords.Correlation, Opcode = EventOpcode.Start)] + [Event(CorrelationTraceId, Level = EventLevel.Informational, Keywords = Keywords.Correlation, Opcode = EventOpcode.Start)] internal void CorrelationTrace(string message) { WriteEvent(CorrelationTraceId, message); } - [Event(NotificationsScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = SqlClientEventSourceKeywords.NotificationScope)] + [Event(NotificationsScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.NotificationScope)] internal long NotificationsScopeEnter(string message) { long scopeId = 0; @@ -152,7 +146,7 @@ internal long NotificationsScopeEnter(string message) return scopeId; } - [Event(PoolerScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = SqlClientEventSourceKeywords.PoolerScope)] + [Event(PoolerScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.PoolerScope)] internal long PoolerScopeEnter(string message) { long scopeId = 0; @@ -164,25 +158,16 @@ internal long PoolerScopeEnter(string message) return scopeId; } - [Event(NotificationsTraceId, Level = EventLevel.Informational, Keywords = SqlClientEventSourceKeywords.Trace)] + [Event(NotificationsTraceId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] internal void NotificationsTrace(string message) { - WriteEvent(PoolerScopeEnterId, message); + WriteEvent(NotificationsTraceId, message); } - [Event(PoolerTraceId, Level = EventLevel.Informational, Keywords = SqlClientEventSourceKeywords.PoolerTrace)] + [Event(PoolerTraceId, Level = EventLevel.Informational, Keywords = Keywords.PoolerTrace)] internal void PoolerTrace(string message) { WriteEvent(PoolerTraceId, message); } - - [Event(PutStrId, Level = EventLevel.Informational, Keywords = SqlClientEventSourceKeywords.StringPrintOut)] - internal void PutStr(string message) - { - if (Log.IsEnabled(EventLevel.Informational, SqlClientEventSourceKeywords.StringPrintOut)) - { - WriteEvent(PutStrId, message); - } - } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs index a87005a411..d9822a292d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs @@ -439,7 +439,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) { long scopeID = 0; - if (Log.IsEnabled()) + if (Log.IsAdvanceTraceOn()) scopeID = Log.ScopeEnter($" {ObjectID}#"); try { @@ -473,7 +473,8 @@ internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) } finally { - Log.ScopeLeave(scopeID); + if (Log.IsAdvanceTraceOn()) + Log.ScopeLeave(scopeID); } } @@ -494,7 +495,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) internal unsafe bool InternalRead(bool ignoreNonFatalErrors) { long scopeID = 0; - if (Log.IsEnabled()) + if (Log.IsAdvanceTraceOn()) scopeID = Log.ScopeEnter($" {ObjectID}#"); try @@ -535,7 +536,8 @@ internal unsafe bool InternalRead(bool ignoreNonFatalErrors) } finally { - Log.ScopeLeave(scopeID); + if (Log.IsAdvanceTraceOn()) + Log.ScopeLeave(scopeID); } } @@ -1327,7 +1329,7 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs { var mdLength = (null != md) ? md.Length : -1; - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {reader.ObjectID}#, md.Length={mdLength} nextEventIsRow={nextEventIsRow}."); @@ -1346,7 +1348,7 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs // Obsolete V2- method internal override void RowAvailable(ITypedGetters row) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {reader.ObjectID}# (v2)."); } @@ -1355,7 +1357,7 @@ internal override void RowAvailable(ITypedGetters row) internal override void RowAvailable(ITypedGettersV3 row) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {reader.ObjectID}# (ITypedGettersV3)."); } @@ -1364,7 +1366,7 @@ internal override void RowAvailable(ITypedGettersV3 row) internal override void RowAvailable(SmiTypedGetterSetter rowData) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {reader.ObjectID}# (SmiTypedGetterSetter)."); } @@ -1373,7 +1375,7 @@ internal override void RowAvailable(SmiTypedGetterSetter rowData) internal override void StatementCompleted(int recordsAffected) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {reader.ObjectID}# recordsAffected= {recordsAffected}."); } @@ -1387,7 +1389,7 @@ internal override void StatementCompleted(int recordsAffected) internal override void BatchCompleted() { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {reader.ObjectID}#."); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index 24b7f3ecd7..72bc1698b7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -315,7 +315,7 @@ override protected DbReferenceCollection CreateReferenceCollection() override protected void Deactivate() { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) Log.Trace($" {ObjectID}# deactivating"); TdsParser bestEffortCleanupTarget = null; @@ -440,14 +440,14 @@ private void EnlistNonNull(SysTx.Transaction tx) { Debug.Assert(null != tx, "null transaction?"); - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) Log.Trace($" {ObjectID}#, transaction {tx.GetHashCode()}#."); bool hasDelegatedTransaction = false; if (IsYukonOrNewer) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) Log.Trace($" {ObjectID}#, attempting to delegate"); // Promotable transactions are only supported on Yukon @@ -517,16 +517,8 @@ private void EnlistNonNull(SysTx.Transaction tx) this.DelegatedTransaction = delegatedTransaction; - long transactionId = SqlInternalTransaction.NullTransactionId; - int transactionObjectID = 0; - if (null != CurrentTransaction) - { - transactionId = CurrentTransaction.TransactionId; - transactionObjectID = CurrentTransaction.ObjectID; - } - - if (Log.IsTraceEnabled()) - Log.Trace($" {ObjectID}#, delegated to transaction {transactionObjectID}# with transactionId=0x{transactionId}"); + if (Log.IsAdvanceTraceOn()) + Log.Trace($" {ObjectID}#, delegated to transaction {(null != CurrentTransaction? CurrentTransaction.ObjectID:0)}# with transactionId=0x{(null != CurrentTransaction? CurrentTransaction.TransactionId:SqlInternalTransaction.NullTransactionId)}"); } } catch (SqlException e) @@ -559,7 +551,7 @@ private void EnlistNonNull(SysTx.Transaction tx) if (!hasDelegatedTransaction) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) Log.Trace($" {ObjectID}#, delegation not possible, enlisting."); byte[] cookie = null; @@ -601,7 +593,7 @@ private void EnlistNonNull(SysTx.Transaction tx) transactionObjectID = CurrentTransaction.ObjectID; } - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) Log.Trace($" {ObjectID}#, enlisted with transaction {transactionObjectID}# with transactionId=0x{transactionId}"); } @@ -626,7 +618,7 @@ private void EnlistNonNull(SysTx.Transaction tx) internal void EnlistNull() { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) Log.Trace($" {ObjectID}#, unenlisting."); // We were in a transaction, but now we are not - so send @@ -646,7 +638,7 @@ internal void EnlistNull() _isEnlistedInTransaction = false; EnlistedTransaction = null; // Tell the base class about our enlistment - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) Log.Trace($" {ObjectID}#, unenlisted."); // The EnlistTransaction above will return an TransactionEnded event, diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs index 9c59f4a2cf..884c58fb93 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs @@ -67,7 +67,7 @@ internal EventSink(SqlInternalConnectionSmi connection) internal override void DefaultDatabaseChanged(string databaseName) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {_connection.ObjectID}#, databaseName='{databaseName}'."); } @@ -76,7 +76,7 @@ internal override void DefaultDatabaseChanged(string databaseName) internal override void TransactionCommitted(long transactionId) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); } @@ -85,7 +85,7 @@ internal override void TransactionCommitted(long transactionId) internal override void TransactionDefected(long transactionId) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); } @@ -94,7 +94,7 @@ internal override void TransactionDefected(long transactionId) internal override void TransactionEnlisted(long transactionId) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); } @@ -103,7 +103,7 @@ internal override void TransactionEnlisted(long transactionId) internal override void TransactionEnded(long transactionId) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); } @@ -112,7 +112,7 @@ internal override void TransactionEnded(long transactionId) internal override void TransactionRolledBack(long transactionId) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); } @@ -123,7 +123,7 @@ internal override void TransactionRolledBack(long transactionId) internal override void TransactionStarted(long transactionId) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); } @@ -143,7 +143,7 @@ internal SqlInternalConnectionSmi(SqlConnectionString connectionOptions, SmiCont _smiEventSink = new EventSink(this); - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}#, constructed new SMI internal connection"); } @@ -297,7 +297,7 @@ internal void AutomaticEnlistment() SysTx.Transaction contextTransaction = _smiContext.ContextTransaction; // returns the transaction that was handed to SysTx that wraps the ContextTransactionId. long contextTransactionId = _smiContext.ContextTransactionId; - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}#, contextTransactionId=0x{contextTransactionId}, contextTransaction={((null != contextTransaction) ? contextTransaction.GetHashCode() : 0)}#, currentSystemTransaction={((null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0)}#."); } @@ -309,7 +309,7 @@ internal void AutomaticEnlistment() throw SQL.NestedTransactionScopesNotSupported(); // can't use TransactionScope(RequiresNew) inside a Sql Transaction. } - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}#, using context transaction with transactionId=0x{contextTransactionId}"); } @@ -320,14 +320,14 @@ internal void AutomaticEnlistment() { _currentTransaction = null; // there really isn't a transaction. - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}#, no transaction."); } } else { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}#, using current System.Transaction."); } @@ -343,7 +343,7 @@ override protected void ChangeDatabaseInternal(string database) override protected void InternalDeactivate() { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}#, Deactivating."); } @@ -376,7 +376,7 @@ override internal void DelegatedTransactionEnded() { base.DelegatedTransactionEnded(); - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}#, cleaning up after Delegated Transaction Completion"); } @@ -386,7 +386,7 @@ override internal void DelegatedTransactionEnded() override internal void DisconnectTransaction(SqlInternalTransaction internalTransaction) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}#, Disconnecting Transaction {internalTransaction.ObjectID}#."); } @@ -415,7 +415,7 @@ override internal void ExecuteTransaction( { var transactionNameValue = (null != transactionName) ? transactionName : "null"; - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}#, transactionRequest={transactionRequest.ToString()}, " + $"transactionName='{transactionNameValue}', isolationLevel={iso.ToString()}, internalTransaction=#{((null != internalTransaction) ? internalTransaction.ObjectID : 0)} transactionId=0x{((null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId)}."); @@ -474,7 +474,7 @@ override protected byte[] GetDTCAddress() _smiEventSink.ProcessMessagesAndThrow(); - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { if (null != whereAbouts) { @@ -508,7 +508,7 @@ private void OnOutOfScope(object s, EventArgs e) // Called whenever the context goes out of scope, we need to make // sure that we close the connection, or the next person that uses // the context may appear to have the connection in use. - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}# context is out of scope"); } @@ -539,7 +539,7 @@ private void OnOutOfScope(object s, EventArgs e) override protected void PropagateTransactionCookie(byte[] transactionCookie) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { if (null != transactionCookie) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs index 77945cbf37..e9172bbced 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -272,7 +272,7 @@ override public void Rollback() { if (IsYukonPartialZombie) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { // Put something in the trace in case a customer has an issue Log.Trace($" {ObjectID}# partial zombie no rollback required"); @@ -490,7 +490,7 @@ internal void Zombie() if (null != internalConnection && internalConnection.IsYukonOrNewer && !_isFromAPI) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}# yukon deferred zombie"); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index 6d5eaea585..06f4cf5ccd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -38,7 +38,7 @@ internal TdsParserSessionPool(TdsParser parser) _freeStateObjects = new TdsParserStateObject[MaxInactiveCount]; _freeStateObjectCount = 0; - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}# created session pool for parser {parser.ObjectID}"); } @@ -89,7 +89,7 @@ internal void Deactivate() { // TODO: consider adding a performance counter for the number of sessions we reclaim - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}# reclaiming session {session.ObjectID}"); } @@ -127,7 +127,7 @@ internal void BestEffortCleanup() internal void Dispose() { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}# disposing cachedCount={_cachedCount}"); } @@ -191,7 +191,7 @@ internal TdsParserStateObject GetSession(object owner) // No free objects, create a new one session = _parser.CreateSession(); - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}# adding session {session.ObjectID} to pool"); } @@ -203,7 +203,7 @@ internal TdsParserStateObject GetSession(object owner) session.Activate(owner); } - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}# using session {session.ObjectID}"); } @@ -229,7 +229,7 @@ internal void PutSession(TdsParserStateObject session) else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount)) { // Session is good to re-use and our cache has space - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}# keeping session {session.ObjectID} cachedCount={_cachedCount}"); } @@ -242,7 +242,7 @@ internal void PutSession(TdsParserStateObject session) else { // Either the session is bad, or we have no cache space - so dispose the session and remove it - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) { Log.Trace($" {ObjectID}# disposing session {session.ObjectID} cachedCount={_cachedCount}"); } diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj index 5800c4f891..65f6484269 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj @@ -21,6 +21,7 @@ + diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlClientEventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlClientEventSourceTest.cs new file mode 100644 index 0000000000..0837aa16c8 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlClientEventSourceTest.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.Tracing; +using System.Linq; +using System.IO; +using System.Threading.Tasks; +using Xunit; + +namespace Microsoft.Data.SqlClient.Tests +{ + public class SqlClientEventSourceTest + { + [Fact] + public void IsTraceEnabled() + { + using (var listener = new SampleEventListener()) + { + listener.EnableEvents(SqlClientEventSource.Log, EventLevel.Informational, SqlClientEventSource.Keywords.Trace); + using (SqlConnection connection = new SqlConnection("Data Source=tcp:localhost;Database=Northwind;Integrated Security=true;")) + { + connection.Open(); + using (SqlCommand command = new SqlCommand("SELECT * From [Customers]", connection)) + { + command.ExecuteNonQuery(); + } + } + //Check if all the events are from Trace + foreach (var item in listener.eventsNames) + { + Assert.Contains("Trace", item); + } + + //Check if we can disable the events + listener.DisableEvents(SqlClientEventSource.Log); + Assert.False(SqlClientEventSource.Log.IsEnabled()); + + //Check if we are able to enable events again + listener.EnableEvents(SqlClientEventSource.Log, EventLevel.Informational); + Assert.True(SqlClientEventSource.Log.IsEnabled()); + } + } + } + + public class SampleEventListener : EventListener + { + public List eventsNames = new List(); + protected override void OnEventWritten(EventWrittenEventArgs eventData) + { + if (eventData.Message != null) + + eventsNames.Add(eventData.EventName); + else + { + eventsNames.Add(eventData.EventName); + } + } + } +} From c3a27a438a9a8d755bd94106439d1b432e8fbe83 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 4 Feb 2020 09:40:09 -0800 Subject: [PATCH 12/46] Fixing Tests issues in NetCore --- .../Microsoft.Data.SqlClient.Tests.csproj | 2 +- .../tests/FunctionalTests/SqlClientEventSourceTest.cs | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj index 65f6484269..5394c531b7 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj @@ -21,7 +21,7 @@ - + diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlClientEventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlClientEventSourceTest.cs index 0837aa16c8..3d6bb55982 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlClientEventSourceTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlClientEventSourceTest.cs @@ -1,13 +1,14 @@ -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + using System.Collections.Generic; using System.Diagnostics.Tracing; -using System.Linq; -using System.IO; -using System.Threading.Tasks; using Xunit; namespace Microsoft.Data.SqlClient.Tests { + [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp,"Not Implemented")] public class SqlClientEventSourceTest { [Fact] From f39321c499fdf62af197ada6dd0b4ec32b3fc33c Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 4 Feb 2020 11:03:14 -0800 Subject: [PATCH 13/46] moving from Functional to Manual Tests --- .../EventSource}/SqlClientEventSourceTest.cs | 8 +++++--- .../Microsoft.Data.SqlClient.ManualTesting.Tests.csproj | 1 + 2 files changed, 6 insertions(+), 3 deletions(-) rename src/Microsoft.Data.SqlClient/tests/{FunctionalTests => ManualTests/EventSource}/SqlClientEventSourceTest.cs (86%) diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlClientEventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/SqlClientEventSourceTest.cs similarity index 86% rename from src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlClientEventSourceTest.cs rename to src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/SqlClientEventSourceTest.cs index 3d6bb55982..707c8428a5 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlClientEventSourceTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/SqlClientEventSourceTest.cs @@ -4,20 +4,22 @@ using System.Collections.Generic; using System.Diagnostics.Tracing; +using Microsoft.Data.SqlClient.ManualTesting.Tests; using Xunit; namespace Microsoft.Data.SqlClient.Tests { - [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp,"Not Implemented")] + [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "Not Implemented")] public class SqlClientEventSourceTest { - [Fact] + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void IsTraceEnabled() { + string connString = DataTestUtility.TCPConnectionString; using (var listener = new SampleEventListener()) { listener.EnableEvents(SqlClientEventSource.Log, EventLevel.Informational, SqlClientEventSource.Keywords.Trace); - using (SqlConnection connection = new SqlConnection("Data Source=tcp:localhost;Database=Northwind;Integrated Security=true;")) + using (SqlConnection connection = new SqlConnection(connString)) { connection.Open(); using (SqlCommand command = new SqlCommand("SELECT * From [Customers]", connection)) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj index d48c72e562..33f137dbca 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj @@ -56,6 +56,7 @@ + From 40df85b7fb22910a5d82cd1e280cba976ac8eee3 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 4 Feb 2020 11:23:17 -0800 Subject: [PATCH 14/46] EventSource --- .../tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj index 5394c531b7..5800c4f891 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj @@ -21,7 +21,6 @@ - From 8c5af7306d5251d639960445b44c8f7671650f7b Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 4 Feb 2020 14:28:34 -0800 Subject: [PATCH 15/46] EventSource unwanted reference --- .../netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 6fab3db478..7cdf4453eb 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -5,7 +5,6 @@ using System.Text; using System.Diagnostics.Tracing; using System.Threading; -using System.Runtime.CompilerServices; namespace Microsoft.Data.SqlClient { From 44bb6c2ee2fbddf20f748abac72c9f27056d68b2 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 4 Feb 2020 14:45:01 -0800 Subject: [PATCH 16/46] Taking extra documentation file out. --- .../SqlClientEventSourceKeywords.xml | 46 ------------------- 1 file changed, 46 deletions(-) delete mode 100644 doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSourceKeywords.xml diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSourceKeywords.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSourceKeywords.xml deleted file mode 100644 index 2536e2a62c..0000000000 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSourceKeywords.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - Specifies a value for SqlClientEventSource. . - - - - Logs all Trace events. - 1 - - - To be added. - 2 - - - To be added. - 4 - - - To be added. - 8 - - - To be added. - 16 - - - To be added. - 32 - - - To be added. - 64 - - - To be added. - 128 - - - To be added. - 512 - - Returns All values of SqlClientEventSourceKeywords. - - From a650fa894b1c036bd4fce334f15b74be15af72da Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 4 Feb 2020 15:11:07 -0800 Subject: [PATCH 17/46] Deleting unwanted file from NetCore --- .../Data/SqlClient/SqlClientEventSource.cs | 170 ------------------ 1 file changed, 170 deletions(-) delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs deleted file mode 100644 index d7355c8315..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Text; -using System.Diagnostics.Tracing; -using System.Threading; -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("Microsoft.Data.SqlClient.ManualTesting.Tests")] -namespace Microsoft.Data.SqlClient -{ - - [EventSource(Name = "Microsoft.Data.SqlClient.EventSource")] - internal class SqlClientEventSource : EventSource - { - internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); - private static long s_nextScopeId = 0; - private static long s_nextNotificationScopeId = 0; - - private const int TraceEventId = 1; - private const int EnterScopeId = 2; - private const int ExitScopeId = 3; - private const int TraceBinId = 4; - private const int CorrelationTraceId = 5; - private const int NotificationsScopeEnterId = 6; - private const int NotificationsTraceId = 7; - private const int PoolerScopeEnterId = 8; - private const int PoolerTraceId = 9; - private const int PutStrId = 10; - - //Any Prropery added to this class should be a power of 2. - public class Keywords - { - internal const EventKeywords Trace = (EventKeywords)0x0001; // Integer 1 - internal const EventKeywords Scope = (EventKeywords)0x0002; // Integer 2 - internal const EventKeywords NotificationTrace = (EventKeywords)0x0004; // Integer 4 - internal const EventKeywords Pooling = (EventKeywords)0x0008; // Integer 8 - internal const EventKeywords Correlation = (EventKeywords)0x0010; // Integer 16 - internal const EventKeywords NotificationScope = (EventKeywords)0x0020; // Integer 32 - internal const EventKeywords PoolerScope = (EventKeywords)0X0040; // Integer 64 - internal const EventKeywords StringPrintOut = (EventKeywords)0x0080; // Integer 128 - internal const EventKeywords PoolerTrace = (EventKeywords)0x0200; //Integer 512 - - public static EventKeywords GetAll() - { - return Trace | Scope | NotificationTrace | Pooling | Correlation | NotificationScope | PoolerScope | StringPrintOut; - } - } - - [NonEvent] - internal bool IsTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Trace); - - [NonEvent] - internal bool IsScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Scope); - - [NonEvent] - internal bool IsPoolerScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerScope); - - [NonEvent] - internal bool IsCorrelationEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Correlation); - - [NonEvent] - internal bool IsNotificationScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationScope); - - [NonEvent] - internal bool IsPoolingEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Pooling); - - [NonEvent] - internal bool IsNotificationTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationTrace); - - [NonEvent] - internal bool IsPoolerTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerTrace); - - - [Event(TraceEventId, Level = EventLevel.Informational, Channel = EventChannel.Debug, Keywords = Keywords.Trace)] - internal void Trace(string message) - { - WriteEvent(TraceEventId, message); - } - - [Event(EnterScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] - internal long ScopeEnter(string message) - { - StringBuilder MsgstrBldr = new StringBuilder(message); - long scopeId = 0; - if (Log.IsEnabled()) - { - scopeId = Interlocked.Increment(ref s_nextScopeId); - WriteEvent(EnterScopeId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); - } - return scopeId; - } - - [Event(ExitScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] - internal void ScopeLeave(long scopeId) - { - if (!Log.IsEnabled()) - { - return; - } - WriteEvent(ExitScopeId, scopeId); - } - - [Event(TraceBinId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] - internal void TraceBin(string message, byte[] whereabout, int length) - { - if (Log.IsEnabled(EventLevel.Informational, Keywords.Trace)) - { - WriteEvent(TraceBinId, message, whereabout, length); - } - - } - - [Event(CorrelationTraceId, Level = EventLevel.Informational, Keywords = Keywords.Correlation, Opcode = EventOpcode.Start)] - internal void CorrelationTrace(string message) - { - - WriteEvent(CorrelationTraceId, message); - } - - [Event(NotificationsScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.NotificationScope)] - internal long NotificationsScopeEnter(string message) - { - long scopeId = 0; - if (Log.IsEnabled()) - { - StringBuilder MsgstrBldr = new StringBuilder(message); - scopeId = Interlocked.Increment(ref s_nextNotificationScopeId); - WriteEvent(NotificationsScopeEnterId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); - } - return scopeId; - } - - [Event(PoolerScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.PoolerScope)] - internal long PoolerScopeEnter(string message) - { - long scopeId = 0; - if (Log.IsEnabled()) - { - - StringBuilder MsgstrBldr = new StringBuilder(message); - WriteEvent(PoolerScopeEnterId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); - } - return scopeId; - } - - [Event(NotificationsTraceId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] - internal void NotificationsTrace(string message) - { - WriteEvent(PoolerScopeEnterId, message); - } - - [Event(PoolerTraceId, Level = EventLevel.Informational, Keywords = Keywords.PoolerTrace)] - internal void PoolerTrace(string message) - { - WriteEvent(PoolerTraceId, message); - } - - [Event(PutStrId, Level = EventLevel.Informational, Keywords = Keywords.StringPrintOut)] - internal void PutStr(string message) - { - if (Log.IsEnabled(EventLevel.Informational, Keywords.StringPrintOut)) - { - WriteEvent(PutStrId, message); - - } - } - } -} From 4b3a7375baa5e138cc6001fae72c324a4f808c02 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 4 Feb 2020 15:23:09 -0800 Subject: [PATCH 18/46] EventSource --- doc/samples/SqlClientEventSource_EventLogger.cs | 2 -- .../netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs | 1 - 2 files changed, 3 deletions(-) diff --git a/doc/samples/SqlClientEventSource_EventLogger.cs b/doc/samples/SqlClientEventSource_EventLogger.cs index ca8bbcd289..429df7cc62 100644 --- a/doc/samples/SqlClientEventSource_EventLogger.cs +++ b/doc/samples/SqlClientEventSource_EventLogger.cs @@ -26,7 +26,6 @@ static void Main(string[] args) } } } - } public class SampleEventListener : EventListenr @@ -42,7 +41,6 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData) // report all event information Out.Write(" Event {0} ", eventData.EventName); - // Events can have formatting strings 'the Message property on the 'Event' attribute. // If the event has a formatted message, print that, otherwise print out argument values. if (eventData.Message != null) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 7cdf4453eb..b69ed29fe6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -26,7 +26,6 @@ public class SqlClientEventSource : EventSource private const int NotificationsTraceId = 7; private const int PoolerScopeEnterId = 8; private const int PoolerTraceId = 9; - private const int PutStrId = 10; /// public class Keywords From 435c9d7afc63e631e0567a484f5fe66f47d7e0b5 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Wed, 5 Feb 2020 11:26:19 -0800 Subject: [PATCH 19/46] Additional Improvments --- .../src/Microsoft/Data/Common/AdapterUtil.cs | 2 +- .../netfx/src/Microsoft/Data/DataException.cs | 24 ++++++++----------- .../Data/ProviderBase/DataReaderContainer.cs | 1 - .../Microsoft/Data/ProviderBase/DbBuffer.cs | 1 - .../Data/ProviderBase/DbConnectionClosed.cs | 2 -- .../Data/ProviderBase/DbConnectionFactory.cs | 3 +-- .../Microsoft/Data/RelationshipConverter.cs | 1 - .../Data/SqlClient/SqlClientEventSource.cs | 8 +++---- .../src/Microsoft/Data/SqlEventSource.cs | 1 - .../Microsoft/Data/SqlTypes/SqlFileStream.cs | 2 ++ .../EventSource/SqlClientEventSourceTest.cs | 3 ++- 11 files changed, 20 insertions(+), 28 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index a2f042d863..8bcc9c698f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -103,7 +103,7 @@ static private void TraceException( Debug.Assert(null != e, "TraceException: null Exception"); if (null != e && Log.IsTraceEnabled()) { - Log.Trace(e.ToString()); // will include callstack if permission is available + Log.Trace($"{e.ToString()}"); // will include callstack if permission is available } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs index c9a2e45ccd..5dae71b776 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -7,12 +7,10 @@ using System.Data; using System.Diagnostics; using System.Globalization; -using Microsoft.Data.SqlClient; using static Microsoft.Data.SqlClient.SqlClientEventSource; namespace Microsoft.Data { - internal static class ExceptionBuilder { // The class defines the exceptions that are specific to the DataSet. @@ -32,14 +30,17 @@ static private void TraceException( { Log.Trace(e.Message); - try - { - Log.Trace($"{trace}, StackTrace='{Environment.StackTrace}'"); - } - catch (System.Security.SecurityException) + if (Log.IsAdvanceTraceOn()) { - // if you don't have permission - you don't get the stack trace - Log.Trace("Permission Denied"); + try + { + Log.Trace($"{trace}, StackTrace='{Environment.StackTrace}'"); + } + catch (System.Security.SecurityException) + { + // if you don't have permission - you don't get the stack trace + Log.Trace("Permission Denied"); + } } } } @@ -216,7 +217,6 @@ static public Exception ArgumentContainsNull(string paramName) return _Argument(paramName, StringsHelper.GetString(Strings.Data_ArgumentContainsNull, paramName)); } - // // Collections // @@ -897,7 +897,6 @@ static public Exception InValidNestedRelation(string childTableName) return _InvalidOperation(StringsHelper.GetString(Strings.DataRelation_InValidNestedRelation, childTableName)); } - static public Exception InvalidParentNamespaceinNestedRelation(string childTableName) { return _InvalidOperation(StringsHelper.GetString(Strings.DataRelation_InValidNamespaceInNestedRelation, childTableName)); @@ -1295,7 +1294,6 @@ static public Exception StorageSetFailed() return _Argument(StringsHelper.GetString(Strings.DataStorage_SetInvalidDataType)); } - // // XML schema // @@ -1449,7 +1447,6 @@ static public Exception PolymorphismNotSupported(string typeName) return _InvalidOperation(StringsHelper.GetString(Strings.Xml_PolymorphismNotSupported, typeName)); } - static public Exception DataTableInferenceNotSupported() { return _InvalidOperation(StringsHelper.GetString(Strings.Xml_DataTableInferenceNotSupported)); @@ -1527,7 +1524,6 @@ static public Exception EmptyDataTableReader(string tableName) return _DeletedRowInaccessible(StringsHelper.GetString(Strings.DataTableReader_DataTableCleared, tableName)); } - // static internal Exception InvalidDuplicateNamedSimpleTypeDelaration(string stName, string errorStr) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DataReaderContainer.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DataReaderContainer.cs index 7ad9077248..d80e3db2d1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DataReaderContainer.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DataReaderContainer.cs @@ -4,7 +4,6 @@ namespace Microsoft.Data.ProviderBase { - using System; using System.Data; using System.Data.Common; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs index 4c85388f56..30a3bc7b99 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs @@ -14,7 +14,6 @@ namespace Microsoft.Data.ProviderBase // so that when debugging, we can tell the difference between one DbBuffer and another internal abstract class DbBuffer : SafeHandle { - internal const int LMEM_FIXED = 0x0000; internal const int LMEM_MOVEABLE = 0x0002; internal const int LMEM_ZEROINIT = 0x0040; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs index 3cc0501354..ad48b3fa30 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs @@ -13,7 +13,6 @@ namespace Microsoft.Data.ProviderBase abstract internal class DbConnectionClosed : DbConnectionInternal { - // Construct an "empty" connection protected DbConnectionClosed(ConnectionState state, bool hidePassword, bool allowSetConnectionString) : base(state, hidePassword, allowSetConnectionString) { @@ -167,7 +166,6 @@ private DbConnectionClosedNeverOpened() : base(ConnectionState.Closed, false, tr sealed internal class DbConnectionClosedPreviouslyOpened : DbConnectionClosed { // Closed Connection, Has Previously Been Opened - internal static readonly DbConnectionInternal SingletonInstance = new DbConnectionClosedPreviouslyOpened(); // singleton object private DbConnectionClosedPreviouslyOpened() : base(ConnectionState.Closed, true, true) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index 9f003f5bf7..7ce370c4e4 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -4,7 +4,6 @@ namespace Microsoft.Data.ProviderBase { - using System; using System.Collections.Generic; using System.Data; @@ -119,7 +118,7 @@ public void ClearPool(DbConnectionPoolKey key) Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, "key.ConnectionString"); - long scopeID=0; + long scopeID = 0; if (Log.IsEnabled()) { scopeID = Log.ScopeEnter(" connectionString"); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/RelationshipConverter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/RelationshipConverter.cs index ac6539a356..9718f0342c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/RelationshipConverter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/RelationshipConverter.cs @@ -16,7 +16,6 @@ public RelationshipConverter() { } - /// /// Gets a value indicating whether this converter can /// convert an object to the given destination type using the context. diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index b69ed29fe6..2bf5d7f01c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -31,10 +31,10 @@ public class SqlClientEventSource : EventSource public class Keywords { /// - public const EventKeywords Trace = (EventKeywords)0x0001; + public const EventKeywords Trace = (EventKeywords)1; /// - public const EventKeywords Scope = (EventKeywords)0x0002; + public const EventKeywords Scope = (EventKeywords)2; /// public const EventKeywords NotificationTrace = (EventKeywords)4; @@ -139,7 +139,7 @@ internal long NotificationsScopeEnter(string message) { StringBuilder MsgstrBldr = new StringBuilder(message); scopeId = Interlocked.Increment(ref s_nextNotificationScopeId); - WriteEvent(NotificationsScopeEnterId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); + WriteEvent(NotificationsScopeEnterId, MsgstrBldr.Append($", Scope ID ='[{ scopeId}]'")); } return scopeId; } @@ -151,7 +151,7 @@ internal long PoolerScopeEnter(string message) if (Log.IsEnabled()) { StringBuilder MsgstrBldr = new StringBuilder(message); - WriteEvent(PoolerScopeEnterId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); + WriteEvent(PoolerScopeEnterId, MsgstrBldr.Append($", Scope ID ='[{ scopeId}]'")); } return scopeId; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlEventSource.cs index 2135c362e5..da1843d6d4 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlEventSource.cs @@ -24,7 +24,6 @@ internal sealed class SqlEventSource : EventSource // Defines the singleton instance for the Resources ETW provider internal static readonly SqlEventSource Log = new SqlEventSource(); - /// /// Keyword definitions. These represent logical groups of events that can be turned on and off independently /// Often each task has a keyword, but where tasks are determined by subsystem, keywords are determined by diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs index b107acc8de..700b89e8d6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs @@ -67,7 +67,9 @@ Int64 allocationSize { long scopeID = 0; if (Log.IsEnabled()) + { scopeID = Log.ScopeEnter($" { ObjectID}# access={(int)access} options={(int)options} path='{path}'"); + } try { diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/SqlClientEventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/SqlClientEventSourceTest.cs index 707c8428a5..839f49367a 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/SqlClientEventSourceTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/SqlClientEventSourceTest.cs @@ -50,8 +50,9 @@ public class SampleEventListener : EventListener protected override void OnEventWritten(EventWrittenEventArgs eventData) { if (eventData.Message != null) - + { eventsNames.Add(eventData.EventName); + } else { eventsNames.Add(eventData.EventName); From 4bc920c96044ecc73a9cff0f1c1c0739ec4c34c2 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Wed, 5 Feb 2020 12:44:45 -0800 Subject: [PATCH 20/46] Taking the Static reference out --- .../src/Microsoft/Data/Common/AdapterUtil.cs | 7 +- .../Data/Common/DBConnectionString.cs | 10 +- .../Data/Common/DbConnectionOptions.cs | 8 +- .../netfx/src/Microsoft/Data/DataException.cs | 12 +- .../Data/ProviderBase/DbConnectionFactory.cs | 56 ++-- .../Data/ProviderBase/DbConnectionInternal.cs | 56 ++-- .../Data/ProviderBase/DbConnectionPool.cs | 196 ++++++------ .../ProviderBase/DbConnectionPoolGroup.cs | 15 +- .../Data/ProviderBase/SqlConnectionHelper.cs | 32 +- .../Microsoft/Data/SqlClient/LocalDBAPI.cs | 26 +- .../SqlClient/Server/SmiEventSink_Default.cs | 6 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 20 +- .../Data/SqlClient/SqlClientEventSource.cs | 28 +- .../Data/SqlClient/SqlClientLogger.cs | 12 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 212 ++++++------- .../Microsoft/Data/SqlClient/SqlCommandSet.cs | 20 +- .../Microsoft/Data/SqlClient/SqlConnection.cs | 108 +++---- .../Data/SqlClient/SqlConnectionFactory.cs | 6 +- .../SqlConnectionPoolGroupProviderInfo.cs | 10 +- .../Data/SqlClient/SqlDataAdapter.cs | 14 +- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 54 ++-- .../Data/SqlClient/SqlDataReaderSmi.cs | 50 +-- .../Data/SqlClient/SqlDelegatedTransaction.cs | 26 +- .../Microsoft/Data/SqlClient/SqlDependency.cs | 244 +++++++-------- .../Data/SqlClient/SqlDependencyListener.cs | 294 +++++++++--------- .../Data/SqlClient/SqlDependencyUtils.cs | 142 ++++----- .../src/Microsoft/Data/SqlClient/SqlError.cs | 6 +- .../Data/SqlClient/SqlInternalConnection.cs | 34 +- .../SqlClient/SqlInternalConnectionSmi.cs | 82 ++--- .../SqlClient/SqlInternalConnectionTds.cs | 186 +++++------ .../Data/SqlClient/SqlTransaction.cs | 42 +-- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 196 ++++++------ .../Data/SqlClient/TdsParserSessionPool.cs | 36 +-- .../Data/SqlClient/TdsParserStateObject.cs | 56 ++-- .../Data/SqlClient/sqlinternaltransaction.cs | 32 +- .../Microsoft/Data/SqlTypes/SqlFileStream.cs | 12 +- 36 files changed, 1173 insertions(+), 1173 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index 8bcc9c698f..748c386b29 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -21,12 +21,11 @@ using System.Threading; using System.Threading.Tasks; using System.Xml; -using static Microsoft.Data.SqlClient.SqlClientEventSource; +using Microsoft.Data.SqlClient; using Microsoft.Data.SqlClient.Server; using Microsoft.Win32; using SysES = System.EnterpriseServices; using SysTx = System.Transactions; -using Microsoft.Data.SqlClient; namespace Microsoft.Data.Common { @@ -101,9 +100,9 @@ static private void TraceException( string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e && Log.IsTraceEnabled()) + if (null != e && SqlClient.SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($"{e.ToString()}"); // will include callstack if permission is available + SqlClient.SqlClientEventSource.Log.Trace($"{e.ToString()}"); // will include callstack if permission is available } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs index 968c5a71fa..51eff9335a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs @@ -12,7 +12,7 @@ namespace Microsoft.Data.Common using System.Diagnostics; using System.Linq; using System.Text; - using static Microsoft.Data.SqlClient.SqlClientEventSource; + using Microsoft.Data.SqlClient; [Serializable] // MDAC 83147 internal sealed class DBConnectionString @@ -470,9 +470,9 @@ static private string[] NoDuplicateUnion(string[] a, string[] b) private static string[] ParseRestrictions(string restrictions, Hashtable synonyms) { #if DEBUG - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" Restrictions='{restrictions}'"); + SqlClientEventSource.Log.Trace($" Restrictions='{restrictions}'"); } #endif List restrictionValues = new List(); @@ -489,9 +489,9 @@ private static string[] ParseRestrictions(string restrictions, Hashtable synonym if (!ADP.IsEmpty(keyname)) { #if DEBUG - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" KeyName='{keyname}'"); + SqlClientEventSource.Log.Trace($" KeyName='{keyname}'"); } #endif string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144 diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs index 061ea12f53..2aeb858dca 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs @@ -12,7 +12,7 @@ namespace Microsoft.Data.Common using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; - using static Microsoft.Data.SqlClient.SqlClientEventSource; + using Microsoft.Data.SqlClient; internal class DbConnectionOptions { @@ -631,17 +631,17 @@ private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hash string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); - if (Log.IsTraceEnabled()) + if (SqlClient.SqlClientEventSource.Log.IsTraceEnabled()) { if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) { // don't trace passwords ever! if (null != keyvalue) { - Log.Trace($" KeyName='{keyname}', KeyValue='{keyvalue}'\n"); + SqlClientEventSource.Log.Trace($" KeyName='{keyname}', KeyValue='{keyvalue}'\n"); } else { - Log.Trace($" KeyName='{keyname}'\n"); + SqlClientEventSource.Log.Trace($" KeyName='{keyname}'\n"); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs index 5dae71b776..86c62b0386 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -7,7 +7,7 @@ using System.Data; using System.Diagnostics; using System.Globalization; -using static Microsoft.Data.SqlClient.SqlClientEventSource; +using Microsoft.Data.SqlClient; namespace Microsoft.Data { @@ -26,20 +26,20 @@ static private void TraceException( string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e && Log.IsAdvanceTraceOn()) + if (null != e && SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace(e.Message); + SqlClientEventSource.Log.Trace(e.Message); - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { try { - Log.Trace($"{trace}, StackTrace='{Environment.StackTrace}'"); + SqlClientEventSource.Log.Trace($"{trace}, StackTrace='{Environment.StackTrace}'"); } catch (System.Security.SecurityException) { // if you don't have permission - you don't get the stack trace - Log.Trace("Permission Denied"); + SqlClientEventSource.Log.Trace("Permission Denied"); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index 7ce370c4e4..b045f47631 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -12,7 +12,7 @@ namespace Microsoft.Data.ProviderBase using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Common; - using static Microsoft.Data.SqlClient.SqlClientEventSource; + using Microsoft.Data.SqlClient; internal abstract class DbConnectionFactory { @@ -66,9 +66,9 @@ internal int ObjectID public void ClearAllPools() { long scopeID = 0; - if (Log.IsEnabled()) + if (SqlClientEventSource.Log.IsEnabled()) { - scopeID = Log.ScopeEnter(""); + scopeID = SqlClientEventSource.Log.ScopeEnter(""); } try @@ -85,7 +85,7 @@ public void ClearAllPools() } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -94,9 +94,9 @@ public void ClearPool(DbConnection connection) ADP.CheckArgumentNull(connection, "connection"); long scopeID = 0; - if (Log.IsEnabled()) + if (SqlClientEventSource.Log.IsEnabled()) { - scopeID = Log.ScopeEnter($" {GetObjectId(connection)}#"); + scopeID = SqlClientEventSource.Log.ScopeEnter($" {GetObjectId(connection)}#"); } try @@ -109,7 +109,7 @@ public void ClearPool(DbConnection connection) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -119,9 +119,9 @@ public void ClearPool(DbConnectionPoolKey key) ADP.CheckArgumentNull(key.ConnectionString, "key.ConnectionString"); long scopeID = 0; - if (Log.IsEnabled()) + if (SqlClientEventSource.Log.IsEnabled()) { - scopeID = Log.ScopeEnter(" connectionString"); + scopeID = SqlClientEventSource.Log.ScopeEnter(" connectionString"); } try @@ -135,7 +135,7 @@ public void ClearPool(DbConnectionPoolKey key) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -167,9 +167,9 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakeNonPooledObject(owningConnection, PerformanceCounters); } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Non-pooled database connection created."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Non-pooled database connection created."); } return newConnection; } @@ -187,9 +187,9 @@ internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbCo newConnection.MakePooledConnection(pool); } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Pooled database connection created."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Pooled database connection created."); } return newConnection; @@ -386,9 +386,9 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour // connection creation failed on semaphore waiting or if max pool reached if (connectionPool.IsRunning) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred."); } // If GetConnection failed while the pool is running, the pool timeout occurred. @@ -408,9 +408,9 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour if (connection == null) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred and all retries were exhausted."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred and all retries were exhausted."); } // exhausted all retries or timed out - give up @@ -438,9 +438,9 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti // however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, DisabledPoolGroup={connectionPoolGroup.ObjectID}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, DisabledPoolGroup={connectionPoolGroup.ObjectID}#"); } // reusing existing pool option in case user originally used SetConnectionPoolOptions @@ -571,10 +571,10 @@ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPo private void PruneConnectionPoolGroups(object state) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { // when debugging this method, expect multiple threads at the same time - Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#"); } // First, walk the pool release list and attempt to clear each @@ -596,9 +596,9 @@ private void PruneConnectionPoolGroups(object state) { _poolsToRelease.Remove(pool); - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" { ObjectID}#, ReleasePool={pool.ObjectID}#"); + SqlClientEventSource.Log.Trace($" { ObjectID}#, ReleasePool={pool.ObjectID}#"); } PerformanceCounters.NumberOfInactiveConnectionPools.Decrement(); @@ -626,9 +626,9 @@ private void PruneConnectionPoolGroups(object state) { _poolGroupsToRelease.Remove(poolGroup); - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}#, ReleasePoolGroup={poolGroup.ObjectID}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, ReleasePoolGroup={poolGroup.ObjectID}#"); } PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Decrement(); @@ -696,9 +696,9 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { Debug.Assert(null != poolGroup, "null poolGroup?"); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, poolGroup={poolGroup.ObjectID}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, poolGroup={poolGroup.ObjectID}#"); } lock (_poolGroupsToRelease) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index 5ce6caf3b8..e3879eebf9 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -14,7 +14,7 @@ namespace Microsoft.Data.ProviderBase using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Common; - using static Microsoft.Data.SqlClient.SqlClientEventSource; + using Microsoft.Data.SqlClient; using SysTx = System.Transactions; internal abstract class DbConnectionInternal @@ -163,9 +163,9 @@ protected internal SysTx.Transaction EnlistedTransaction if (null != value) { - if (Log.IsPoolerTraceEnabled()) + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) { - Log.PoolerTrace($" {ObjectID}#, Transaction {value.GetHashCode()}#, Enlisting."); + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {value.GetHashCode()}#, Enlisting."); } TransactionOutcomeEnlist(value); @@ -393,9 +393,9 @@ internal void ActivateConnection(SysTx.Transaction transaction) // Internal method called from the connection pooler so we don't expose // the Activate method publicly. - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.PoolerTrace($" {ObjectID}#, Activating"); + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Activating"); } #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); @@ -468,8 +468,8 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac Debug.Assert(null != owningObject, "null owningObject"); Debug.Assert(null != connectionFactory, "null connectionFactory"); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}# Closing."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}# Closing."); // if an exception occurs after the state change but before the try block // the connection will be stuck in OpenBusy state. The commented out try-catch @@ -574,8 +574,8 @@ internal void DeactivateConnection() { // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Deactivating"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Deactivating"); #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); Debug.Assert(0 == activateCount, "activated multiple times?"); @@ -610,9 +610,9 @@ virtual internal void DelegatedTransactionEnded() // you call this method to prevent race conditions with Clear and // ReclaimEmancipatedObjects. - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Delegated Transaction Completed."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Delegated Transaction Completed."); } if (1 == _pooledCount) @@ -677,8 +677,8 @@ protected internal void DoNotPoolThisConnection() { _cannotBePooled = true; - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Marking pooled object as non-poolable so it will be disposed"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Marking pooled object as non-poolable so it will be disposed"); } /// Ensure that this connection cannot be put back into the pool. @@ -687,8 +687,8 @@ protected internal void DoomThisConnection() { _connectionIsDoomed = true; - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Dooming"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Dooming"); } // Reset connection doomed status so it can be re-connected and pooled. @@ -822,8 +822,8 @@ internal void PrePush(object expectedOwner) } //DbConnection x = (expectedOwner as DbConnection); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Preparing to push into pool, owning connection {0}#, pooledCount={ _pooledCount}"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Preparing to push into pool, owning connection {0}#, pooledCount={ _pooledCount}"); _pooledCount++; _owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2% @@ -855,8 +855,8 @@ internal void PostPop(object newOwner) _pooledCount--; //DbConnection x = (newOwner as DbConnection); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Preparing to pop from pool, owning connection {0}#, pooledCount={_pooledCount}"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Preparing to pop from pool, owning connection {0}#, pooledCount={_pooledCount}"); //3 // The following tests are retail assertions of things we can't allow to happen. if (null != Pool) @@ -913,9 +913,9 @@ internal void DetachCurrentTransactionIfEnded() // Detach transaction from connection. internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})"); } // potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new @@ -958,9 +958,9 @@ void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) { SysTx.Transaction transaction = e.Transaction; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})"); } CleanupTransactionOnCompletion(transaction); @@ -980,23 +980,23 @@ internal void SetInStasis() { _isInStasis = true; - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose."); PerformanceCounters.NumberOfStasisConnections.Increment(); } private void TerminateStasis(bool returningToPool) { - if (Log.IsPoolerTraceEnabled()) + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) { if (returningToPool) { - Log.PoolerTrace($" { ObjectID}#, Delegated Transaction has ended, connection is closed. Returning to general pool."); + SqlClientEventSource.Log.PoolerTrace($" { ObjectID}#, Delegated Transaction has ended, connection is closed. Returning to general pool."); } else { - Log.PoolerTrace($" {ObjectID}#, Delegated Transaction has ended, connection is closed/leaked. Disposing."); + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Delegated Transaction has ended, connection is closed/leaked. Disposing."); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index 007703e385..f454ea4c0a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -19,7 +19,7 @@ namespace Microsoft.Data.ProviderBase using System.Threading.Tasks; using Microsoft.Data.Common; using Microsoft.Data.SqlClient; - using static Microsoft.Data.SqlClient.SqlClientEventSource; + using SysTx = System.Transactions; sealed internal class DbConnectionPool @@ -83,8 +83,8 @@ internal TransactedConnectionPool(DbConnectionPool pool) _pool = pool; _transactedCxns = new Dictionary(); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Constructed for connection pool {_pool.ObjectID}#"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Constructed for connection pool {_pool.ObjectID}#"); } internal int ObjectID @@ -141,9 +141,9 @@ internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction) } } - if (null != transactedObject && Log.IsPoolerTraceEnabled()) + if (null != transactedObject && SqlClientEventSource.Log.IsPoolerTraceEnabled()) { - Log.PoolerTrace($" { ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Popped."); + SqlClientEventSource.Log.PoolerTrace($" { ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Popped."); } return transactedObject; } @@ -171,8 +171,8 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing."); connections.Add(transactedObject); } @@ -209,16 +209,16 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing."); connections.Add(transactedObject); } } else { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Adding List to transacted pool."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Adding List to transacted pool."); // add the connection/transacted object to the list newConnections.Add(transactedObject); @@ -247,8 +247,8 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt } } - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Added."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Added."); } Pool.PerformanceCounters.NumberOfFreeConnections.Increment(); @@ -257,8 +257,8 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionInternal transactedObject) { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed"); TransactedConnectionList connections; int entry = -1; @@ -293,8 +293,8 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern // safely remove the list from the transacted pool. if (0 >= connections.Count) { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Removing List from transacted pool."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Removing List from transacted pool."); _transactedCxns.Remove(transaction); // we really need to dispose our connection list; it may have @@ -311,8 +311,8 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern else { //Debug.Assert ( false, "TransactionCompletedEvent fired before PutTransactedObject put the connection in the transacted pool." ); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transacted pool not yet created prior to transaction completing. Connection may be leaked."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transacted pool not yet created prior to transaction completing. Connection may be leaked."); } } @@ -540,8 +540,8 @@ internal DbConnectionPool( _poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback _state = State.Running; - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Constructed."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Constructed."); //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls // StartBackgroundCallbacks after pool is actually in the collection @@ -690,8 +690,8 @@ private void CleanupCallback(Object state) // With this logic, objects are pruned from the pool if unused for // at least one period but not more than two periods. - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#"); // Destroy free objects that put us above MinPoolSize from old stack. while (Count > MinPoolSize) @@ -766,8 +766,8 @@ private void CleanupCallback(Object state) Debug.Assert(obj != null, "null connection is not expected"); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, ChangeStacks={obj.ObjectID}#"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, ChangeStacks={obj.ObjectID}#"); Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); Debug.Assert(obj.CanBePooled, "pooled object is not poolable"); @@ -783,8 +783,8 @@ private void CleanupCallback(Object state) internal void Clear() { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Clearing."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Clearing."); DbConnectionInternal obj; @@ -822,8 +822,8 @@ internal void Clear() // it's been doomed, will cause it to be disposed of as well) ReclaimEmancipatedObjects(); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Cleared."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Cleared."); } private Timer CreateCleanupTimer() @@ -914,8 +914,8 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio } } - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {newObj.ObjectID}#, Added to pool."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {newObj.ObjectID}#, Added to pool."); // Reset the error wait: _errorWait = ERROR_WAIT_DEFAULT; @@ -976,8 +976,8 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio private void DeactivateObject(DbConnectionInternal obj) { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Deactivating."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Deactivating."); obj.DeactivateConnection(); // we presume this operation is safe outside of a lock... @@ -1118,13 +1118,13 @@ internal void DestroyObject(DbConnectionInternal obj) // again. if (obj.IsTxRootWaitingForTxEnd) { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Has Delegated Transaction, waiting to Dispose."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Has Delegated Transaction, waiting to Dispose."); } else { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removing from pool."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removing from pool."); bool removed = false; lock (_objectList) @@ -1136,13 +1136,13 @@ internal void DestroyObject(DbConnectionInternal obj) if (removed) { - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removed from pool."); + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removed from pool."); PerformanceCounters.NumberOfPooledConnections.Decrement(); } obj.Dispose(); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Disposed."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Disposed."); PerformanceCounters.HardDisconnectsPerSecond.Increment(); } @@ -1150,8 +1150,8 @@ internal void DestroyObject(DbConnectionInternal obj) private void ErrorCallback(Object state) { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Resetting Error handling."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Resetting Error handling."); _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); @@ -1326,8 +1326,8 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource {ObjectID}#, DbConnectionInternal State != Running."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, DbConnectionInternal State != Running."); connection = null; return true; } @@ -1373,8 +1373,8 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj PerformanceCounters.SoftConnectsPerSecond.Increment(); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Getting connection."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Getting connection."); // If automatic transaction enlistment is required, then we try to // get the connection from the transacted connection pool first. @@ -1428,8 +1428,8 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj { case WAIT_TIMEOUT: - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Wait timed out."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Wait timed out."); Interlocked.Decrement(ref _waitCount); connection = null; @@ -1437,14 +1437,14 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case ERROR_HANDLE: // Throw the error that PoolCreateRequest stashed. - Log.PoolerTrace($" {ObjectID}#, Errors are set."); + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Errors are set."); Interlocked.Decrement(ref _waitCount); throw TryCloneCachedException(); case CREATION_HANDLE: - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Creating new connection."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Creating new connection."); try { @@ -1498,8 +1498,8 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj if ((obj != null) && (!obj.IsConnectionAlive())) { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); DestroyObject(obj); obj = null; // Setting to null in case creating a new object fails @@ -1511,8 +1511,8 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj RuntimeHelpers.PrepareConstrainedRegions(); try { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Creating new connection."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Creating new connection."); obj = UserCreateRequest(owningObject, userOptions); } @@ -1524,8 +1524,8 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj else { // Timeout waiting for creation semaphore - return null - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Wait timed out."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Wait timed out."); connection = null; return false; @@ -1537,37 +1537,37 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case WAIT_FAILED: Debug.Assert(waitForMultipleObjectsExHR != 0, "WaitForMultipleObjectsEx failed but waitForMultipleObjectsExHR remained 0"); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Wait failed.\n"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Wait failed.\n"); Interlocked.Decrement(ref _waitCount); Marshal.ThrowExceptionForHR(waitForMultipleObjectsExHR); goto default; // if ThrowExceptionForHR didn't throw for some reason case (WAIT_ABANDONED + SEMAPHORE_HANDLE): - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Semaphore handle abandonded."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Semaphore handle abandonded."); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(SEMAPHORE_HANDLE, _waitHandles.PoolSemaphore); case (WAIT_ABANDONED + ERROR_HANDLE): - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Error handle abandonded."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Error handle abandonded."); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(ERROR_HANDLE, _waitHandles.ErrorEvent); case (WAIT_ABANDONED + CREATION_HANDLE): - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Creation handle abandoned."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Creation handle abandoned."); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(CREATION_HANDLE, _waitHandles.CreationSemaphore); default: - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, WaitForMultipleObjects={waitResult}"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, WaitForMultipleObjects={waitResult}"); Interlocked.Decrement(ref _waitCount); throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult); @@ -1634,8 +1634,8 @@ internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbCon { PerformanceCounters.SoftConnectsPerSecond.Increment(); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, replacing connection."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, replacing connection."); DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); @@ -1678,8 +1678,8 @@ private DbConnectionInternal GetFromGeneralPool() if (null != obj) { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from general pool."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from general pool."); PerformanceCounters.NumberOfFreeConnections.Decrement(); } @@ -1697,8 +1697,8 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac if (null != obj) { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from transacted pool."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from transacted pool."); PerformanceCounters.NumberOfFreeConnections.Decrement(); @@ -1710,8 +1710,8 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac } catch { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); DestroyObject(obj); throw; @@ -1719,8 +1719,8 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac } else if (!obj.IsConnectionAlive()) { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); DestroyObject(obj); obj = null; @@ -1738,9 +1738,9 @@ private void PoolCreateRequest(object state) // creation mutex has not been obtained long scopeID = 0; - if (Log.IsEnabled()) + if (SqlClientEventSource.Log.IsEnabled()) { - scopeID = Log.PoolerScopeEnter($" {ObjectID}#"); + scopeID = SqlClientEventSource.Log.PoolerScopeEnter($" {ObjectID}#"); } try @@ -1827,8 +1827,8 @@ private void PoolCreateRequest(object state) else { // trace waitResult and ignore the failure - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called WaitForSingleObject failed {waitResult}"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called WaitForSingleObject failed {waitResult}"); } } catch (Exception e) @@ -1842,8 +1842,8 @@ private void PoolCreateRequest(object state) // Now that CreateObject can throw, we need to catch the exception and discard it. // There is no further action we can take beyond tracing. The error will be // thrown to the user the next time they request a connection. - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called CreateConnection which threw an exception: {e}"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called CreateConnection which threw an exception: {e}"); } finally { @@ -1863,7 +1863,7 @@ private void PoolCreateRequest(object state) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1877,8 +1877,8 @@ internal void PutNewObject(DbConnectionInternal obj) // against checked bits. // Debug.Assert(obj.CanBePooled, "non-poolable object in pool"); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Pushing to general pool."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Pushing to general pool."); _stackNew.Push(obj); _waitHandles.PoolSemaphore.Release(1); @@ -1928,8 +1928,8 @@ internal void PutObjectFromTransactedPool(DbConnectionInternal obj) // that is using the connection, and that all pre-push logic has been // done and all transactions are ended. - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Transaction has ended."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Transaction has ended."); if (_state == State.Running && obj.CanBePooled) { @@ -1955,8 +1955,8 @@ private bool ReclaimEmancipatedObjects() { bool emancipatedObjectFound = false; - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#"); List reclaimedObjects = new List(); int count; @@ -2010,8 +2010,8 @@ private bool ReclaimEmancipatedObjects() { DbConnectionInternal obj = reclaimedObjects[i]; - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Reclaiming."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Reclaiming."); PerformanceCounters.NumberOfReclaimedConnections.Increment(); @@ -2025,8 +2025,8 @@ private bool ReclaimEmancipatedObjects() internal void Startup() { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, CleanupWait={_cleanupWait}"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, CleanupWait={_cleanupWait}"); _cleanupTimer = CreateCleanupTimer(); if (NeedToReplenish) @@ -2037,8 +2037,8 @@ internal void Startup() internal void Shutdown() { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#\n"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#\n"); _state = State.ShuttingDown; @@ -2061,8 +2061,8 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern Debug.Assert(null != transactedObject, "null transactedObject?"); // Note: connection may still be associated with transaction due to Explicit Unbinding requirement. - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed"); // called by the internal connection when it get's told that the // transaction is completed. We tell the transacted pool to remove diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs index 468eb149af..8a8b7df99d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -7,7 +7,8 @@ namespace Microsoft.Data.ProviderBase using System.Collections.Concurrent; using System.Diagnostics; using Microsoft.Data.Common; - using static Microsoft.Data.SqlClient.SqlClientEventSource; + using Microsoft.Data.SqlClient; + // set_ConnectionString calls DbConnectionFactory.GetConnectionPoolGroup // when not found a new pool entry is created and potentially added @@ -273,9 +274,9 @@ private bool MarkPoolGroupAsActive() { _state = PoolGroupStateActive; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Active"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Active"); } } return (PoolGroupStateActive == _state); @@ -339,18 +340,18 @@ internal bool Prune() { _state = PoolGroupStateIdle; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Idle"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Idle"); } } else if (PoolGroupStateIdle == _state) { _state = PoolGroupStateDisabled; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Disabled"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Disabled"); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs index 7a553a05b6..2c91a20711 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs @@ -12,7 +12,7 @@ namespace Microsoft.Data.SqlClient using System.Threading; using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; - using static Microsoft.Data.SqlClient.SqlClientEventSource; + using SysTx = System.Transactions; public sealed partial class SqlConnection : DbConnection @@ -87,9 +87,9 @@ internal DbConnectionOptions ConnectionOptions private string ConnectionString_Get() { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#"); } bool hidePassword = InnerConnection.ShouldHidePassword; @@ -137,9 +137,9 @@ private void ConnectionString_Set(DbConnectionPoolKey key) string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, '{cstr}'"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, '{cstr}'"); } } @@ -186,17 +186,17 @@ internal void Abort(Exception e) } // NOTE: we put the tracing last, because the ToString() calls (and - // the SqlClientEventSource.Log.Trace, for that matter) have no reliability contract and + // the SqlClientEventSource.SqlClientEventSource.Log.Trace, for that matter) have no reliability contract and // will end the reliable try... - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { if (e is OutOfMemoryException) { - Log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {"OutOfMemory"}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {"OutOfMemory"}"); } else { - Log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {e.ToString()}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {e.ToString()}"); } } } @@ -212,9 +212,9 @@ override protected DbCommand CreateDbCommand() DbCommand command = null; long scopeID = 0; - if (Log.IsEnabled()) + if (SqlClientEventSource.Log.IsEnabled()) { - scopeID = Log.ScopeEnter($" {ObjectID}#"); + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); } try @@ -225,7 +225,7 @@ override protected DbCommand CreateDbCommand() } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } return command; } @@ -262,9 +262,9 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)); permissionSet.Demand(); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Connection enlisting in a transaction."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection enlisting in a transaction."); } SysTx.Transaction indigoTransaction = null; @@ -292,9 +292,9 @@ override public void EnlistTransaction(SysTx.Transaction transaction) { SqlConnection.ExecutePermission.Demand(); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Connection enlisting in a transaction."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection enlisting in a transaction."); } // If we're currently enlisted in a transaction and we were called diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs index 299f5259b6..c75f5a0368 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs @@ -13,7 +13,7 @@ using System.Text; using System.Threading; using Microsoft.Data.SqlClient; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data { @@ -74,9 +74,9 @@ static IntPtr UserInstanceDLLHandle SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle); if (s_userInstanceDLLHandle != IntPtr.Zero) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace(" LocalDB - handle obtained"); + SqlClientEventSource.Log.Trace(" LocalDB - handle obtained"); } } else @@ -122,9 +122,9 @@ static LocalDBCreateInstanceDelegate LocalDBCreateInstance { int hResult = Marshal.GetLastWin32Error(); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" GetProcAddress for LocalDBCreateInstance error 0x{hResult}"); + SqlClientEventSource.Log.Trace($" GetProcAddress for LocalDBCreateInstance error 0x{hResult}"); } throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); @@ -169,9 +169,9 @@ static LocalDBFormatMessageDelegate LocalDBFormatMessage // SNI checks for LocalDBFormatMessage during DLL loading, so it is practically impossibe to get this error. int hResult = Marshal.GetLastWin32Error(); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" GetProcAddress for LocalDBFormatMessage error 0x{hResult}"); + SqlClientEventSource.Log.Trace($" GetProcAddress for LocalDBFormatMessage error 0x{hResult}"); } throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); @@ -329,9 +329,9 @@ internal static void CreateLocalDBInstance(string instance) } else { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace(" No system.data.localdb section found in configuration"); + SqlClientEventSource.Log.Trace(" No system.data.localdb section found in configuration"); } } s_configurableInstances = tempConfigurableInstances; @@ -360,9 +360,9 @@ internal static void CreateLocalDBInstance(string instance) // LocalDBCreateInstance is thread- and cross-process safe method, it is OK to call from two threads simultaneously int hr = LocalDBCreateInstance(instanceInfo.version, instance, flags: 0); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Starting creation of instance {instance} version {instanceInfo.version}"); + SqlClientEventSource.Log.Trace($" Starting creation of instance {instance} version {instanceInfo.version}"); } if (hr < 0) @@ -370,9 +370,9 @@ internal static void CreateLocalDBInstance(string instance) throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_CreateFailed"), instance: instance, localDbError: hr); } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Finished creation of instance {instance}"); + SqlClientEventSource.Log.Trace($" Finished creation of instance {instance}"); } instanceInfo.created = true; // mark instance as created } // CreateLocalDbInstance diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs index 3756721a4f..b84d2f199e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs @@ -3,7 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient.Server { @@ -269,9 +269,9 @@ internal override void MessagePosted(int number, byte state, byte errorClass, st { if (null == _parent) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {0}#, number={number} state={state} errorClass={errorClass} server='{server ?? ""}' message='{message ?? ""}' procedure='{procedure ?? ""}' linenumber={lineNumber}."); + SqlClientEventSource.Log.Trace($" {0}#, number={number} state={state} errorClass={errorClass} server='{server ?? ""}' message='{message ?? ""}' procedure='{procedure ?? ""}' linenumber={lineNumber}."); } SqlError error = new SqlError(number, state, errorClass, server, message, procedure, lineNumber); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index 05cbd6609c..c4bb8ab87f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; using System.Xml; using Microsoft.Data.Common; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + // todo list: // * An ID column need to be ignored - even if there is an association @@ -595,16 +595,16 @@ private Task CreateAndExecuteInitialQueryAsync(out Bulk { string TDSCommand = CreateInitialQuery(); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Initial Query: '{TDSCommand}'"); + SqlClientEventSource.Log.Trace($" Initial Query: '{TDSCommand}'"); } } - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls"); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); @@ -895,8 +895,8 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i // private Task SubmitUpdateBulkCommand(string TDSCommand) { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}\n"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}\n"); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); @@ -2528,9 +2528,9 @@ private void CheckAndRaiseNotification() _stateObj.BcpLock = true; abortOperation = FireRowsCopiedEvent(_rowsCopied); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace(""); + SqlClientEventSource.Log.Trace(""); } // just in case some pathological person closes the target connection ... diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 2bf5d7f01c..74ccfd4f79 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -62,31 +62,31 @@ public static EventKeywords GetAll() } [NonEvent] - internal bool IsTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Trace); + internal bool IsTraceEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Trace); [NonEvent] - internal bool IsScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Scope); + internal bool IsScopeEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Scope); [NonEvent] - internal bool IsPoolerScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerScope); + internal bool IsPoolerScopeEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.PoolerScope); [NonEvent] - internal bool IsCorrelationEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Correlation); + internal bool IsCorrelationEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Correlation); [NonEvent] - internal bool IsNotificationScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationScope); + internal bool IsNotificationScopeEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.NotificationScope); [NonEvent] - internal bool IsPoolingEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Pooling); + internal bool IsPoolingEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Pooling); [NonEvent] - internal bool IsNotificationTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationTrace); + internal bool IsNotificationTraceEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.NotificationTrace); [NonEvent] - internal bool IsPoolerTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerTrace); + internal bool IsPoolerTraceEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.PoolerTrace); [NonEvent] - internal bool IsAdvanceTraceOn() => Log.IsEnabled(EventLevel.LogAlways, EventKeywords.All); + internal bool IsAdvanceTraceOn() => SqlClientEventSource.Log.IsEnabled(EventLevel.LogAlways, EventKeywords.All); [Event(TraceEventId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] internal void Trace(string message) @@ -98,7 +98,7 @@ internal void Trace(string message) internal long ScopeEnter(string message) { long scopeId = 0; - if (Log.IsEnabled()) + if (SqlClientEventSource.Log.IsEnabled()) { StringBuilder MsgstrBldr = new StringBuilder(message); scopeId = Interlocked.Increment(ref s_nextScopeId); @@ -110,7 +110,7 @@ internal long ScopeEnter(string message) [Event(ExitScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] internal void ScopeLeave(long scopeId) { - if (Log.IsEnabled()) + if (SqlClientEventSource.Log.IsEnabled()) { WriteEvent(ExitScopeId, scopeId); } @@ -119,7 +119,7 @@ internal void ScopeLeave(long scopeId) [Event(TraceBinId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] internal void TraceBin(string message, byte[] whereabout, int length) { - if (Log.IsEnabled(EventLevel.Informational, Keywords.Trace)) + if (SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Trace)) { WriteEvent(TraceBinId, message, whereabout, length); } @@ -135,7 +135,7 @@ internal void CorrelationTrace(string message) internal long NotificationsScopeEnter(string message) { long scopeId = 0; - if (Log.IsEnabled()) + if (SqlClientEventSource.Log.IsEnabled()) { StringBuilder MsgstrBldr = new StringBuilder(message); scopeId = Interlocked.Increment(ref s_nextNotificationScopeId); @@ -148,7 +148,7 @@ internal long NotificationsScopeEnter(string message) internal long PoolerScopeEnter(string message) { long scopeId = 0; - if (Log.IsEnabled()) + if (SqlClientEventSource.Log.IsEnabled()) { StringBuilder MsgstrBldr = new StringBuilder(message); WriteEvent(PoolerScopeEnterId, MsgstrBldr.Append($", Scope ID ='[{ scopeId}]'")); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs index 678ae209aa..219de588bb 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -19,23 +19,23 @@ internal enum LogLevel /// public void LogInfo(string type, string method, string message) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($"{message}"); + SqlClientEventSource.Log.Trace($"{message}"); } } /// public void LogError(string type, string method, string message) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($"{message}"); + SqlClientEventSource.Log.Trace($"{message}"); } } /// - public bool IsLoggingEnabled => Log.IsEnabled(); + public bool IsLoggingEnabled => SqlClientEventSource.Log.IsEnabled(); /// public bool LogAssert(bool value, string type, string method, string message) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index dea51616e3..92a55dc59d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -24,7 +24,7 @@ using Microsoft.Data.Sql; using Microsoft.Data.SqlClient.Server; using SysTx = System.Transactions; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -347,9 +347,9 @@ internal CommandEventSink(SqlCommand command) : base() internal override void StatementCompleted(int rowsAffected) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {_command.ObjectID}#, rowsAffected={rowsAffected}."); + SqlClientEventSource.Log.Trace($" {_command.ObjectID}#, rowsAffected={rowsAffected}."); } _command.InternalRecordsAffected = rowsAffected; @@ -363,25 +363,25 @@ internal override void StatementCompleted(int rowsAffected) internal override void BatchCompleted() { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {_command.ObjectID}#."); + SqlClientEventSource.Log.Trace($" {_command.ObjectID}#."); } } internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 parameterValues) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {_command.ObjectID}# metaData.Length={((null != metaData) ? metaData.Length : -1)}."); + SqlClientEventSource.Log.Trace($" {_command.ObjectID}# metaData.Length={((null != metaData) ? metaData.Length : -1)}."); } - if (null != metaData && Log.IsTraceEnabled()) + if (null != metaData && SqlClientEventSource.Log.IsTraceEnabled()) { for (int i = 0; i < metaData.Length; i++) { - Log.Trace($" {_command.ObjectID}#, metaData[{i}] is {metaData[i].GetType().ToString()}{metaData[i].TraceString()}"); + SqlClientEventSource.Log.Trace($" {_command.ObjectID}#, metaData[{i}] is {metaData[i].GetType().ToString()}{metaData[i].TraceString()}"); } } @@ -391,9 +391,9 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter parameterValues, int ordinal) { - if (null != metaData && Log.IsTraceEnabled()) + if (null != metaData && SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {_command.ObjectID}#, metaData[{ordinal}] is {metaData.GetType().ToString()}{ metaData.TraceString()}"); + SqlClientEventSource.Log.Trace($" {_command.ObjectID}#, metaData[{ordinal}] is {metaData.GetType().ToString()}{ metaData.TraceString()}"); } Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion); @@ -580,9 +580,9 @@ private SqlCommand(SqlCommand from) : this() _activeConnection = value; // UNDONE: Designers need this setter. Should we block other scenarios? - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, {((null != value) ? value.ObjectID : -1)}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, {((null != value) ? value.ObjectID : -1)}#"); } } } @@ -661,9 +661,9 @@ public SqlNotificationRequest Notification } set { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#"); } _sqlDep = null; @@ -715,9 +715,9 @@ internal SqlStatistics Statistics } // TODO: Add objid here - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#"); } _transaction = value; } @@ -753,9 +753,9 @@ override public string CommandText } set { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, String Value = '{value}'"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, String Value = '{value}'"); } if (0 != ADP.SrcCompare(_commandText, value)) @@ -794,9 +794,9 @@ override public int CommandTimeout } set { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, {value}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, {value}"); } if (value < 0) @@ -843,9 +843,9 @@ override public CommandType CommandType } set { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, {(int)value}{_commandType}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, {(int)value}{_commandType}"); } if (_commandType != value) { @@ -989,9 +989,9 @@ internal void OnStatementCompleted(int recordCount) { try { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, recordCount={recordCount}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, recordCount={recordCount}"); } handler(this, new StatementCompletedEventArgs(recordCount)); @@ -1033,11 +1033,11 @@ override public void Prepare() SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); statistics = SqlStatistics.StartTimer(Statistics); @@ -1139,7 +1139,7 @@ override public void Prepare() } SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } private void InternalPrepare() @@ -1203,9 +1203,9 @@ internal void Unprepare() } _cachedMetaData = null; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Command unprepared."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Command unprepared."); } } @@ -1217,11 +1217,11 @@ internal void Unprepare() override public void Cancel() { long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($"< sc.SqlCommand.Cancel | API > {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($"< sc.SqlCommand.Cancel | API > {ObjectID}#"); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); SqlStatistics statistics = null; try @@ -1340,7 +1340,7 @@ override public void Cancel() finally { SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1385,11 +1385,11 @@ override public object ExecuteScalar() SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); bool success = false; int? sqlExceptionNumber = null; @@ -1411,7 +1411,7 @@ override public object ExecuteScalar() finally { SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1458,11 +1458,11 @@ override public int ExecuteNonQuery() SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); - if (Log.IsPoolerTraceEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); bool success = false; int? sqlExceptionNumber = null; @@ -1483,7 +1483,7 @@ override public int ExecuteNonQuery() finally { SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1501,8 +1501,8 @@ internal void ExecuteToPipe(SmiContext pipeContext) SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); try { @@ -1513,7 +1513,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) finally { SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1529,8 +1529,8 @@ public IAsyncResult BeginExecuteNonQuery() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); SqlConnection.ExecutePermission.Demand(); return BeginExecuteNonQueryInternal(0, callback, stateObject, 0, inRetry: false); @@ -1757,8 +1757,8 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) } finally { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); } } @@ -1776,8 +1776,8 @@ private void ThrowIfReconnectionHasBeenCanceled() private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); @@ -2039,9 +2039,9 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st { // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Command executed as RPC."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Command executed as RPC."); } SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, methodName, completion, timeout, out task, out usedCache, asyncWrite, inRetry); @@ -2097,11 +2097,11 @@ public XmlReader ExecuteXmlReader() SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); bool success = false; int? sqlExceptionNumber = null; @@ -2125,7 +2125,7 @@ public XmlReader ExecuteXmlReader() finally { SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -2142,8 +2142,8 @@ public IAsyncResult BeginExecuteXmlReader() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); SqlConnection.ExecutePermission.Demand(); return BeginExecuteXmlReaderInternal(CommandBehavior.SequentialAccess, callback, stateObject, 0, inRetry: false); @@ -2297,15 +2297,15 @@ public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) } finally { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); } } private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); @@ -2425,8 +2425,8 @@ public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObjec /// override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); return ExecuteReader(behavior, ADP.ExecuteReader); } @@ -2437,11 +2437,11 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); try { @@ -2451,17 +2451,17 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) finally { SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } /// new public SqlDataReader ExecuteReader(CommandBehavior behavior) { - var scopeID = Log.ScopeEnter($" {ObjectID}#, behavior={(int)behavior}"); + var scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, behavior={(int)behavior}"); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {SqlClientEventSource.Log.Guid}"); try { @@ -2469,7 +2469,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -2484,8 +2484,8 @@ public IAsyncResult BeginExecuteReader(CommandBehavior behavior) [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior) { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {SqlClientEventSource.Log.Guid}"); SqlConnection.ExecutePermission.Demand(); return BeginExecuteReaderInternal(behavior, callback, stateObject, 0, inRetry: false); @@ -2568,15 +2568,15 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) } finally { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); } } private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); @@ -2978,8 +2978,8 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string /// public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); SqlConnection.ExecutePermission.Demand(); @@ -3065,8 +3065,8 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b /// new public Task ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {SqlClientEventSource.Log.Guid}"); SqlConnection.ExecutePermission.Demand(); @@ -3201,8 +3201,8 @@ public Task ExecuteXmlReaderAsync() /// public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken) { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); SqlConnection.ExecutePermission.Demand(); @@ -3811,9 +3811,9 @@ private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, b // no data reader is returned // use this overload for "batch SQL" tds token type - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Command executed as SQLBATCH."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Command executed as SQLBATCH."); } Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(this.CommandText, timeout, this.Notification, _stateObj, sync: true); @@ -3877,9 +3877,9 @@ private void RunExecuteNonQuerySmi(bool sendToPipe) SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, cmdBehavior={(int)CommandBehavior.Default}."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, cmdBehavior={(int)CommandBehavior.Default}."); } if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) @@ -5357,9 +5357,9 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // Send over SQL Batch command if we are not a stored proc and have no parameters // MDAC BUG #'s 73776 & 72101 Debug.Assert(!IsUserPrepared, "CommandType.Text with no params should not be prepared!"); - if (returnStream && Log.IsTraceEnabled()) + if (returnStream && SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Command executed as SQLBATCH."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Command executed as SQLBATCH."); } string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior); @@ -5422,9 +5422,9 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // if shiloh, then set NOMETADATA_UNLESSCHANGED flag if (_activeConnection.IsShiloh) rpc.options = TdsEnums.RPC_NOMETADATA; - if (returnStream && Log.IsTraceEnabled()) + if (returnStream && SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Command executed as RPC."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Command executed as RPC."); } // TODO: Medusa: Unprepare only happens for SQL 7.0 which may be broken anyway (it's not re-prepared). Consider removing the reset here if we're really dropping 7.0 support. @@ -5445,9 +5445,9 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // then batch sql them over. This is inefficient (3 round trips) but the only way we can get metadata only from // a stored proc optionSettings = GetSetOptionsString(cmdBehavior); - if (returnStream && Log.IsTraceEnabled()) + if (returnStream && SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Command executed as RPC."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Command executed as RPC."); } // turn set options ON if (null != optionSettings) @@ -5542,9 +5542,9 @@ private SqlDataReader RunExecuteReaderSmi(CommandBehavior cmdBehavior, RunBehavi SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, commandBehavior={(int)cmdBehavior}."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, commandBehavior={(int)cmdBehavior}."); } if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) @@ -5766,9 +5766,9 @@ public SqlCommand Clone() { SqlCommand clone = new SqlCommand(this); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, clone={clone.ObjectID}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, clone={clone.ObjectID}#"); } return clone; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index 8f770267ca..817df214e9 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -10,7 +10,7 @@ using System.Text; using System.Text.RegularExpressions; using Microsoft.Data.Common; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -130,9 +130,9 @@ internal int ObjectID internal void Append(SqlCommand command) { ADP.CheckArgumentNull(command, "command"); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, command={command.ObjectID}, parameterCount={command.Parameters.Count}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, command={command.ObjectID}, parameterCount={command.Parameters.Count}"); } string cmdText = command.CommandText; @@ -268,9 +268,9 @@ internal static void BuildStoredProcedureName(StringBuilder builder, string part internal void Clear() { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#"); } DbCommand batchCommand = BatchCommand; @@ -288,9 +288,9 @@ internal void Clear() internal void Dispose() { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#"); } SqlCommand command = _batchCommand; @@ -308,8 +308,8 @@ internal int ExecuteNonQuery() SqlConnection.ExecutePermission.Demand(); long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); try { @@ -330,7 +330,7 @@ internal int ExecuteNonQuery() } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index 0c2da41cfc..940733b7b2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -28,7 +28,7 @@ using System.Threading.Tasks; using Microsoft.Data.ProviderBase; using Microsoft.Data.SqlClient.Server; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Data.DataSetExtensions, PublicKey=" + Microsoft.Data.SqlClient.AssemblyRef.EcmaPublicKeyFull)] // DevDiv Bugs 92166 @@ -1104,8 +1104,8 @@ public SqlTransaction BeginTransaction(string transactionName) override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#, isolationLevel={(int)isolationLevel}"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, isolationLevel={(int)isolationLevel}"); try { @@ -1122,7 +1122,7 @@ override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLeve } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1133,8 +1133,8 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#, iso={(int)iso}, transactionName='{(ADP.IsEmpty(transactionName) ? "None" : transactionName)}'"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, iso={(int)iso}, transactionName='{(ADP.IsEmpty(transactionName) ? "None" : transactionName)}'"); try { @@ -1162,7 +1162,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); SqlStatistics.StopTimer(statistics); } } @@ -1173,8 +1173,8 @@ override public void ChangeDatabase(string database) SqlStatistics statistics = null; RepairInnerConnection(); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -1269,11 +1269,11 @@ void CloseInnerConnection() override public void Close() { long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); try { @@ -1356,7 +1356,7 @@ override public void Close() { SqlDebugContext sdc = _sdc; _sdc = null; - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); if (sdc != null) { @@ -1411,11 +1411,11 @@ public void EnlistDistributedTransaction(System.EnterpriseServices.ITransaction override public void Open() { long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" ObjectID: {ObjectID}, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" ObjectID: {ObjectID}, ActivityID {SqlClientEventSource.Log.Guid}"); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); try { @@ -1449,7 +1449,7 @@ override public void Open() } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1483,9 +1483,9 @@ private async Task ReconnectAsync(int timeout) { if (ctoken.IsCancellationRequested) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Orginal ClientConnectionID: {_originalConnectionId.ToString()} - reconnection cancelled."); + SqlClientEventSource.Log.Trace($" Orginal ClientConnectionID: {_originalConnectionId.ToString()} - reconnection cancelled."); } return; } @@ -1508,24 +1508,24 @@ private async Task ReconnectAsync(int timeout) ForceNewConnection = false; } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Reconnection suceeded. ClientConnectionID {_originalConnectionId.ToString()} -> {ClientConnectionId.ToString()}"); + SqlClientEventSource.Log.Trace($" Reconnection suceeded. ClientConnectionID {_originalConnectionId.ToString()} -> {ClientConnectionId.ToString()}"); } return; } catch (SqlException e) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Orginal ClientConnectionID {_originalConnectionId} - reconnection attempt failed error {e.Message}"); + SqlClientEventSource.Log.Trace($" Orginal ClientConnectionID {_originalConnectionId} - reconnection attempt failed error {e.Message}"); } if (attempt == retryCount - 1) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Orginal ClientConnectionID {_originalConnectionId.ToString()} - give up reconnection"); + SqlClientEventSource.Log.Trace($" Orginal ClientConnectionID {_originalConnectionId.ToString()} - give up reconnection"); } throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); @@ -1594,9 +1594,9 @@ internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Connection ClientConnectionID {_originalConnectionId.ToString()} is invalid, reconnecting"); + SqlClientEventSource.Log.Trace($" Connection ClientConnectionID {_originalConnectionId.ToString()} is invalid, reconnecting"); } _recoverySessionData = cData; if (beforeDisconnect != null) @@ -1690,11 +1690,11 @@ void CancelOpenAndWait() public override Task OpenAsync(CancellationToken cancellationToken) { long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.PoolerScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.PoolerScopeEnter($" {ObjectID}#"); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); try { @@ -1772,7 +1772,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1793,9 +1793,9 @@ public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource retryTask) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {_parent.ObjectID}#"); + SqlClientEventSource.Log.Trace($" {_parent.ObjectID}#"); } _registration.Dispose(); try @@ -2143,9 +2143,9 @@ internal void OnError(SqlException exception, bool breakConnection, Action {ObjectID}#, Connection broken."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection broken."); } Close(); @@ -2156,9 +2156,9 @@ internal void OnError(SqlException exception, bool breakConnection, Action {ObjectID}#, Connection broken."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection broken."); } Close(); } @@ -2268,9 +2268,9 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) Debug.Assert(null != imevent, "null SqlInfoMessageEventArgs"); var imeventValue = (null != imevent) ? imevent.Message : ""; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Message='{imeventValue}'"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Message='{imeventValue}'"); } SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage]; @@ -2486,11 +2486,11 @@ private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, s public static void ChangePassword(string connectionString, string newPassword) { long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter(""); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter(""); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); try { @@ -2530,7 +2530,7 @@ public static void ChangePassword(string connectionString, string newPassword) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -2538,11 +2538,11 @@ public static void ChangePassword(string connectionString, string newPassword) public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter(""); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter(""); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); try { @@ -2605,7 +2605,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -2711,9 +2711,9 @@ private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) Debug.Assert(TypeSystemAssemblyVersion != null, "TypeSystemAssembly should be set !"); if (string.Compare(asmRef.Name, "Microsoft.SqlServer.Types", StringComparison.OrdinalIgnoreCase) == 0) { - if (asmRef.Version != TypeSystemAssemblyVersion && Log.IsTraceEnabled()) + if (asmRef.Version != TypeSystemAssemblyVersion && SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" SQL CLR type version change: Server sent {asmRef.Version.ToString()}, client will instantiate {TypeSystemAssemblyVersion.ToString()}"); + SqlClientEventSource.Log.Trace($" SQL CLR type version change: Server sent {asmRef.Version.ToString()}, client will instantiate {TypeSystemAssemblyVersion.ToString()}"); } asmRef.Version = TypeSystemAssemblyVersion; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs index bcba61d1ba..88e72daaaf 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs @@ -12,7 +12,7 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; using Microsoft.Data.SqlClient.Server; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -194,9 +194,9 @@ override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions connectionTimeout *= 10; } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($"Set connection pool CreateTimeout={connectionTimeout} when AD Interactive is in use."); + SqlClientEventSource.Log.Trace($"Set connection pool CreateTimeout={connectionTimeout} when AD Interactive is in use."); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs index 7dd791afcd..c0273caf68 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs @@ -4,7 +4,7 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -56,9 +56,9 @@ internal void AliasCheck(string server) } else if (_alias != server) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" alias change detected. Clearing PoolGroup"); + SqlClientEventSource.Log.Trace($" alias change detected. Clearing PoolGroup"); } base.PoolGroup.Clear(); @@ -104,9 +104,9 @@ internal void FailoverCheck(SqlInternalConnection connection, bool actualUseFail if (UseFailoverPartner != actualUseFailoverPartner) { // TODO: will connections in progress somehow be active for two different datasources? - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Failover detected. failover partner='{actualFailoverPartner}'. Clearing PoolGroup"); + SqlClientEventSource.Log.Trace($" Failover detected. failover partner='{actualFailoverPartner}'. Clearing PoolGroup"); } base.PoolGroup.Clear(); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index 0b3adfa9ee..8f1aacb5f6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -8,7 +8,7 @@ using System.Data.Common; using System.Diagnostics; using Microsoft.Data.Common; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -144,9 +144,9 @@ override public int UpdateBatchSize } _updateBatchSize = value; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, {value}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, {value}"); } } } @@ -255,8 +255,8 @@ override protected int ExecuteBatch() { Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls"); return _commandSet.ExecuteNonQuery(); } @@ -280,9 +280,9 @@ override protected bool GetBatchedRecordsAffected(int commandIdentifier, out int /// override protected void InitializeBatching() { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#"); } _commandSet = new SqlCommandSet(); SqlCommand command = SelectCommand; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs index 111fdede85..98a863f625 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -21,7 +21,7 @@ using Microsoft.Data.SqlClient.DataClassification; using Microsoft.Data.SqlClient.Server; using Microsoft.Data.SqlTypes; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -942,8 +942,8 @@ override public void Close() SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); try { @@ -1030,7 +1030,7 @@ override public void Close() finally { SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1676,8 +1676,8 @@ override public DataTable GetSchemaTable() SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); try { @@ -1701,7 +1701,7 @@ override public DataTable GetSchemaTable() finally { SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -3611,8 +3611,8 @@ private bool TryNextResult(out bool more) SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -3790,7 +3790,7 @@ private bool TryNextResult(out bool more) finally { SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -3820,8 +3820,8 @@ private bool TryReadInternal(bool setTimeout, out bool more) SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -4023,7 +4023,7 @@ private bool TryReadInternal(bool setTimeout, out bool more) finally { SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -4488,8 +4488,8 @@ private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateO // broken connection, so check state first. if (parser.State == TdsParserState.OpenLoggedIn) { - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID '{Log.Guid}'"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID '{SqlClientEventSource.Log.Guid}'"); Task executeTask = parser.TdsExecuteSQLBatch(_resetOptionsString, (_command != null) ? _command.CommandTimeout : 0, null, stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -4803,8 +4803,8 @@ private void AssertReaderState(bool requireData, bool permitAsync, int? columnIn public override Task NextResultAsync(CancellationToken cancellationToken) { long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); try { @@ -4850,9 +4850,9 @@ public override Task NextResultAsync(CancellationToken cancellationToken) { if (t != null) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" attempt retry {ObjectID}#"); + SqlClientEventSource.Log.Trace($" attempt retry {ObjectID}#"); } PrepareForAsyncContinuation(); } @@ -4871,7 +4871,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -4935,9 +4935,9 @@ internal Task GetBytesAsync(int i, byte[] buffer, int index, int length, in { if (t != null) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" attempt retry {ObjectID}#"); + SqlClientEventSource.Log.Trace($" attempt retry {ObjectID}#"); } PrepareForAsyncContinuation(); @@ -5111,8 +5111,8 @@ private Task GetBytesAsyncReadDataStage(int i, byte[] buffer, int index, in public override Task ReadAsync(CancellationToken cancellationToken) { long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); try { @@ -5233,9 +5233,9 @@ public override Task ReadAsync(CancellationToken cancellationToken) { if (t != null) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" attempt retry {ObjectID}#"); + SqlClientEventSource.Log.Trace($" attempt retry {ObjectID}#"); } PrepareForAsyncContinuation(); @@ -5276,7 +5276,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs index d9822a292d..b125223dbb 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs @@ -15,7 +15,7 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; using Microsoft.Data.SqlClient.Server; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + using Microsoft.Data.SqlTypes; @@ -377,8 +377,8 @@ public override void Close() private void CloseInternal(bool closeConnection) { long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); bool processFinallyBlock = true; try @@ -415,7 +415,7 @@ private void CloseInternal(bool closeConnection) Connection.Close(); } - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } } @@ -439,8 +439,8 @@ public override Task NextResultAsync(CancellationToken cancellationToken) internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) { long scopeID = 0; - if (Log.IsAdvanceTraceOn()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); try { _hasRows = false; @@ -473,8 +473,8 @@ internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) } finally { - if (Log.IsAdvanceTraceOn()) - Log.ScopeLeave(scopeID); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -495,8 +495,8 @@ public override Task ReadAsync(CancellationToken cancellationToken) internal unsafe bool InternalRead(bool ignoreNonFatalErrors) { long scopeID = 0; - if (Log.IsAdvanceTraceOn()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); try { @@ -536,8 +536,8 @@ internal unsafe bool InternalRead(bool ignoreNonFatalErrors) } finally { - if (Log.IsAdvanceTraceOn()) - Log.ScopeLeave(scopeID); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1329,16 +1329,16 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs { var mdLength = (null != md) ? md.Length : -1; - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {reader.ObjectID}#, md.Length={mdLength} nextEventIsRow={nextEventIsRow}."); + SqlClientEventSource.Log.Trace($" {reader.ObjectID}#, md.Length={mdLength} nextEventIsRow={nextEventIsRow}."); if (null != md) { for (int i = 0; i < md.Length; i++) { - Log.Trace($" {reader.ObjectID}#, metaData[{i}] is {md[i].GetType().ToString()}{md[i].TraceString()}"); + SqlClientEventSource.Log.Trace($" {reader.ObjectID}#, metaData[{i}] is {md[i].GetType().ToString()}{md[i].TraceString()}"); } } } @@ -1348,36 +1348,36 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs // Obsolete V2- method internal override void RowAvailable(ITypedGetters row) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {reader.ObjectID}# (v2)."); + SqlClientEventSource.Log.Trace($" {reader.ObjectID}# (v2)."); } this.reader.RowAvailable(row); } internal override void RowAvailable(ITypedGettersV3 row) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {reader.ObjectID}# (ITypedGettersV3)."); + SqlClientEventSource.Log.Trace($" {reader.ObjectID}# (ITypedGettersV3)."); } this.reader.RowAvailable(row); } internal override void RowAvailable(SmiTypedGetterSetter rowData) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {reader.ObjectID}# (SmiTypedGetterSetter)."); + SqlClientEventSource.Log.Trace($" {reader.ObjectID}# (SmiTypedGetterSetter)."); } this.reader.RowAvailable(rowData); } internal override void StatementCompleted(int recordsAffected) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {reader.ObjectID}# recordsAffected= {recordsAffected}."); + SqlClientEventSource.Log.Trace($" {reader.ObjectID}# recordsAffected= {recordsAffected}."); } // devnote: relies on SmiEventSink_Default to pass event to parent @@ -1389,9 +1389,9 @@ internal override void StatementCompleted(int recordsAffected) internal override void BatchCompleted() { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {reader.ObjectID}#."); + SqlClientEventSource.Log.Trace($" {reader.ObjectID}#."); } // devnote: relies on SmiEventSink_Default to pass event to parent diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs index e69977d465..61df7c5d73 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs @@ -8,7 +8,7 @@ using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Data.Common; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + using SysTx = System.Transactions; namespace Microsoft.Data.SqlClient @@ -89,9 +89,9 @@ public void Initialize() // transaction. SqlInternalConnection connection = _connection; SqlConnection usersConnection = connection.Connection; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, delegating transaction."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, delegating transaction."); } RuntimeHelpers.PrepareConstrainedRegions(); @@ -108,9 +108,9 @@ public void Initialize() #endif //DEBUG if (connection.IsEnlistedInTransaction) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, was enlisted, now defecting."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, was enlisted, now defecting."); } // defect first @@ -173,9 +173,9 @@ public Byte[] Promote() byte[] returnValue = null; SqlConnection usersConnection = connection.Connection; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, promoting transaction."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, promoting transaction."); } RuntimeHelpers.PrepareConstrainedRegions(); @@ -275,9 +275,9 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) SqlInternalConnection connection = GetValidConnection(); SqlConnection usersConnection = connection.Connection; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, aborting transaction."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, aborting transaction."); } RuntimeHelpers.PrepareConstrainedRegions(); @@ -371,9 +371,9 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) SqlInternalConnection connection = GetValidConnection(); SqlConnection usersConnection = connection.Connection; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, committing transaction."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, committing transaction."); } RuntimeHelpers.PrepareConstrainedRegions(); @@ -504,9 +504,9 @@ internal void TransactionEnded(SysTx.Transaction transaction) if (connection != null) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, transaction completed externally."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, transaction completed externally."); } lock (connection) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs index b5c2477e81..3823242f77 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -18,7 +18,7 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; using Microsoft.Data.Sql; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -318,8 +318,8 @@ public SqlDependency(SqlCommand command) : this(command, null, SQL.SqlDependency public SqlDependency(SqlCommand command, string options, int timeout) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, options: '{options}', timeout: '{timeout}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, options: '{options}', timeout: '{timeout}'"); try { @@ -343,7 +343,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -441,8 +441,8 @@ public event OnChangeEventHandler OnChange add { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { if (null != value) @@ -454,15 +454,15 @@ public event OnChangeEventHandler OnChange if (_dependencyFired) { // If fired, fire the new event immediately. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Dependency already fired, firing new event."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Dependency already fired, firing new event."); sqlNotificationEvent = new SqlNotificationEventArgs(SqlNotificationType.Subscribe, SqlNotificationInfo.AlreadyChanged, SqlNotificationSource.Client); } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Dependency has not fired, adding new event."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Dependency has not fired, adding new event."); EventContextPair pair = new EventContextPair(value, this); if (!_eventList.Contains(pair)) @@ -484,14 +484,14 @@ public event OnChangeEventHandler OnChange } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } remove { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { if (null != value) @@ -509,7 +509,7 @@ public event OnChangeEventHandler OnChange } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } } @@ -527,8 +527,8 @@ public void AddCommandDependency(SqlCommand command) // Adds command to dependency collection so we automatically create the SqlNotificationsRequest object // and listen for a notification for the added commands. long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { @@ -541,7 +541,7 @@ public void AddCommandDependency(SqlCommand command) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -567,12 +567,12 @@ private static void ObtainProcessDispatcher() if (nativeStorage == null) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher."); #if DEBUG // Possibly expensive, limit to debug. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); #endif _AppDomain masterDomain = SNINativeMethodWrapper.GetDefaultAppDomain(); @@ -597,43 +597,43 @@ private static void ObtainProcessDispatcher() } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" ERROR - ObjectHandle.Unwrap returned null!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" ERROR - ObjectHandle.Unwrap returned null!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyObtainProcessDispatcherFailureObjectHandle); } } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureCreateInstance); } } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - unable to obtain default AppDomain!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - unable to obtain default AppDomain!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureAppDomain); } } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher."); #if DEBUG // Possibly expensive, limit to debug. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); #endif BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(nativeStorage); _processDispatcher = GetDeserializedObject(formatter, stream); // Deserialize and set for appdomain. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" processDispatcher obtained, ID: {_processDispatcher.ObjectID}"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" processDispatcher obtained, ID: {_processDispatcher.ObjectID}"); } } @@ -681,8 +681,8 @@ public static bool Start(string connectionString, string queue) internal static bool Start(string connectionString, string queue, bool useDefaults) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -755,8 +755,8 @@ internal static bool Start(string connectionString, string queue, bool useDefaul SqlDependencyPerAppDomainDispatcher.SingletonInstance, out errorOccurred, out appDomainStart); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Start (defaults) returned: '{result}', with service: '{service}', server: '{server}', database: '{database}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Start (defaults) returned: '{result}', with service: '{service}', server: '{server}', database: '{database}'"); } finally { @@ -779,8 +779,8 @@ internal static bool Start(string connectionString, string queue, bool useDefaul ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" Exception occurred from Stop() after duplicate was found on Start()."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" Exception occurred from Stop() after duplicate was found on Start()."); } throw SQL.SqlDependencyDuplicateStart(); } @@ -793,8 +793,8 @@ internal static bool Start(string connectionString, string queue, bool useDefaul queue, _appDomainKey, SqlDependencyPerAppDomainDispatcher.SingletonInstance); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Start (user provided queue) returned: '{result}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Start (user provided queue) returned: '{result}'"); // No need to call AddToServerDatabaseHash since if not using default queue user is required // to provide options themselves. @@ -809,8 +809,8 @@ internal static bool Start(string connectionString, string queue, bool useDefaul ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); throw; } @@ -820,7 +820,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -841,8 +841,8 @@ public static bool Stop(string connectionString, string queue) internal static bool Stop(string connectionString, string queue, bool useDefaults, bool startFailed) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -952,7 +952,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -963,8 +963,8 @@ internal static bool Stop(string connectionString, string queue, bool useDefault private static bool AddToServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); try { bool result = false; @@ -975,8 +975,8 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!_serverUserHash.ContainsKey(server)) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" Hash did not contain server, adding."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" Hash did not contain server, adding."); identityDatabaseHash = new Dictionary>(); _serverUserHash.Add(server, identityDatabaseHash); @@ -990,8 +990,8 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!identityDatabaseHash.ContainsKey(identityUser)) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" Hash contained server but not user, adding user."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" Hash contained server but not user, adding user."); databaseServiceList = new List(); identityDatabaseHash.Add(identityUser, databaseServiceList); @@ -1003,14 +1003,14 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!databaseServiceList.Contains(databaseService)) { - Log.NotificationsTrace(" Adding database.\n"); + SqlClientEventSource.Log.NotificationsTrace(" Adding database.\n"); databaseServiceList.Add(databaseService); result = true; } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - hash already contained server, user, and database - we will throw!."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash already contained server, user, and database - we will throw!."); } } @@ -1018,15 +1018,15 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } private static void RemoveFromServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); try { lock (_serverUserHash) @@ -1046,22 +1046,22 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair int index = databaseServiceList.IndexOf(databaseService); if (index >= 0) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" Hash contained server, user, and database - removing database."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" Hash contained server, user, and database - removing database."); databaseServiceList.RemoveAt(index); if (databaseServiceList.Count == 0) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" databaseServiceList count 0, removing the list for this server and user."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" databaseServiceList count 0, removing the list for this server and user."); identityDatabaseHash.Remove(identityUser); if (identityDatabaseHash.Count == 0) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" identityDatabaseHash count 0, removing the hash for this server."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" identityDatabaseHash count 0, removing the hash for this server."); _serverUserHash.Remove(server); } @@ -1069,24 +1069,24 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - hash contained server and user but not database!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash contained server and user but not database!"); Debug.Assert(false, "Unexpected state - hash did not contain database!"); } } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - hash contained server but not user!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash contained server but not user!"); Debug.Assert(false, "Unexpected state - hash did not contain user!"); } } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - hash did not contain server!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash did not contain server!"); Debug.Assert(false, "Unexpected state - hash did not contain server!"); } @@ -1094,7 +1094,7 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1103,8 +1103,8 @@ internal static string GetDefaultComposedOptions(string server, string failoverS // Server must be an exact match, but user and database only needs to match exactly if there is more than one // for the given user or database passed. That is ambiguious and we must fail. long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" server: '{server}', failoverServer: '{failoverServer}', database: '{database}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" server: '{server}', failoverServer: '{failoverServer}', database: '{database}'"); try { @@ -1117,20 +1117,20 @@ internal static string GetDefaultComposedOptions(string server, string failoverS if (0 == _serverUserHash.Count) { // Special error for no calls to start. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - no start calls have been made, about to throw."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - no start calls have been made, about to throw."); throw SQL.SqlDepDefaultOptionsButNoStart(); } else if (!ADP.IsEmpty(failoverServer) && _serverUserHash.ContainsKey(failoverServer)) { - Log.NotificationsTrace(" using failover server instead\n"); + SqlClientEventSource.Log.NotificationsTrace(" using failover server instead\n"); server = failoverServer; } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - not listening to this server, about to throw."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - not listening to this server, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } } @@ -1143,8 +1143,8 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { if (identityDatabaseHash.Count > 1) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - not listening for this user, " + + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - not listening for this user, " + "but listening to more than one other user, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } @@ -1192,8 +1192,8 @@ internal static string GetDefaultComposedOptions(string server, string failoverS else { // More than one database for given server, ambiguous - fail the default case! - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); throw SQL.SqlDependencyNoMatchingServerDatabaseStart(); } @@ -1201,14 +1201,14 @@ internal static string GetDefaultComposedOptions(string server, string failoverS } Debug.Assert(!ADP.IsEmpty(result), "GetDefaultComposedOptions should never return null or empty string!"); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" resulting options: '{result}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" resulting options: '{result}'."); return result; } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1221,8 +1221,8 @@ internal static string GetDefaultComposedOptions(string server, string failoverS internal void AddToServerList(string server) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); try { lock (_serverList) @@ -1230,8 +1230,8 @@ internal void AddToServerList(string server) int index = _serverList.BinarySearch(server, StringComparer.OrdinalIgnoreCase); if (0 > index) { // If less than 0, item was not found in list. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Server not present in hashtable, adding server: '{server}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Server not present in hashtable, adding server: '{server}'."); index = ~index; // BinarySearch returns the 2's compliment of where the item should be inserted to preserver a sorted list after insertion. _serverList.Insert(index, server); @@ -1241,7 +1241,7 @@ internal void AddToServerList(string server) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1256,8 +1256,8 @@ internal bool ContainsServer(string server) internal string ComputeHashAndAddToDispatcher(SqlCommand command) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); try { // Create a string representing the concatenation of the connection string, command text and .ToString on all parameter values. @@ -1272,21 +1272,21 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) string commandHash = ComputeCommandHash(command.Connection.ConnectionString, command); // calculate the string representation of command string idString = SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddCommandEntry(commandHash, this); // Add to map. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" computed id string: '{idString}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" computed id string: '{idString}'."); return idString; } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { @@ -1305,15 +1305,15 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql // raises Timeout event but before removing this event from the list. If notification is received from // server in this case, we will hit this code path. // It is safe to ignore this race condition because no event is sent to user and no leak happens. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ignore notification received after timeout!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ignore notification received after timeout!"); } else { Debug.Assert(false, "Received notification twice - we should never enter this state!"); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - notification received twice - we should never enter this state!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - notification received twice - we should never enter this state!"); } } else @@ -1327,8 +1327,8 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (eventList != null) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" Firing events."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" Firing events."); foreach (EventContextPair pair in eventList) { @@ -1338,7 +1338,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1346,14 +1346,14 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql internal void StartTimer(SqlNotificationRequest notificationRequest) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { if (_expirationTime == DateTime.MaxValue) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" We've timed out, executing logic."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" We've timed out, executing logic."); int seconds = SQL.SqlDependencyServerTimeout; if (0 != _timeout) @@ -1372,7 +1372,7 @@ internal void StartTimer(SqlNotificationRequest notificationRequest) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1386,8 +1386,8 @@ private void AddCommandInternal(SqlCommand cmd) { // Don't bother with BID if command null. long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {cmd.ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {cmd.ObjectID}#"); try { @@ -1398,8 +1398,8 @@ private void AddCommandInternal(SqlCommand cmd) // Fail if cmd has notification that is not already associated with this dependency. if (cmd._sqlDep == null || cmd._sqlDep != this) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception."); throw SQL.SqlCommandHasExistingSqlNotificationRequest(); } @@ -1432,8 +1432,8 @@ private void AddCommandInternal(SqlCommand cmd) if (0 == _eventList.Count) { // Keep logic just in case. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point."); needToInvalidate = true; // Delay invalidation until outside of lock. } } @@ -1447,7 +1447,7 @@ private void AddCommandInternal(SqlCommand cmd) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } } @@ -1455,8 +1455,8 @@ private void AddCommandInternal(SqlCommand cmd) private string ComputeCommandHash(string connectionString, SqlCommand command) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); try { // Create a string representing the concatenation of the connection string, the command text and .ToString on all its parameter values. @@ -1514,14 +1514,14 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) string result = builder.ToString(); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" ComputeCommandHash result: '{result}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" ComputeCommandHash result: '{result}'."); return result; } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index 69886bcd07..ae8cfeb231 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -17,7 +17,7 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; using Microsoft.Data.SqlClient; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + // This class is the process wide dependency dispatcher. It contains all connection listeners for the entire process and // receives notifications on those connections to dispatch to the corresponding AppDomain dispatcher to notify the @@ -81,8 +81,8 @@ internal int ObjectID internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, queue: '{hashHelper.Queue}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, queue: '{hashHelper.Queue}'"); bool setupCompleted = false; @@ -107,8 +107,8 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(_hashHelper.ConnectionStringBuilder.ConnectionString); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); #endif // Always use ConnectionStringBuilder since in default case it is different from the @@ -223,7 +223,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -284,8 +284,8 @@ internal string Server internal bool AppDomainUnload(string appDomainKey) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, AppDomainKey: '{ appDomainKey}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, AppDomainKey: '{ appDomainKey}'"); try { @@ -298,13 +298,13 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { // Do nothing if AppDomain did not call Start! - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}'."); int value = _appDomainKeyHash[appDomainKey]; - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{appDomainKey}' count: '{value}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{appDomainKey}' count: '{value}'."); Debug.Assert(value > 0, "Why is value 0 or less?"); @@ -322,33 +322,33 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{appDomainKey}' entry not removed from hash. Count: {_appDomainKeyHash[appDomainKey]}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{appDomainKey}' entry not removed from hash. Count: {_appDomainKeyHash[appDomainKey]}'"); } } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}'."); } } - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{_stopped}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{_stopped}'."); return _stopped; } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } private void AsynchronouslyQueryServiceBrokerQueue() { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { @@ -357,15 +357,15 @@ private void AsynchronouslyQueryServiceBrokerQueue() } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } private void AsyncResultCallback(IAsyncResult asyncResult) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { using (SqlDataReader reader = _com.EndExecuteReader(asyncResult)) @@ -392,8 +392,8 @@ private void AsyncResultCallback(IAsyncResult asyncResult) throw; } - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Exception occurred."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Exception occurred."); if (!_stop) { // Only assert if not in cancel path. @@ -413,15 +413,15 @@ private void AsyncResultCallback(IAsyncResult asyncResult) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } private void CreateQueueAndService(bool restart) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { SqlCommand com = new SqlCommand(); @@ -551,22 +551,22 @@ private void CreateQueueAndService(bool restart) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { appDomainStart = false; // Reset out param. int result = Interlocked.Increment(ref _startCount); // Add to refCount. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> {_staticInstance.ObjectID}#, incremented _startCount: {result}"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> {_staticInstance.ObjectID}#, incremented _startCount: {result}"); // Dictionary used to track how many times start has been called per app domain. // For each increment, add to count, and create entry if not present. @@ -576,30 +576,30 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { _appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1; - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', incremented count: '{_appDomainKeyHash[appDomainKey]}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', incremented count: '{_appDomainKeyHash[appDomainKey]}'."); } else { _appDomainKeyHash[appDomainKey] = 1; appDomainStart = true; - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}', added to hashtable and value set to 1."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}', added to hashtable and value set to 1."); } } } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } private void ProcessNotificationResults(SqlDataReader reader) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { Guid handle = Guid.Empty; // Conversation_handle. Always close this! @@ -609,23 +609,23 @@ private void ProcessNotificationResults(SqlDataReader reader) { while (reader.Read()) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Row read."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Row read."); #if DEBUG for (int i = 0; i < reader.FieldCount; i++) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" column: {reader.GetName(i)}, value: {reader.GetValue(i).ToString()}"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" column: {reader.GetName(i)}, value: {reader.GetValue(i).ToString()}"); } #endif string msgType = reader.GetString(0); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" msgType: '{ msgType}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" msgType: '{ msgType}'"); handle = reader.GetGuid(1); - // SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.ProcessNotificationResults(SqlDataReader)|DEP> conversationHandle: '%p(GUID)'", conversationHandle); + // SqlClientEventSource.SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.ProcessNotificationResults(SqlDataReader)|DEP> conversationHandle: '%p(GUID)'", conversationHandle); // Only process QueryNotification messages. if (0 == String.Compare(msgType, "http://schemas.microsoft.com/SQL/Notifications/QueryNotification", StringComparison.OrdinalIgnoreCase)) @@ -638,8 +638,8 @@ private void ProcessNotificationResults(SqlDataReader reader) { string key = notification.Key; - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Key: '{key}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Key: '{key}'"); int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash" @@ -670,32 +670,32 @@ private void ProcessNotificationResults(SqlDataReader reader) { Debug.Assert(false, "Received notification but do not have an associated PerAppDomainDispatcher!"); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Received notification but do not have an associated PerAppDomainDispatcher!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Received notification but do not have an associated PerAppDomainDispatcher!"); } } else { Debug.Assert(false, "Unexpected ID format received!"); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Unexpected ID format received!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Unexpected ID format received!"); } } else { Debug.Assert(false, "Null notification returned from ProcessMessage!"); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Null notification returned from ProcessMessage!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Null notification returned from ProcessMessage!"); } } else { Debug.Assert(false, "Null payload for QN notification type!"); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Null payload for QN notification type!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Null payload for QN notification type!"); } } else @@ -704,8 +704,8 @@ private void ProcessNotificationResults(SqlDataReader reader) // VSDD 546707: this assert was hit by SQL Notification fuzzing tests, disable it to let these tests run on Debug bits // Debug.Assert(false, "Unexpected message format received!"); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Unexpected message format received!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Unexpected message format received!"); } } } @@ -737,7 +737,7 @@ private void ProcessNotificationResults(SqlDataReader reader) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -749,8 +749,8 @@ private void Restart(object unused) { // Unused arg required by TimerCallback. long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { try @@ -912,15 +912,15 @@ private void Restart(object unused) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } internal bool Stop(string appDomainKey, out bool appDomainStop) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { appDomainStop = false; @@ -941,8 +941,8 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) Debug.Assert(value > 0, "Unexpected count for appDomainKey"); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', pre-decrement Count: '{value}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', pre-decrement Count: '{value}'."); if (value > 0) { @@ -950,8 +950,8 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" ERROR pre-decremented count <= 0!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" ERROR pre-decremented count <= 0!"); Debug.Assert(false, "Unexpected AppDomainKey count in Stop()"); } @@ -964,8 +964,8 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" ERROR appDomainKey not null and not found in hash!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" ERROR appDomainKey not null and not found in hash!"); Debug.Assert(false, "Unexpected state on Stop() - no AppDomainKey entry in hashtable!"); } @@ -979,8 +979,8 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) { // If we've reached refCount 0, destroy. // Lock to ensure Cancel() complete prior to other thread calling TearDown. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Reached 0 count, cancelling and waiting."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Reached 0 count, cancelling and waiting."); lock (this) { @@ -1024,8 +1024,8 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) // TearDownAndDispose in the maximum retry period case as well as in the _errorState case. if (_errorState || retryStopwatch.Elapsed.Seconds >= 30) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" forcing cleanup. elapsedSeconds: '{retryStopwatch.Elapsed.Seconds}', _errorState: '{_errorState}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" forcing cleanup. elapsedSeconds: '{retryStopwatch.Elapsed.Seconds}', _errorState: '{_errorState}'."); Timer retryTimer = _retryTimer; _retryTimer = null; @@ -1045,8 +1045,8 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" _startCount not 0 after decrement. _startCount: '{_startCount}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" _startCount not 0 after decrement. _startCount: '{_startCount}'."); } Debug.Assert(0 <= _startCount, "Invalid start count state"); @@ -1055,15 +1055,15 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } private void SynchronouslyQueryServiceBrokerQueue() { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { @@ -1074,7 +1074,7 @@ private void SynchronouslyQueryServiceBrokerQueue() } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1082,8 +1082,8 @@ private void SynchronouslyQueryServiceBrokerQueue() private void TearDownAndDispose() { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { lock (this) @@ -1156,7 +1156,7 @@ private void TearDownAndDispose() } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } } @@ -1301,9 +1301,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) { ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace. - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Exception thrown - Enum.Parse failed to parse the value '{xmlReader.Value}' of the attribute '{xmlReader.LocalName}'."); + SqlClientEventSource.Log.Trace($" Exception thrown - Enum.Parse failed to parse the value '{xmlReader.Value}' of the attribute '{xmlReader.LocalName}'."); } return null; } @@ -1311,9 +1311,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) if (MessageAttributes.All != messageAttributes) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Not all expected attributes in Message; messageAttributes = '{(int)messageAttributes}'."); + SqlClientEventSource.Log.Trace($" Not all expected attributes in Message; messageAttributes = '{(int)messageAttributes}'."); } return null; } @@ -1321,9 +1321,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the "Message" node. if (!xmlReader.Read()) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1331,9 +1331,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Verify state after Read(). if ((XmlNodeType.Element != xmlReader.NodeType) || (0 != string.Compare(xmlReader.LocalName, MessageNode, StringComparison.OrdinalIgnoreCase))) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1341,9 +1341,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the Text Node. if (!xmlReader.Read()) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1351,9 +1351,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Verify state after Read(). if (xmlReader.NodeType != XmlNodeType.Text) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1364,9 +1364,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the Text Node. if (!xmlMessageReader.Read()) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1378,9 +1378,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1390,9 +1390,9 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); } return null; // failure } @@ -1575,21 +1575,21 @@ private SqlDependencyProcessDispatcher(object dummyVariable) Debug.Assert(null == _staticInstance, "Real constructor called with static instance already created!"); long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { #if DEBUG // Possibly expensive, limit to debug. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); #endif _connectionContainers = new Dictionary(); _sqlDependencyPerAppDomainDispatchers = new Dictionary(); } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1598,20 +1598,20 @@ private SqlDependencyProcessDispatcher(object dummyVariable) public SqlDependencyProcessDispatcher() { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { // Empty constructor and object - dummy to obtain singleton. #if DEBUG // Possibly expensive, limit to debug. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); #endif } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1638,8 +1638,8 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS string queue) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {_staticInstance.ObjectID}#, queue: {queue}"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {_staticInstance.ObjectID}#, queue: {queue}"); try { @@ -1673,7 +1673,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1686,8 +1686,8 @@ public override object InitializeLifetimeService() private void Invalidate(string server, SqlNotification sqlNotification) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, server: {server}"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, server: {server}"); try { @@ -1720,7 +1720,7 @@ private void Invalidate(string server, SqlNotification sqlNotification) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1738,8 +1738,8 @@ internal void QueueAppDomainUnloading(string appDomainKey) private void AppDomainUnloading(object state) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { @@ -1772,7 +1772,7 @@ private void AppDomainUnloading(object state) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1840,8 +1840,8 @@ private bool Start(string connectionString, bool useDefaults) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, queue: '{ queueService}', appDomainKey: '{appDomainKey}', perAppDomainDispatcher ID: '{dispatcher.ObjectID}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, queue: '{ queueService}', appDomainKey: '{appDomainKey}', perAppDomainDispatcher ID: '{dispatcher.ObjectID}'"); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1869,8 +1869,8 @@ private bool Start(string connectionString, #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); #endif bool started = false; @@ -1880,8 +1880,8 @@ private bool Start(string connectionString, { if (!_connectionContainers.ContainsKey(hashHelper)) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" {ObjectID}#, hashtable miss, creating new container."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, hashtable miss, creating new container."); container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults); _connectionContainers.Add(hashHelper, container); @@ -1891,11 +1891,11 @@ private bool Start(string connectionString, else { container = _connectionContainers[hashHelper]; - Log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}"); + SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}"); if (container.InErrorState) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" {ObjectID}#, container: {container.ObjectID} is in error state!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, container: {container.ObjectID} is in error state!"); errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start(). } @@ -1912,18 +1912,18 @@ private bool Start(string connectionString, database = container.Database; queueService = container.Queue; - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" {ObjectID}#, default service: '{queueService}', server: '{server}', database: '{database}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, default service: '{queueService}', server: '{server}', database: '{database}'"); } - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" {ObjectID}#, started: {started}"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, started: {started}"); return started; } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1941,8 +1941,8 @@ internal bool Stop(string connectionString, out bool appDomainStop) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, queue: '{queueService}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, queue: '{queueService}'"); try { @@ -1962,8 +1962,8 @@ internal bool Stop(string connectionString, #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); #endif bool stopped = false; @@ -1974,8 +1974,8 @@ internal bool Stop(string connectionString, { SqlConnectionContainer container = _connectionContainers[hashHelper]; - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}"); server = container.Server; // Return server, database, and queue info for use by calling SqlDependency. database = container.Database; @@ -1988,19 +1988,19 @@ internal bool Stop(string connectionString, } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" {ObjectID}#, hashtable miss."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, hashtable miss."); } } - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" %d#, stopped: {stopped}"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" %d#, stopped: {stopped}"); return stopped; } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs index 8d26f9f4dd..e282469cbb 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs @@ -7,7 +7,7 @@ using System.Diagnostics; using System.Threading; using Microsoft.Data.Common; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -94,8 +94,8 @@ internal int ObjectID private SqlDependencyPerAppDomainDispatcher() { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { @@ -110,7 +110,7 @@ private SqlDependencyPerAppDomainDispatcher() } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -129,8 +129,8 @@ public override object InitializeLifetimeService() private void UnloadEventHandler(object sender, EventArgs e) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); try { // Make non-blocking call to ProcessDispatcher to ThreadPool.QueueUserWorkItem to complete @@ -145,7 +145,7 @@ private void UnloadEventHandler(object sender, EventArgs e) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -157,8 +157,8 @@ private void UnloadEventHandler(object sender, EventArgs e) internal void AddDependencyEntry(SqlDependency dep) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); try { lock (this) @@ -168,7 +168,7 @@ internal void AddDependencyEntry(SqlDependency dep) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -178,8 +178,8 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) string notificationId = string.Empty; long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{commandHash}', SqlDependency: {dep.ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{commandHash}', SqlDependency: {dep.ObjectID}#"); try { @@ -188,8 +188,8 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) if (!_dependencyIdToDependencyHash.ContainsKey(dep.Id)) { // Determine if depId->dep hashtable contains dependency. If not, it's been invalidated. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Dependency not present in depId->dep hash, must have been invalidated."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Dependency not present in depId->dep hash, must have been invalidated."); } else { @@ -210,15 +210,15 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // join the new dependency to the list if (!dependencyList.Contains(dep)) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Dependency not present for commandHash, adding."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Dependency not present for commandHash, adding."); dependencyList.Add(dep); } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Dependency already present for commandHash."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Dependency already present for commandHash."); } } else @@ -233,8 +233,8 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) Guid.NewGuid().ToString("D", System.Globalization.CultureInfo.InvariantCulture) ); - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Creating new Dependencies list for commandHash."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Creating new Dependencies list for commandHash."); DependencyList dependencyList = new DependencyList(commandHash); dependencyList.Add(dep); @@ -257,7 +257,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } return notificationId; @@ -267,8 +267,8 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) internal void InvalidateCommandID(SqlNotification sqlNotification) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{sqlNotification.Key}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{sqlNotification.Key}'"); try { @@ -280,8 +280,8 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) if (null != dependencyList) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" commandHash found in hashtable."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" commandHash found in hashtable."); foreach (SqlDependency dependency in dependencyList) { @@ -294,8 +294,8 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" commandHash NOT found in hashtable."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" commandHash NOT found in hashtable."); } } @@ -304,8 +304,8 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) // After removal from hashtables, invalidate. foreach (SqlDependency dependency in dependencyList) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Dependency found in commandHash dependency ArrayList - calling invalidate."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Dependency found in commandHash dependency ArrayList - calling invalidate."); try { @@ -327,7 +327,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -335,8 +335,8 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) internal void InvalidateServer(string server, SqlNotification sqlNotification) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); try { @@ -384,7 +384,7 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -392,8 +392,8 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) internal SqlDependency LookupDependencyEntry(string id) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, Key: '{id}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, Key: '{id}'"); try { @@ -416,8 +416,8 @@ internal SqlDependency LookupDependencyEntry(string id) } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" ERROR - dependency ID mismatch - not throwing."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" ERROR - dependency ID mismatch - not throwing."); } } @@ -425,7 +425,7 @@ internal SqlDependency LookupDependencyEntry(string id) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -433,8 +433,8 @@ internal SqlDependency LookupDependencyEntry(string id) private void LookupDependencyEntryWithRemove(string id) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, id: '{id}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, id: '{id}'"); try { @@ -442,8 +442,8 @@ private void LookupDependencyEntryWithRemove(string id) { if (_dependencyIdToDependencyHash.ContainsKey(id)) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Entry found in hashtable - removing."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Entry found in hashtable - removing."); _dependencyIdToDependencyHash.Remove(id); @@ -456,14 +456,14 @@ private void LookupDependencyEntryWithRemove(string id) } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Entry NOT found in hashtable."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Entry NOT found in hashtable."); } } } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -471,8 +471,8 @@ private void LookupDependencyEntryWithRemove(string id) private List LookupCommandEntryWithRemove(string notificationId) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{notificationId}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{notificationId}'"); try { DependencyList entry = null; @@ -481,8 +481,8 @@ private List LookupCommandEntryWithRemove(string notificationId) { if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry)) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Entries found in hashtable - removing."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Entries found in hashtable - removing."); // update the tables - do it inside finally block to avoid ThreadAbort exception interrupt this operation try @@ -496,8 +496,8 @@ private List LookupCommandEntryWithRemove(string notificationId) } else { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Entries NOT found in hashtable."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Entries NOT found in hashtable."); } Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!"); @@ -507,7 +507,7 @@ private List LookupCommandEntryWithRemove(string notificationId) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -515,8 +515,8 @@ private List LookupCommandEntryWithRemove(string notificationId) private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency dependency) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dependency.ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dependency.ObjectID}#"); try { lock (this) @@ -529,8 +529,8 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende DependencyList dependencies = entry.Value; if (dependencies.Remove(dependency)) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Removed SqlDependency: {dependency.ObjectID}#, with ID: '{dependency.Id}'."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Removed SqlDependency: {dependency.ObjectID}#, with ID: '{dependency.Id}'."); if (dependencies.Count == 0) { @@ -564,7 +564,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -575,8 +575,8 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende internal void StartTimer(SqlDependency dep) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); try { // If this dependency expires sooner than the current next timeout, change @@ -587,8 +587,8 @@ internal void StartTimer(SqlDependency dep) // Enable the timer if needed (disable when empty, enable on the first addition). if (!_SqlDependencyTimeOutTimerStarted) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Timer not yet started, starting."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Timer not yet started, starting."); _timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */); @@ -598,8 +598,8 @@ internal void StartTimer(SqlDependency dep) } else if (_nextTimeout > dep.ExpirationTime) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" Timer already started, resetting time."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" Timer already started, resetting time."); // Save this as the earlier timeout to come. _nextTimeout = dep.ExpirationTime; @@ -608,15 +608,15 @@ internal void StartTimer(SqlDependency dep) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } private static void TimeoutTimerCallback(object state) { long scopeID = 0; - if (Log.IsNotificationTraceEnabled()) - scopeID = Log.NotificationsScopeEnter($" AppDomainKey: '{SqlDependency.AppDomainKey}'"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" AppDomainKey: '{SqlDependency.AppDomainKey}'"); try { SqlDependency[] dependencies; @@ -629,14 +629,14 @@ private static void TimeoutTimerCallback(object state) if (0 == SingletonInstance._dependencyIdToDependencyHash.Count) { // Nothing to check. - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" No dependencies, exiting."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" No dependencies, exiting."); return; } if (SingletonInstance._nextTimeout > DateTime.UtcNow) { - if (Log.IsNotificationTraceEnabled()) - Log.NotificationsTrace($" No timeouts expired, exiting."); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + SqlClientEventSource.Log.NotificationsTrace($" No timeouts expired, exiting."); // No dependency timed-out yet. return; @@ -707,7 +707,7 @@ private static void TimeoutTimerCallback(object state) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs index de8c84486d..55ecb6550d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs @@ -3,7 +3,7 @@ // See the LICENSE file in the project root for more information. using System; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -42,9 +42,9 @@ internal SqlError(int infoNumber, byte errorState, byte errorClass, string serve this.lineNumber = lineNumber; if (errorClass != 0) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" infoNumber={infoNumber}, errorState={(int)errorState}, errorClass={(int)errorClass}, errorMessage='{errorMessage}', procedure='{procedure ?? "None"}', lineNumber={(int)lineNumber}"); + SqlClientEventSource.Log.Trace($" infoNumber={infoNumber}, errorState={(int)errorState}, errorClass={(int)errorClass}, errorMessage='{errorMessage}', procedure='{procedure ?? "None"}', lineNumber={(int)lineNumber}"); } } this.win32ErrorCode = 0; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index 72bc1698b7..5156ad3306 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -9,7 +9,7 @@ using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using Microsoft.Data.Common; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + using Microsoft.Data.ProviderBase; using SysTx = System.Transactions; @@ -315,8 +315,8 @@ override protected DbReferenceCollection CreateReferenceCollection() override protected void Deactivate() { - if (Log.IsAdvanceTraceOn()) - Log.Trace($" {ObjectID}# deactivating"); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + SqlClientEventSource.Log.Trace($" {ObjectID}# deactivating"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -440,15 +440,15 @@ private void EnlistNonNull(SysTx.Transaction tx) { Debug.Assert(null != tx, "null transaction?"); - if (Log.IsAdvanceTraceOn()) - Log.Trace($" {ObjectID}#, transaction {tx.GetHashCode()}#."); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + SqlClientEventSource.Log.Trace($" {ObjectID}#, transaction {tx.GetHashCode()}#."); bool hasDelegatedTransaction = false; if (IsYukonOrNewer) { - if (Log.IsAdvanceTraceOn()) - Log.Trace($" {ObjectID}#, attempting to delegate"); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + SqlClientEventSource.Log.Trace($" {ObjectID}#, attempting to delegate"); // Promotable transactions are only supported on Yukon // servers or newer. @@ -517,8 +517,8 @@ private void EnlistNonNull(SysTx.Transaction tx) this.DelegatedTransaction = delegatedTransaction; - if (Log.IsAdvanceTraceOn()) - Log.Trace($" {ObjectID}#, delegated to transaction {(null != CurrentTransaction? CurrentTransaction.ObjectID:0)}# with transactionId=0x{(null != CurrentTransaction? CurrentTransaction.TransactionId:SqlInternalTransaction.NullTransactionId)}"); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + SqlClientEventSource.Log.Trace($" {ObjectID}#, delegated to transaction {(null != CurrentTransaction? CurrentTransaction.ObjectID:0)}# with transactionId=0x{(null != CurrentTransaction? CurrentTransaction.TransactionId:SqlInternalTransaction.NullTransactionId)}"); } } catch (SqlException e) @@ -551,8 +551,8 @@ private void EnlistNonNull(SysTx.Transaction tx) if (!hasDelegatedTransaction) { - if (Log.IsAdvanceTraceOn()) - Log.Trace($" {ObjectID}#, delegation not possible, enlisting."); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + SqlClientEventSource.Log.Trace($" {ObjectID}#, delegation not possible, enlisting."); byte[] cookie = null; @@ -593,8 +593,8 @@ private void EnlistNonNull(SysTx.Transaction tx) transactionObjectID = CurrentTransaction.ObjectID; } - if (Log.IsAdvanceTraceOn()) - Log.Trace($" {ObjectID}#, enlisted with transaction {transactionObjectID}# with transactionId=0x{transactionId}"); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + SqlClientEventSource.Log.Trace($" {ObjectID}#, enlisted with transaction {transactionObjectID}# with transactionId=0x{transactionId}"); } EnlistedTransaction = tx; // Tell the base class about our enlistment @@ -618,8 +618,8 @@ private void EnlistNonNull(SysTx.Transaction tx) internal void EnlistNull() { - if (Log.IsAdvanceTraceOn()) - Log.Trace($" {ObjectID}#, unenlisting."); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + SqlClientEventSource.Log.Trace($" {ObjectID}#, unenlisting."); // We were in a transaction, but now we are not - so send // message to server with empty transaction - confirmed proper @@ -638,8 +638,8 @@ internal void EnlistNull() _isEnlistedInTransaction = false; EnlistedTransaction = null; // Tell the base class about our enlistment - if (Log.IsAdvanceTraceOn()) - Log.Trace($" {ObjectID}#, unenlisted."); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + SqlClientEventSource.Log.Trace($" {ObjectID}#, unenlisted."); // The EnlistTransaction above will return an TransactionEnded event, // which causes the TdsParser or SmiEventSink should to clear the diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs index 884c58fb93..55e5fc078c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs @@ -8,7 +8,7 @@ using System.Diagnostics; using Microsoft.Data.Common; using Microsoft.Data.SqlClient.Server; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + using SysTx = System.Transactions; namespace Microsoft.Data.SqlClient @@ -67,54 +67,54 @@ internal EventSink(SqlInternalConnectionSmi connection) internal override void DefaultDatabaseChanged(string databaseName) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {_connection.ObjectID}#, databaseName='{databaseName}'."); + SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, databaseName='{databaseName}'."); } _connection.CurrentDatabase = databaseName; } internal override void TransactionCommitted(long transactionId) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); + SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); } _connection.TransactionEnded(transactionId, TransactionState.Committed); } internal override void TransactionDefected(long transactionId) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); + SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); } _connection.TransactionEnded(transactionId, TransactionState.Unknown); } internal override void TransactionEnlisted(long transactionId) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); + SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); } _connection.TransactionStarted(transactionId, true); // distributed; } internal override void TransactionEnded(long transactionId) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); + SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); } _connection.TransactionEndedByServer(transactionId, TransactionState.Unknown); } internal override void TransactionRolledBack(long transactionId) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); + SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); } // Dev11 1066: ensure delegated transaction is rolled back @@ -123,9 +123,9 @@ internal override void TransactionRolledBack(long transactionId) internal override void TransactionStarted(long transactionId) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); + SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); } _connection.TransactionStarted(transactionId, false); // not distributed; } @@ -143,9 +143,9 @@ internal SqlInternalConnectionSmi(SqlConnectionString connectionOptions, SmiCont _smiEventSink = new EventSink(this); - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}#, constructed new SMI internal connection"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, constructed new SMI internal connection"); } } @@ -297,9 +297,9 @@ internal void AutomaticEnlistment() SysTx.Transaction contextTransaction = _smiContext.ContextTransaction; // returns the transaction that was handed to SysTx that wraps the ContextTransactionId. long contextTransactionId = _smiContext.ContextTransactionId; - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}#, contextTransactionId=0x{contextTransactionId}, contextTransaction={((null != contextTransaction) ? contextTransaction.GetHashCode() : 0)}#, currentSystemTransaction={((null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0)}#."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, contextTransactionId=0x{contextTransactionId}, contextTransaction={((null != contextTransaction) ? contextTransaction.GetHashCode() : 0)}#, currentSystemTransaction={((null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0)}#."); } if (SqlInternalTransaction.NullTransactionId != contextTransactionId) @@ -309,9 +309,9 @@ internal void AutomaticEnlistment() throw SQL.NestedTransactionScopesNotSupported(); // can't use TransactionScope(RequiresNew) inside a Sql Transaction. } - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}#, using context transaction with transactionId=0x{contextTransactionId}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, using context transaction with transactionId=0x{contextTransactionId}"); } _currentTransaction = new SqlInternalTransaction(this, TransactionType.Context, null, contextTransactionId); ContextTransaction = contextTransaction; @@ -320,16 +320,16 @@ internal void AutomaticEnlistment() { _currentTransaction = null; // there really isn't a transaction. - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}#, no transaction."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, no transaction."); } } else { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}#, using current System.Transaction."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, using current System.Transaction."); } base.Enlist(currentSystemTransaction); } @@ -343,9 +343,9 @@ override protected void ChangeDatabaseInternal(string database) override protected void InternalDeactivate() { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}#, Deactivating."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Deactivating."); } // When we put this to bed, we should not hold on to the transaction @@ -376,9 +376,9 @@ override internal void DelegatedTransactionEnded() { base.DelegatedTransactionEnded(); - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}#, cleaning up after Delegated Transaction Completion"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, cleaning up after Delegated Transaction Completion"); } _currentTransaction = null; // clean up our current transaction too @@ -386,9 +386,9 @@ override internal void DelegatedTransactionEnded() override internal void DisconnectTransaction(SqlInternalTransaction internalTransaction) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}#, Disconnecting Transaction {internalTransaction.ObjectID}#."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Disconnecting Transaction {internalTransaction.ObjectID}#."); } // VSTS 215465/15029: allow _currentTransaction to be null - it can be cleared before by server's callback @@ -415,9 +415,9 @@ override internal void ExecuteTransaction( { var transactionNameValue = (null != transactionName) ? transactionName : "null"; - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}#, transactionRequest={transactionRequest.ToString()}, " + + SqlClientEventSource.Log.Trace($" {ObjectID}#, transactionRequest={transactionRequest.ToString()}, " + $"transactionName='{transactionNameValue}', isolationLevel={iso.ToString()}, internalTransaction=#{((null != internalTransaction) ? internalTransaction.ObjectID : 0)} transactionId=0x{((null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId)}."); } @@ -474,15 +474,15 @@ override protected byte[] GetDTCAddress() _smiEventSink.ProcessMessagesAndThrow(); - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { if (null != whereAbouts) { - Log.TraceBin($" whereAbouts", whereAbouts, (ushort)whereAbouts.Length); + SqlClientEventSource.Log.TraceBin($" whereAbouts", whereAbouts, (ushort)whereAbouts.Length); } else { - Log.Trace($" whereAbouts=null"); + SqlClientEventSource.Log.Trace($" whereAbouts=null"); } } return whereAbouts; @@ -508,9 +508,9 @@ private void OnOutOfScope(object s, EventArgs e) // Called whenever the context goes out of scope, we need to make // sure that we close the connection, or the next person that uses // the context may appear to have the connection in use. - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}# context is out of scope"); + SqlClientEventSource.Log.Trace($" {ObjectID}# context is out of scope"); } // TODO: This is suspect to me -- if I go out of scope, who will commit the transaction? @@ -539,15 +539,15 @@ private void OnOutOfScope(object s, EventArgs e) override protected void PropagateTransactionCookie(byte[] transactionCookie) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { if (null != transactionCookie) { - Log.TraceBin($" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); + SqlClientEventSource.Log.TraceBin($" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); } else { - Log.Trace($" null"); + SqlClientEventSource.Log.Trace($" null"); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs index 781f3951f6..bb5d029a3b 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs @@ -19,7 +19,7 @@ using Microsoft.Data.ProviderBase; using Microsoft.Identity.Client; using SysTx = System.Transactions; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -516,9 +516,9 @@ internal SqlInternalConnectionTds( ThreadHasParserLockForClose = false; _parserLock.Release(); } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, constructed new TDS internal connection"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, constructed new TDS internal connection"); } } @@ -774,9 +774,9 @@ override protected void ChangeDatabaseInternal(string database) override public void Dispose() { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}# disposing"); + SqlClientEventSource.Log.Trace($" {ObjectID}# disposing"); } try @@ -1369,18 +1369,18 @@ private void CompleteLogin(bool enlistOK) { // ROR should not affect state of connection recovery if (_federatedAuthenticationRequested && !_federatedAuthenticationAcknowledged) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Server did not acknowledge the federated authentication request"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Server did not acknowledge the federated authentication request"); } throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged); } if (_federatedAuthenticationInfoRequested && !_federatedAuthenticationInfoReceived) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Server never sent the requested federated authentication info"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Server never sent the requested federated authentication info"); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoNotReceived); } @@ -1420,9 +1420,9 @@ private void CompleteLogin(bool enlistOK) _fConnectionOpen = true; // mark connection as open - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Post-Login Phase: Server connection obtained."); + SqlClientEventSource.Log.Trace($" Post-Login Phase: Server connection obtained."); } // for non-pooled connections, enlist in a distributed transaction @@ -1552,9 +1552,9 @@ private void Login(ServerInfo server, TimeoutTimer timeout, string newPassword, private void LoginFailure() { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace($" {ObjectID}#"); } // If the parser was allocated and we failed, then we must have failed on @@ -1681,9 +1681,9 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt int routingAttempts = 0; ServerInfo originalServerInfo = serverInfo; // serverInfo may end up pointing to new object due to routing, original object is used to set CurrentDatasource - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, host={serverInfo.UserServerName}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, host={serverInfo.UserServerName}"); } int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. @@ -1790,9 +1790,9 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt if (_routingInfo != null) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Routed to {serverInfo.ExtendedServerName}"); + SqlClientEventSource.Log.Trace($" Routed to {serverInfo.ExtendedServerName}"); } if (routingAttempts > _maxNumberOfRedirectRoute) @@ -1882,9 +1882,9 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt // Sleep for a bit to prevent clogging the network with requests, // then update sleep interval for next iteration (max 1 second interval) - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]"); } Thread.Sleep(sleepInterval); @@ -1968,9 +1968,9 @@ TimeoutTimer timeout Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used"); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, useFailover={useFailoverHost}[bool], primary={primaryServerInfo.UserServerName}, failover={failoverHost}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, useFailover={useFailoverHost}[bool], primary={primaryServerInfo.UserServerName}, failover={failoverHost}"); } int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. @@ -2039,9 +2039,9 @@ TimeoutTimer timeout // Primary server may give us a different failover partner than the connection string indicates. Update it if (null != ServerProvidedFailOverPartner && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, new failover partner={ServerProvidedFailOverPartner}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, new failover partner={ServerProvidedFailOverPartner}"); } failoverServerInfo.SetDerivedNames(protocol, ServerProvidedFailOverPartner); } @@ -2075,9 +2075,9 @@ TimeoutTimer timeout } routingAttempts++; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Routed to {_routingInfo.ServerName}"); + SqlClientEventSource.Log.Trace($" Routed to {_routingInfo.ServerName}"); } if (_parser != null) @@ -2147,9 +2147,9 @@ TimeoutTimer timeout // the network with requests, then update sleep interval for next iteration (max 1 second interval) if (1 == attemptNumber % 2) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]"); } Thread.Sleep(sleepInterval); @@ -2226,9 +2226,9 @@ private void ResolveExtendedServerName(ServerInfo serverInfo, bool aliasLookup, // Common code path for making one attempt to establish a connection and log in to server. private void AttemptOneLogin(ServerInfo serverInfo, string newPassword, SecureString newSecurePassword, bool ignoreSniOpenTimeout, TimeoutTimer timeout, bool withFailover = false, bool isFirstTransparentAttempt = true, bool disableTnir = false) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, timout={timeout.MillisecondsRemaining}[msec], server={serverInfo.ExtendedServerName}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, timout={timeout.MillisecondsRemaining}[msec], server={serverInfo.ExtendedServerName}"); } _routingInfo = null; // forget routing information @@ -2382,9 +2382,9 @@ internal void BreakConnection() { var connection = Connection; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Breaking connection."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Breaking connection."); } DoomThisConnection(); // Mark connection as unusable, so it will be destroyed if (null != connection) @@ -2477,9 +2477,9 @@ internal void OnEnvChange(SqlEnvChange rec) case TdsEnums.ENV_ROUTING: - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Received routing info"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Received routing info"); } if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0) @@ -2526,9 +2526,9 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) Debug.Assert(fedAuthInfo != null, "info should not be null."); Debug.Assert(_dbConnectionPoolAuthenticationContextKey == null, "_dbConnectionPoolAuthenticationContextKey should be null."); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Generating federated authentication token"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Generating federated authentication token"); } DbConnectionPoolAuthenticationContext dbConnectionPoolAuthenticationContext = null; @@ -2561,9 +2561,9 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // And on successful login, try to update the cache with the new token. if (contextValidity <= _dbAuthenticationContextUnLockedRefreshTimeSpan) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, " + + SqlClientEventSource.Log.Trace($" {ObjectID}#, " + $"The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + $"The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. Current Time is {DateTime.UtcNow.ToLongTimeString()}."); } @@ -2587,9 +2587,9 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // If a thread is already doing the refresh, just use the existing token in the cache and proceed. else if (contextValidity <= _dbAuthenticationContextLockedRefreshTimeSpan) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, " + + SqlClientEventSource.Log.Trace($" {ObjectID}#, " + $"The authentication context needs a refresh.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. " + $"Current Time is {DateTime.UtcNow.ToLongTimeString()}."); } @@ -2606,16 +2606,16 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // Indicate in Bid Trace that we are successful with the update. if (attemptRefreshTokenLocked) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" %d#, The attempt to get a new access token succeeded under the locked mode."); + SqlClientEventSource.Log.Trace($" %d#, The attempt to get a new access token succeeded under the locked mode."); } } } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token."); } } } @@ -2676,9 +2676,9 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP // Else some other thread is already updating it, so just proceed forward with the existing token in the cache. if (dbConnectionPoolAuthenticationContext.LockToUpdate()) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, " + + SqlClientEventSource.Log.Trace($" {ObjectID}#, " + $"Acquired the lock to update the authentication context.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. " + $"Current Time is {DateTime.UtcNow.ToLongTimeString()}."); } @@ -2687,9 +2687,9 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP } else { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Refreshing the context is already in progress by another thread."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Refreshing the context is already in progress by another thread."); } } @@ -2848,9 +2848,9 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) || _timeout.IsExpired || _timeout.MillisecondsRemaining <= sleepInterval) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {msalException.ErrorCode}#"); + SqlClientEventSource.Log.Trace($" {msalException.ErrorCode}#"); } // Error[0] @@ -2870,10 +2870,10 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) throw exc; } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, sleeping {sleepInterval}[Milliseconds]"); - Log.Trace($" {ObjectID}#, remaining {_timeout.MillisecondsRemaining}[Milliseconds]"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, sleeping {sleepInterval}[Milliseconds]"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, remaining {_timeout.MillisecondsRemaining}[Milliseconds]"); } Thread.Sleep(sleepInterval); @@ -2891,9 +2891,9 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) _newDbConnectionPoolAuthenticationContext = new DbConnectionPoolAuthenticationContext(fedAuthToken.accessToken, expirationTime); } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Finished generating federated authentication token."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Finished generating federated authentication token."); } return fedAuthToken; @@ -2958,16 +2958,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_FEDAUTH: { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for federated authentication"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for federated authentication"); } if (!_federatedAuthenticationRequested) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Did not request federated authentication"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Did not request federated authentication"); } throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); @@ -2982,9 +2982,9 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // The server shouldn't have sent any additional data with the ack (like a nonce) if (data.Length != 0) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, " + + SqlClientEventSource.Log.Trace($" {ObjectID}#, " + $"Federated authentication feature extension ack for MSAL and Security Token includes extra data"); } throw SQL.ParsingError(ParsingErrorState.FedAuthFeatureAckContainsExtraData); @@ -2993,9 +2993,9 @@ internal void OnFeatureExtAck(int featureId, byte[] data) default: Debug.Fail("Unknown _fedAuthLibrary type"); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Attempting to use unknown federated authentication library"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Attempting to use unknown federated authentication library"); } throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType); @@ -3013,16 +3013,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) Debug.Assert(newAuthenticationContextInCacheAfterAddOrUpdate != null, "newAuthenticationContextInCacheAfterAddOrUpdate should not be null."); #if DEBUG - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) { - Log.Trace($" {ObjectID}#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts."); } else { - Log.Trace($" {ObjectID}#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value."); + SqlClientEventSource.Log.Trace($" {ObjectID}#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value."); } } #endif @@ -3032,16 +3032,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_TCE: { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for TCE"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for TCE"); } if (data.Length < 1) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Unknown version number for TCE"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Unknown version number for TCE"); } throw SQL.ParsingError(ParsingErrorState.TceUnknownVersion); @@ -3050,9 +3050,9 @@ internal void OnFeatureExtAck(int featureId, byte[] data) byte supportedTceVersion = data[0]; if (0 == supportedTceVersion || supportedTceVersion > TdsEnums.MAX_SUPPORTED_TCE_VERSION) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Invalid version number for TCE"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Invalid version number for TCE"); } throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidVersion, supportedTceVersion); } @@ -3072,16 +3072,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS: { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for GlobalTransactions"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for GlobalTransactions"); } if (data.Length < 1) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Unknown version number for GlobalTransactions"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Unknown version number for GlobalTransactions"); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); @@ -3097,16 +3097,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_AZURESQLSUPPORT: { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for AzureSQLSupport"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for AzureSQLSupport"); } if (data.Length < 1) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Unknown token for AzureSQLSupport"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Unknown token for AzureSQLSupport"); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); @@ -3115,25 +3115,25 @@ internal void OnFeatureExtAck(int featureId, byte[] data) IsAzureSQLConnection = true; // Bit 0 for RO/FP support - if ((data[0] & 1) == 1 && Log.IsTraceEnabled()) + if ((data[0] & 1) == 1 && SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, FailoverPartner enabled with Readonly intent for AzureSQL DB"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, FailoverPartner enabled with Readonly intent for AzureSQL DB"); } break; } case TdsEnums.FEATUREEXT_DATACLASSIFICATION: { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for DATACLASSIFICATION"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for DATACLASSIFICATION"); } if (data.Length < 1) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION"); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); @@ -3141,18 +3141,18 @@ internal void OnFeatureExtAck(int featureId, byte[] data) byte supportedDataClassificationVersion = data[0]; if ((0 == supportedDataClassificationVersion) || (supportedDataClassificationVersion > TdsEnums.MAX_SUPPORTED_DATA_CLASSIFICATION_VERSION)) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Invalid version number for DATACLASSIFICATION"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Invalid version number for DATACLASSIFICATION"); } throw SQL.ParsingErrorValue(ParsingErrorState.DataClassificationInvalidVersion, supportedDataClassificationVersion); } if (data.Length != 2) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION"); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } @@ -3163,16 +3163,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_UTF8SUPPORT: { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for UTF8 support"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for UTF8 support"); } if (data.Length < 1) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Unknown value for UTF8 support"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Unknown value for UTF8 support"); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs index e9172bbced..eb5747babb 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -8,7 +8,7 @@ using System.Diagnostics; using System.Runtime.CompilerServices; using Microsoft.Data.Common; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -144,11 +144,11 @@ override public void Commit() SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -211,7 +211,7 @@ override public void Commit() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -272,10 +272,10 @@ override public void Rollback() { if (IsYukonPartialZombie) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { // Put something in the trace in case a customer has an issue - Log.Trace($" {ObjectID}# partial zombie no rollback required"); + SqlClientEventSource.Log.Trace($" {ObjectID}# partial zombie no rollback required"); } _internalTransaction = null; // yukon zombification @@ -287,11 +287,11 @@ override public void Rollback() SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); - if (Log.IsCorrelationEnabled()) - Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {Log.Guid}"); + if (SqlClientEventSource.Log.IsCorrelationEnabled()) + SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -342,7 +342,7 @@ override public void Rollback() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } } @@ -357,8 +357,8 @@ public void Rollback(string transactionName) SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}# transactionName='{transactionName}'"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}# transactionName='{transactionName}'"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -409,7 +409,7 @@ public void Rollback(string transactionName) _isFromAPI = false; SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -423,8 +423,8 @@ public void Save(string savePointName) SqlStatistics statistics = null; long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}# savePointName='{savePointName}'"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}# savePointName='{savePointName}'"); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -471,7 +471,7 @@ public void Save(string savePointName) finally { SqlStatistics.StopTimer(statistics); - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -490,9 +490,9 @@ internal void Zombie() if (null != internalConnection && internalConnection.IsYukonOrNewer && !_isFromAPI) { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}# yukon deferred zombie"); + SqlClientEventSource.Log.Trace($" {ObjectID}# yukon deferred zombie"); } } else diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index 7da7549947..d1ed8c8cc9 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -21,7 +21,7 @@ using Microsoft.Data.SqlClient.DataClassification; using Microsoft.Data.SqlClient.Server; using Microsoft.Data.SqlTypes; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -504,9 +504,9 @@ internal void Connect(ServerInfo serverInfo, // now allocate proper length of buffer _sniSpnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength]; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication"); + SqlClientEventSource.Log.Trace($" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication"); } } else @@ -514,30 +514,30 @@ internal void Connect(ServerInfo serverInfo, _sniSpnBuffer = null; if (authType == SqlAuthenticationMethod.ActiveDirectoryPassword) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Active Directory Password authentication"); + SqlClientEventSource.Log.Trace($" Active Directory Password authentication"); } } else if (authType == SqlAuthenticationMethod.SqlPassword) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" SQL Password authentication"); + SqlClientEventSource.Log.Trace($" SQL Password authentication"); } } else if (authType == SqlAuthenticationMethod.ActiveDirectoryInteractive) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Active Directory Interactive authentication"); + SqlClientEventSource.Log.Trace($" Active Directory Interactive authentication"); } } else { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" SQL authentication"); + SqlClientEventSource.Log.Trace($" SQL authentication"); } } } @@ -576,9 +576,9 @@ internal void Connect(ServerInfo serverInfo, // a bad error could be returned (as it was when it was freed to early for me). _physicalStateObj.Dispose(); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Login failure"); + SqlClientEventSource.Log.Trace($" Login failure"); } ThrowExceptionAndWarning(_physicalStateObj); @@ -609,9 +609,9 @@ internal void Connect(ServerInfo serverInfo, UInt32 result = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId); Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Sending prelogin handshake"); + SqlClientEventSource.Log.Trace($" Sending prelogin handshake"); } // UNDONE - send "" for instance now, need to fix later @@ -622,9 +622,9 @@ internal void Connect(ServerInfo serverInfo, _physicalStateObj.SniContext = SniContext.Snix_PreLogin; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Consuming prelogin handshake"); + SqlClientEventSource.Log.Trace($" Consuming prelogin handshake"); } PreLoginHandshakeStatus status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, @@ -632,9 +632,9 @@ internal void Connect(ServerInfo serverInfo, if (status == PreLoginHandshakeStatus.InstanceFailure) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Prelogin handshake unsuccessful. Reattempting prelogin handshake"); + SqlClientEventSource.Log.Trace($" Prelogin handshake unsuccessful. Reattempting prelogin handshake"); } _physicalStateObj.Dispose(); // Close previous connection @@ -646,9 +646,9 @@ internal void Connect(ServerInfo serverInfo, { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Login failure"); + SqlClientEventSource.Log.Trace($" Login failure"); } ThrowExceptionAndWarning(_physicalStateObj); } @@ -656,9 +656,9 @@ internal void Connect(ServerInfo serverInfo, UInt32 retCode = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId); Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Sending prelogin handshake"); + SqlClientEventSource.Log.Trace($" Sending prelogin handshake"); } SendPreLoginHandshake(instanceName, encrypt, !string.IsNullOrEmpty(certificate), useOriginalAddressInfo); status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, out marsCapable, @@ -668,17 +668,17 @@ internal void Connect(ServerInfo serverInfo, // one pre-login packet and know we are connecting to Shiloh. if (status == PreLoginHandshakeStatus.InstanceFailure) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Prelogin handshake unsuccessful. Login failure"); + SqlClientEventSource.Log.Trace($" Prelogin handshake unsuccessful. Login failure"); } throw SQL.InstanceFailure(); } } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Prelogin handshake successful"); + SqlClientEventSource.Log.Trace($" Prelogin handshake successful"); } if (_fMARS && marsCapable) @@ -772,9 +772,9 @@ internal TdsParserStateObject CreateSession() { TdsParserStateObject session = new TdsParserStateObject(this, (SNIHandle)_pMarsPhysicalConObj.Handle, true); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}# created session {session.ObjectID}"); + SqlClientEventSource.Log.Trace($" {ObjectID}# created session {session.ObjectID}"); } return session; @@ -791,18 +791,18 @@ internal TdsParserStateObject GetSession(object owner) session = _sessionPool.GetSession(owner); Debug.Assert(!session._pendingData, "pending data on a pooled MARS session"); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}# getting session {session.ObjectID} from pool"); + SqlClientEventSource.Log.Trace($" {ObjectID}# getting session {session.ObjectID} from pool"); } } else { session = _physicalStateObj; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}# getting physical session {session.ObjectID}"); + SqlClientEventSource.Log.Trace($" {ObjectID}# getting physical session {session.ObjectID}"); } } Debug.Assert(session._outputPacketNumber == 1, "The packet number is expected to be 1"); @@ -1018,9 +1018,9 @@ private void SendPreLoginHandshake(byte[] instanceName, bool encrypt, bool clien offset += actIdSize; optionDataSize += actIdSize; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" ClientConnectionID {_connHandler._clientConnectionId.ToString()}, ActivityID {actId.ToString()}"); + SqlClientEventSource.Log.Trace($" ClientConnectionID {_connHandler._clientConnectionId.ToString()}, ActivityID {actId.ToString()}"); } break; @@ -1332,9 +1332,9 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod // Only 0x00 and 0x01 are accepted values from the server. if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, " + + SqlClientEventSource.Log.Trace($" {ObjectID}#, " + $"Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {(int)payload[payloadOffset]}."); } @@ -1377,11 +1377,11 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod internal void Deactivate(bool connectionIsDoomed) { // Called when the connection that owns us is deactivated. - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}# deactivating"); + SqlClientEventSource.Log.Trace($" {ObjectID}# deactivating"); - Log.Trace($" {ObjectID}#, {TraceString()}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, {TraceString()}"); } if (MARSOn) @@ -1538,9 +1538,9 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle Debug.Assert(temp.Count > 0, "TdsParser::ThrowExceptionAndWarning called with no exceptions or warnings!"); if (temp.Count == 0) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {ObjectID}#"); + SqlClientEventSource.Log.Trace($" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {ObjectID}#"); } } Debug.Assert(_connHandler != null, "TdsParser::ThrowExceptionAndWarning called with null connectionHandler!"); @@ -2262,9 +2262,9 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead _state = TdsParserState.Broken; _connHandler.BreakConnection(); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Potential multi-threaded misuse of connection, unexpected TDS token found {ObjectID}#"); + SqlClientEventSource.Log.Trace($" Potential multi-threaded misuse of connection, unexpected TDS token found {ObjectID}#"); } throw SQL.ParsingErrorToken(ParsingErrorState.InvalidTdsTokenReceived, token); // MDAC 82443 } @@ -2587,9 +2587,9 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead } case TdsEnums.SQLLOGINACK: { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Received login acknowledgement token"); + SqlClientEventSource.Log.Trace($" Received login acknowledgement token"); } SqlLoginAck ack; if (!TryProcessLoginAck(stateObj, out ack)) @@ -2613,9 +2613,9 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead _connHandler._federatedAuthenticationInfoReceived = true; SqlFedAuthInfo info; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Received federated authentication info token"); + SqlClientEventSource.Log.Trace($" Received federated authentication info token"); } if (!TryProcessFedAuthInfo(stateObj, tokenLength, out info)) @@ -4029,17 +4029,17 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, SqlFedAuthInfo tempFedAuthInfo = new SqlFedAuthInfo(); // Skip reading token length, since it has already been read in caller - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" FEDAUTHINFO token stream length = {tokenLen}"); + SqlClientEventSource.Log.Trace($" FEDAUTHINFO token stream length = {tokenLen}"); } if (tokenLen < sizeof(uint)) { // the token must at least contain a DWORD indicating the number of info IDs - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); + SqlClientEventSource.Log.Trace($" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); } throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen); } @@ -4048,17 +4048,17 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, uint optionsCount; if (!stateObj.TryReadUInt32(out optionsCount)) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream."); + SqlClientEventSource.Log.Trace($" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream."); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadCountOfInfoIds); } tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" CountOfInfoIDs = {optionsCount.ToString(CultureInfo.InvariantCulture)}"); + SqlClientEventSource.Log.Trace($" CountOfInfoIDs = {optionsCount.ToString(CultureInfo.InvariantCulture)}"); } if (tokenLen > 0) @@ -4068,16 +4068,16 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, int totalRead = 0; bool successfulRead = stateObj.TryReadByteArray(tokenData, 0, tokenLen, out totalRead); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Read rest of FEDAUTHINFO token stream: {BitConverter.ToString(tokenData, 0, totalRead)}"); + SqlClientEventSource.Log.Trace($" Read rest of FEDAUTHINFO token stream: {BitConverter.ToString(tokenData, 0, totalRead)}"); } if (!successfulRead || totalRead != tokenLen) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Failed to read FEDAUTHINFO token stream. Attempted to read {tokenLen} bytes, actually read {totalRead}"); + SqlClientEventSource.Log.Trace($" Failed to read FEDAUTHINFO token stream. Attempted to read {tokenLen} bytes, actually read {totalRead}"); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadTokenStream); } @@ -4100,7 +4100,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, uint dataLen = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 1))); uint dataOffset = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 5))); - Log.Trace($" FedAuthInfoOpt: ID={id}, DataLen={dataLen.ToString(CultureInfo.InvariantCulture)}, Offset={dataOffset.ToString(CultureInfo.InvariantCulture)}\n"); + SqlClientEventSource.Log.Trace($" FedAuthInfoOpt: ID={id}, DataLen={dataLen.ToString(CultureInfo.InvariantCulture)}, Offset={dataOffset.ToString(CultureInfo.InvariantCulture)}\n"); // offset is measured from optCount, so subtract to make offset measured // from the beginning of tokenData @@ -4112,9 +4112,9 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, // if dataOffset points to a region within FedAuthInfoOpt or after the end of the token, throw if (dataOffset < totalOptionsSize || dataOffset >= tokenLen) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" FedAuthInfoDataOffset points to an invalid location."); + SqlClientEventSource.Log.Trace($" FedAuthInfoDataOffset points to an invalid location."); } throw SQL.ParsingErrorOffset(ParsingErrorState.FedAuthInfoInvalidOffset, unchecked((int)dataOffset)); } @@ -4127,24 +4127,24 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } catch (ArgumentOutOfRangeException e) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Failed to read FedAuthInfoData."); + SqlClientEventSource.Log.Trace($" Failed to read FedAuthInfoData."); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadData, e); } catch (ArgumentException e) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" FedAuthInfoData is not in unicode format."); + SqlClientEventSource.Log.Trace($" FedAuthInfoData is not in unicode format."); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e); } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" FedAuthInfoData: {data}"); + SqlClientEventSource.Log.Trace($" FedAuthInfoData: {data}"); } // store data in tempFedAuthInfo @@ -4157,9 +4157,9 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, tempFedAuthInfo.stsurl = data; break; default: - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Ignoring unknown federated authentication info option: {id}"); + SqlClientEventSource.Log.Trace($" Ignoring unknown federated authentication info option: {id}"); } break; } @@ -4167,24 +4167,24 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } else { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" FEDAUTHINFO token stream is not long enough to contain the data it claims to."); + SqlClientEventSource.Log.Trace($" FEDAUTHINFO token stream is not long enough to contain the data it claims to."); } throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForData, tokenLen); } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Processed FEDAUTHINFO token stream: {tempFedAuthInfo.ToString()}"); + SqlClientEventSource.Log.Trace($" Processed FEDAUTHINFO token stream: {tempFedAuthInfo.ToString()}"); } if (string.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || string.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) { // We should be receiving both stsurl and spn - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" FEDAUTHINFO token stream does not contain both STSURL and SPN."); + SqlClientEventSource.Log.Trace($" FEDAUTHINFO token stream does not contain both STSURL and SPN."); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDoesNotContainStsurlAndSpn); } @@ -4613,9 +4613,9 @@ internal bool TryProcessTceCryptoMetadata(TdsParserStateObject stateObj, // validate the index (ordinal passed) if (index >= cipherTable.Value.Size) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Incorrect ordinal received {index}, max tab size: {cipherTable.Value.Size}"); + SqlClientEventSource.Log.Trace($" Incorrect ordinal received {index}, max tab size: {cipherTable.Value.Size}"); } throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidOrdinalIntoCipherInfoTable, index); } @@ -8884,9 +8884,9 @@ internal void TdsLogin(SqlLogin rec, WriteInt(log7Flags, _physicalStateObj); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, TDS Login7 flags = {log7Flags}:"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, TDS Login7 flags = {log7Flags}:"); } WriteInt(0, _physicalStateObj); // ClientTimeZone is not used @@ -9046,9 +9046,9 @@ internal void TdsLogin(SqlLogin rec, }; if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Sending federated authentication feature request"); + SqlClientEventSource.Log.Trace($" Sending federated authentication feature request"); } Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null."); WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true); @@ -9123,9 +9123,9 @@ internal void SendFedAuthToken(SqlFedAuthToken fedAuthToken) Debug.Assert(fedAuthToken != null, "fedAuthToken cannot be null"); Debug.Assert(fedAuthToken.accessToken != null, "fedAuthToken.accessToken cannot be null"); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Sending federated authentication token"); + SqlClientEventSource.Log.Trace($" Sending federated authentication token"); } _physicalStateObj._outputMessageType = TdsEnums.MT_FEDAUTH; @@ -9518,9 +9518,9 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) { int old_outputPacketNumber = stateObj._outputPacketNumber; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Exception caught on ExecuteXXX: '{e.ToString()}'"); + SqlClientEventSource.Log.Trace($" Exception caught on ExecuteXXX: '{e.ToString()}'"); } if (stateObj.HasOpenResult) @@ -9555,9 +9555,9 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) } } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Exception rethrown."); + SqlClientEventSource.Log.Trace($" Exception rethrown."); } } @@ -9614,9 +9614,9 @@ internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationReques stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#"); + SqlClientEventSource.Log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#"); } } stateObj.SniContext = SniContext.Snix_Execute; @@ -9746,9 +9746,9 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#"); + SqlClientEventSource.Log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#"); } } stateObj.SniContext = SniContext.Snix_Execute; @@ -10614,9 +10614,9 @@ private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefa var sendDefaultValue = sendDefault ? 1 : 0; - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, Sending parameter '{param.ParameterName}', default flag={sendDefaultValue}, metadata:{metaData.TraceString(3)}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, Sending parameter '{param.ParameterName}', default flag={sendDefaultValue}, metadata:{metaData.TraceString(3)}"); } // @@ -11673,7 +11673,7 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio Debug.Assert(-1 <= timeout, "Timeout"); - Log.NotificationsTrace($" NotificationRequest: userData: '{notificationRequest.UserData}', options: '{notificationRequest.Options}', timeout: '{notificationRequest.Timeout}'\n"); + SqlClientEventSource.Log.NotificationsTrace($" NotificationRequest: userData: '{notificationRequest.UserData}', options: '{notificationRequest.Options}', timeout: '{notificationRequest.Timeout}'\n"); WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj); // Query notifications Type @@ -11700,9 +11700,9 @@ private void WriteTraceHeaderData(TdsParserStateObject stateObj) stateObj.WriteByteArray(actId.Id.ToByteArray(), GUID_SIZE, 0); // Id (Guid) WriteUnsignedInt(actId.Sequence, stateObj); // sequence number - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" ActivityID {actId.ToString()}"); + SqlClientEventSource.Log.Trace($" ActivityID {actId.ToString()}"); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index 06f4cf5ccd..2ef39df94e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.Diagnostics; using Microsoft.Data.Common; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -38,9 +38,9 @@ internal TdsParserSessionPool(TdsParser parser) _freeStateObjects = new TdsParserStateObject[MaxInactiveCount]; _freeStateObjectCount = 0; - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}# created session pool for parser {parser.ObjectID}"); + SqlClientEventSource.Log.Trace($" {ObjectID}# created session pool for parser {parser.ObjectID}"); } } @@ -67,8 +67,8 @@ internal void Deactivate() // sessions that are past what we want to keep around. long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}# deactivating cachedCount={_cachedCount}\n"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}# deactivating cachedCount={_cachedCount}\n"); try { @@ -89,9 +89,9 @@ internal void Deactivate() { // TODO: consider adding a performance counter for the number of sessions we reclaim - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}# reclaiming session {session.ObjectID}"); + SqlClientEventSource.Log.Trace($" {ObjectID}# reclaiming session {session.ObjectID}"); } PutSession(session); @@ -104,7 +104,7 @@ internal void Deactivate() } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -127,9 +127,9 @@ internal void BestEffortCleanup() internal void Dispose() { - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}# disposing cachedCount={_cachedCount}"); + SqlClientEventSource.Log.Trace($" {ObjectID}# disposing cachedCount={_cachedCount}"); } lock (_cache) @@ -191,9 +191,9 @@ internal TdsParserStateObject GetSession(object owner) // No free objects, create a new one session = _parser.CreateSession(); - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}# adding session {session.ObjectID} to pool"); + SqlClientEventSource.Log.Trace($" {ObjectID}# adding session {session.ObjectID} to pool"); } _cache.Add(session); @@ -203,9 +203,9 @@ internal TdsParserStateObject GetSession(object owner) session.Activate(owner); } - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}# using session {session.ObjectID}"); + SqlClientEventSource.Log.Trace($" {ObjectID}# using session {session.ObjectID}"); } return session; @@ -229,9 +229,9 @@ internal void PutSession(TdsParserStateObject session) else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount)) { // Session is good to re-use and our cache has space - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}# keeping session {session.ObjectID} cachedCount={_cachedCount}"); + SqlClientEventSource.Log.Trace($" {ObjectID}# keeping session {session.ObjectID} cachedCount={_cachedCount}"); } Debug.Assert(!session._pendingData, "pending data on a pooled session?"); @@ -242,9 +242,9 @@ internal void PutSession(TdsParserStateObject session) else { // Either the session is bad, or we have no cache space - so dispose the session and remove it - if (Log.IsAdvanceTraceOn()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - Log.Trace($" {ObjectID}# disposing session {session.ObjectID} cachedCount={_cachedCount}"); + SqlClientEventSource.Log.Trace($" {ObjectID}# disposing session {session.ObjectID} cachedCount={_cachedCount}"); } bool removed = _cache.Remove(session); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index 868bf185de..25b2c530a0 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -14,7 +14,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Common; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -561,11 +561,11 @@ internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount) return false; } - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {stateObj.ObjectID}#, NBCROW bitmap received, column count = {columnsCount}"); + SqlClientEventSource.Log.Trace($" {stateObj.ObjectID}#, NBCROW bitmap received, column count = {columnsCount}"); } - Log.TraceBin($" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); + SqlClientEventSource.Log.TraceBin($" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); return true; } @@ -919,16 +919,16 @@ internal int DecrementPendingCallbacks(bool release) { int remaining = Interlocked.Decrement(ref _pendingCallbacks); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, after decrementing _pendingCallbacks: { _pendingCallbacks}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, after decrementing _pendingCallbacks: { _pendingCallbacks}"); } if ((0 == remaining || release) && _gcHandle.IsAllocated) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, FREEING HANDLE!"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, FREEING HANDLE!"); } _gcHandle.Free(); } @@ -1038,9 +1038,9 @@ internal int IncrementPendingCallbacks() { int remaining = Interlocked.Increment(ref _pendingCallbacks); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, after incrementing _pendingCallbacks: {_pendingCallbacks}"); + SqlClientEventSource.Log.Trace($" {ObjectID}#, after incrementing _pendingCallbacks: {_pendingCallbacks}"); } Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}"); @@ -2175,9 +2175,9 @@ internal bool TryReadNetworkPacket() _snapshot.CheckStack(new StackTrace()); } #endif - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Async packet replay"); + SqlClientEventSource.Log.Trace($" Async packet replay"); } return true; } @@ -2600,9 +2600,9 @@ internal bool IsConnectionAlive(bool throwOnException) if ((error != TdsEnums.SNI_SUCCESS) && (error != TdsEnums.SNI_WAIT_TIMEOUT)) { // Connection is dead - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" received error {(int)error} on idle connection"); + SqlClientEventSource.Log.Trace($" received error {(int)error} on idle connection"); } isAlive = false; if (throwOnException) @@ -2819,9 +2819,9 @@ public void ProcessSniPacket(IntPtr packet, UInt32 error) SniReadStatisticsAndTracing(); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.TraceBin($" Packet read", _inBuff, (UInt16)_inBytesRead); + SqlClientEventSource.Log.TraceBin($" Packet read", _inBuff, (UInt16)_inBytesRead); } AssertValidState(); @@ -2980,9 +2980,9 @@ public void WriteAsyncCallback(IntPtr key, IntPtr packet, UInt32 sniError) { if (sniError != TdsEnums.SNI_SUCCESS) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" write async returned error code {(int)sniError}"); + SqlClientEventSource.Log.Trace($" write async returned error code {(int)sniError}"); } try @@ -3452,9 +3452,9 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr if (error != TdsEnums.SNI_SUCCESS) { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" write async returned error code {(int)error}"); + SqlClientEventSource.Log.Trace($" write async returned error code {(int)error}"); } AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(); @@ -3492,9 +3492,9 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr } else { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" write async returned error code {(int)sniError}"); + SqlClientEventSource.Log.Trace($" write async returned error code {(int)sniError}"); } AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(callerHasConnectionLock); @@ -3556,9 +3556,9 @@ internal void SendAttention(bool mustTakeWriteLock = false) _parser._asyncWrite = false; // stop async write SNIWritePacket(Handle, attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Send Attention ASync."); + SqlClientEventSource.Log.Trace($" Send Attention ASync."); } } finally @@ -3582,11 +3582,11 @@ internal void SendAttention(bool mustTakeWriteLock = false) _attentionSending = false; } - Log.TraceBin($" Packet sent", _outBuff, (ushort)_outBytesUsed); + SqlClientEventSource.Log.TraceBin($" Packet sent", _outBuff, (ushort)_outBytesUsed); - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" Attention sent to the server."); + SqlClientEventSource.Log.Trace($" Attention sent to the server."); } AssertValidState(); @@ -3771,7 +3771,7 @@ private void SniWriteStatisticsAndTracing() _traceChangePasswordOffset = 0; _traceChangePasswordLength = 0; } - Log.TraceBin($" Packet sent", _outBuff, (UInt16)_outBytesUsed); + SqlClientEventSource.Log.TraceBin($" Packet sent", _outBuff, (UInt16)_outBytesUsed); } [Conditional("DEBUG")] diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs index f061dbf83d..40023a1b3e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs @@ -7,7 +7,7 @@ using System.Diagnostics; using System.Threading; using Microsoft.Data.Common; -using static Microsoft.Data.SqlClient.SqlClientEventSource; + namespace Microsoft.Data.SqlClient { @@ -54,8 +54,8 @@ internal SqlInternalTransaction(SqlInternalConnection innerConnection, Transacti internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction, long transactionId) { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Created for connection {innerConnection.ObjectID}#, outer transaction {((null != outerTransaction) ? outerTransaction.ObjectID : -1)}#, Type {(int)type}"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Created for connection {innerConnection.ObjectID}#, outer transaction {((null != outerTransaction) ? outerTransaction.ObjectID : -1)}#, Type {(int)type}"); _innerConnection = innerConnection; _transactionType = type; @@ -271,8 +271,8 @@ internal void CloseFromConnection() Debug.Assert(innerConnection != null, "How can we be here if the connection is null?"); - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Closing"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Closing"); bool processFinallyBlock = true; try @@ -301,8 +301,8 @@ internal void CloseFromConnection() internal void Commit() { long scopeID = 0; - if (Log.IsEnabled()) - scopeID = Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); if (_innerConnection.IsLockedForBulkCopy) { @@ -347,7 +347,7 @@ internal void Commit() } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -376,8 +376,8 @@ internal void Dispose() private /*protected override*/ void Dispose(bool disposing) { - if (Log.IsPoolerTraceEnabled()) - Log.PoolerTrace($" {ObjectID}#, Disposing"); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Disposing"); if (disposing) { @@ -433,7 +433,7 @@ internal void InitParent(SqlTransaction transaction) internal void Rollback() { - var scopeID = Log.ScopeEnter($" {ObjectID}#"); + var scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); if (_innerConnection.IsLockedForBulkCopy) { @@ -474,13 +474,13 @@ internal void Rollback() } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } internal void Rollback(string transactionName) { - var scopeID = Log.ScopeEnter($" {ObjectID}#, transactionName='{transactionName}'"); + var scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, transactionName='{transactionName}'"); if (_innerConnection.IsLockedForBulkCopy) { @@ -523,13 +523,13 @@ internal void Rollback(string transactionName) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } internal void Save(string savePointName) { - var scopeID = Log.ScopeEnter($" {ObjectID}#, savePointName='{savePointName}'"); + var scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, savePointName='{savePointName}'"); _innerConnection.ValidateConnectionForExecute(null); @@ -561,7 +561,7 @@ internal void Save(string savePointName) } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs index 700b89e8d6..0826073310 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs @@ -12,7 +12,7 @@ using System.Diagnostics; using System.Runtime.Versioning; using Microsoft.Data.Common; -using static Microsoft.Data.SqlClient.SqlClientEventSource; +using Microsoft.Data.SqlClient; namespace Microsoft.Data.SqlTypes { @@ -66,9 +66,9 @@ Int64 allocationSize ) { long scopeID = 0; - if (Log.IsEnabled()) + if (SqlClientEventSource.Log.IsEnabled()) { - scopeID = Log.ScopeEnter($" { ObjectID}# access={(int)access} options={(int)options} path='{path}'"); + scopeID = SqlClientEventSource.Log.ScopeEnter($" { ObjectID}# access={(int)access} options={(int)options} path='{path}'"); } try @@ -95,7 +95,7 @@ Int64 allocationSize } finally { - Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -718,9 +718,9 @@ Int64 allocationSize UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode); try { - if (Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { - Log.Trace($" {ObjectID}#, desiredAccess=0x{(int)nDesiredAccess}, allocationSize={allocationSize}, " + + SqlClientEventSource.Log.Trace($" {ObjectID}#, desiredAccess=0x{(int)nDesiredAccess}, allocationSize={allocationSize}, " + $"fileAttributes=0x%{0}, shareAccess=0x{(int)shareAccess}, dwCreateDisposition=0x{dwCreateDisposition}, createOptions=0x{ dwCreateOptions}"); } From 7ac07422b3d8d84bc3da84e9afd0edd37a3aa0dc Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Wed, 5 Feb 2020 13:11:15 -0800 Subject: [PATCH 21/46] Removing Extra lines and unwanted SqlClient Reference from SqlClientEventSource --- .../netfx/src/Microsoft/Data/Common/AdapterUtil.cs | 4 ++-- .../netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs | 2 +- .../netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs | 1 - .../Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs | 2 -- .../netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs | 3 --- .../netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs | 2 -- .../netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs | 1 - .../netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs | 4 +--- .../netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs | 1 - .../netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs | 1 - .../netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs | 1 - .../src/Microsoft/Data/SqlClient/SqlDependencyListener.cs | 1 - .../netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs | 1 - .../netfx/src/Microsoft/Data/SqlClient/SqlError.cs | 1 - .../src/Microsoft/Data/SqlClient/SqlInternalConnection.cs | 2 -- .../src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs | 2 -- .../netfx/src/Microsoft/Data/SqlClient/TdsParser.cs | 1 - .../src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs | 1 - .../src/Microsoft/Data/SqlClient/TdsParserStateObject.cs | 1 - .../src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs | 1 - 20 files changed, 4 insertions(+), 29 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index 748c386b29..93a4f8d6b9 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -100,9 +100,9 @@ static private void TraceException( string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e && SqlClient.SqlClientEventSource.Log.IsTraceEnabled()) + if (null != e && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClient.SqlClientEventSource.Log.Trace($"{e.ToString()}"); // will include callstack if permission is available + SqlClientEventSource.Log.Trace($"{e.ToString()}"); // will include callstack if permission is available } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs index 2aeb858dca..c626374cc6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs @@ -631,7 +631,7 @@ private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hash string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); - if (SqlClient.SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsTraceEnabled()) { if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) { // don't trace passwords ever! diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs index c75f5a0368..a6e8cc1e1d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs @@ -14,7 +14,6 @@ using System.Threading; using Microsoft.Data.SqlClient; - namespace Microsoft.Data { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs index b84d2f199e..433d7ccc01 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs @@ -4,10 +4,8 @@ using System.Diagnostics; - namespace Microsoft.Data.SqlClient.Server { - internal class SmiEventSink_Default : SmiEventSink { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs index 219de588bb..b8c15cf72c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs @@ -2,11 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - - namespace Microsoft.Data.SqlClient { - /// public class SqlClientLogger { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index 92a55dc59d..0e82c45e21 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -10,7 +10,6 @@ using System.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; -using System.Diagnostics.Tracing; using System.IO; using System.Linq; using System.Runtime.CompilerServices; @@ -25,7 +24,6 @@ using Microsoft.Data.SqlClient.Server; using SysTx = System.Transactions; - namespace Microsoft.Data.SqlClient { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index 817df214e9..1b28d0920f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -11,7 +11,6 @@ using System.Text.RegularExpressions; using Microsoft.Data.Common; - namespace Microsoft.Data.SqlClient { internal sealed class SqlCommandSet diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index 940733b7b2..8c71c131ff 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -29,9 +29,7 @@ using Microsoft.Data.ProviderBase; using Microsoft.Data.SqlClient.Server; - -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Data.DataSetExtensions, PublicKey=" + Microsoft.Data.SqlClient.AssemblyRef.EcmaPublicKeyFull)] // DevDiv Bugs 92166 - +[assembly: InternalsVisibleTo("System.Data.DataSetExtensions, PublicKey=" + Microsoft.Data.SqlClient.AssemblyRef.EcmaPublicKeyFull)] // DevDiv Bugs 92166 namespace Microsoft.Data.SqlClient { using System.Diagnostics.Tracing; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index 8f1aacb5f6..8ae19e4fc4 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -9,7 +9,6 @@ using System.Diagnostics; using Microsoft.Data.Common; - namespace Microsoft.Data.SqlClient { /// diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs index 98a863f625..871c69760c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -22,7 +22,6 @@ using Microsoft.Data.SqlClient.Server; using Microsoft.Data.SqlTypes; - namespace Microsoft.Data.SqlClient { /// diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs index 3823242f77..2e79b11407 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -19,7 +19,6 @@ using Microsoft.Data.ProviderBase; using Microsoft.Data.Sql; - namespace Microsoft.Data.SqlClient { /// diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index ae8cfeb231..b1cfe3a938 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -18,7 +18,6 @@ using Microsoft.Data.ProviderBase; using Microsoft.Data.SqlClient; - // This class is the process wide dependency dispatcher. It contains all connection listeners for the entire process and // receives notifications on those connections to dispatch to the corresponding AppDomain dispatcher to notify the // appropriate dependencies. diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs index e282469cbb..6cdad9107f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs @@ -8,7 +8,6 @@ using System.Threading; using Microsoft.Data.Common; - namespace Microsoft.Data.SqlClient { // This is a singleton instance per AppDomain that acts as the notification dispatcher for diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs index 55ecb6550d..659a34b775 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs @@ -4,7 +4,6 @@ using System; - namespace Microsoft.Data.SqlClient { /// diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index 5156ad3306..46f50613cc 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -9,9 +9,7 @@ using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using Microsoft.Data.Common; - using Microsoft.Data.ProviderBase; - using SysTx = System.Transactions; namespace Microsoft.Data.SqlClient diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs index 55e5fc078c..7f32e8324f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs @@ -8,12 +8,10 @@ using System.Diagnostics; using Microsoft.Data.Common; using Microsoft.Data.SqlClient.Server; - using SysTx = System.Transactions; namespace Microsoft.Data.SqlClient { - sealed internal class SqlInternalConnectionSmi : SqlInternalConnection { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index d1ed8c8cc9..f32ae77d9e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -22,7 +22,6 @@ using Microsoft.Data.SqlClient.Server; using Microsoft.Data.SqlTypes; - namespace Microsoft.Data.SqlClient { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index 2ef39df94e..c09d454039 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -7,7 +7,6 @@ using System.Diagnostics; using Microsoft.Data.Common; - namespace Microsoft.Data.SqlClient { internal class TdsParserSessionPool diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index 25b2c530a0..8d4f6d26b5 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -15,7 +15,6 @@ using System.Threading.Tasks; using Microsoft.Data.Common; - namespace Microsoft.Data.SqlClient { sealed internal class LastIOTimer diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs index 40023a1b3e..59fecfea32 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs @@ -8,7 +8,6 @@ using System.Threading; using Microsoft.Data.Common; - namespace Microsoft.Data.SqlClient { internal enum TransactionState From ab912e6b3e1ac012c2d713ed634ae5a1e10dc3ee Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Fri, 7 Feb 2020 10:59:17 -0800 Subject: [PATCH 22/46] Changing documentation and adding Advanced Keyword --- .../SqlClientEventSource.xml | 30 +++++++++---------- .../Data/SqlClient/SqlClientEventSource.cs | 9 ++---- 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml index 8d536f1ab4..d802e648e4 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml @@ -2,52 +2,52 @@ - This class implements parent class. + This class implements class and provides ability to create events for event tracing for Windows(ETW). - this is the singleton instantiation of the SqlClientEventSource class. + This is the singleton instance of the class. - This class defines the nested class of Keywords for . + This class provides supported Keywords from an EventSource consumer point of view, but these definitions are not needed outside this class. - Representing possible group of events for Tracing. + Enabling this event turns on the 'Trace' events for listening implementation. 1 - Reperesnting possible group of events for Scope. + Enabling this event turns on the 'Scope' events for listening implementation. 2 - Representing possible froup of events for Notofocation Trace. + Enabling this event turns on the 'NotificationTrace' events for listening implementation. 4 - Representing possible group of events for Pooling. + Enabling this event turns on the 'Pooling' events for listening implementation. 8 - Representing possible group of events for Correlation. + Enabling this event turns on the 'Correlation' events for listening implementation. 16 - Representing possible group of events for NotificationScope + Enabling this event turns on the 'NotificationScope' events for listening implementation. 32 - Representing possible group of events for PoolerScope. + Enabling this event turns on the 'PoolerScope' events for listening implementation. 64 - Representing possible group of events for PoolerTrace. + Enabling this event turns on 'PoolerTrace' events for listening implementation. 128 - - - - + + Enabling this event turns on 'Advanced' events for listening implementation. + 512 + diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 74ccfd4f79..135fd12de9 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -54,11 +54,8 @@ public class Keywords /// public const EventKeywords PoolerTrace = (EventKeywords)128; - /// - public static EventKeywords GetAll() - { - return Trace | Scope | NotificationTrace | Pooling | Correlation | NotificationScope | PoolerScope; - } + /// + public const EventKeywords Advanced = (EventKeywords)512; } [NonEvent] @@ -86,7 +83,7 @@ public static EventKeywords GetAll() internal bool IsPoolerTraceEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.PoolerTrace); [NonEvent] - internal bool IsAdvanceTraceOn() => SqlClientEventSource.Log.IsEnabled(EventLevel.LogAlways, EventKeywords.All); + internal bool IsAdvanceTraceOn() => SqlClientEventSource.Log.IsEnabled(EventLevel.LogAlways, Keywords.Advanced); [Event(TraceEventId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] internal void Trace(string message) From 9557b3a1641d38ffee0c5a527b80bb21afb4b3d8 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 11 Feb 2020 11:02:48 -0800 Subject: [PATCH 23/46] Adding Overloaded methods in EventSource --- .../src/Microsoft/Data/Common/AdapterUtil.cs | 2 +- .../Data/Common/DBConnectionString.cs | 4 +- .../Data/Common/DbConnectionOptions.cs | 4 +- .../netfx/src/Microsoft/Data/DataException.cs | 2 +- .../Data/ProviderBase/DbConnectionFactory.cs | 26 +- .../Data/ProviderBase/DbConnectionInternal.cs | 42 ++- .../Data/ProviderBase/DbConnectionPool.cs | 202 ++++++++++---- .../ProviderBase/DbConnectionPoolGroup.cs | 6 +- .../Data/ProviderBase/SqlConnectionHelper.cs | 16 +- .../Microsoft/Data/SqlClient/LocalDBAPI.cs | 8 +- .../SqlClient/Server/SmiEventSink_Default.cs | 2 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 11 +- .../Data/SqlClient/SqlClientEventSource.cs | 182 ++++++++++++- .../Microsoft/Data/SqlClient/SqlCommand.cs | 182 ++++++++----- .../Microsoft/Data/SqlClient/SqlConnection.cs | 83 ++++-- .../Data/SqlClient/SqlConnectionFactory.cs | 2 +- .../SqlConnectionPoolGroupProviderInfo.cs | 4 +- .../Data/SqlClient/SqlDataAdapter.cs | 6 +- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 42 +-- .../Data/SqlClient/SqlDataReaderSmi.cs | 33 ++- .../Data/SqlClient/SqlDelegatedTransaction.cs | 36 ++- .../Microsoft/Data/SqlClient/SqlDependency.cs | 173 +++++++++--- .../Data/SqlClient/SqlDependencyListener.cs | 253 +++++++++++++----- .../Data/SqlClient/SqlDependencyUtils.cs | 124 ++++++--- .../src/Microsoft/Data/SqlClient/SqlError.cs | 2 +- .../Data/SqlClient/SqlInternalConnection.cs | 32 ++- .../SqlClient/SqlInternalConnectionSmi.cs | 44 +-- .../SqlClient/SqlInternalConnectionTds.cs | 108 ++++---- .../Data/SqlClient/SqlTransaction.cs | 38 ++- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 109 ++++---- .../Data/SqlClient/TdsParserSessionPool.cs | 20 +- .../Data/SqlClient/TdsParserStateObject.cs | 30 +-- .../Data/SqlClient/sqlinternaltransaction.cs | 32 ++- .../Microsoft/Data/SqlTypes/SqlFileStream.cs | 8 +- 34 files changed, 1309 insertions(+), 559 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index 93a4f8d6b9..2dba4ec6f6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -102,7 +102,7 @@ static private void TraceException( Debug.Assert(null != e, "TraceException: null Exception"); if (null != e && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($"{e.ToString()}"); // will include callstack if permission is available + SqlClientEventSource.Log.Trace(trace,e.ToString()); // will include callstack if permission is available } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs index 51eff9335a..f864c563f7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs @@ -472,7 +472,7 @@ private static string[] ParseRestrictions(string restrictions, Hashtable synonym #if DEBUG if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" Restrictions='{restrictions}'"); + SqlClientEventSource.Log.Trace(" Restrictions='{0}'",restrictions); } #endif List restrictionValues = new List(); @@ -491,7 +491,7 @@ private static string[] ParseRestrictions(string restrictions, Hashtable synonym #if DEBUG if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" KeyName='{keyname}'"); + SqlClientEventSource.Log.Trace(" KeyName='{0}'",keyname); } #endif string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144 diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs index c626374cc6..527d39be7e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs @@ -637,11 +637,11 @@ private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hash { // don't trace passwords ever! if (null != keyvalue) { - SqlClientEventSource.Log.Trace($" KeyName='{keyname}', KeyValue='{keyvalue}'\n"); + SqlClientEventSource.Log.Trace(" KeyName='{0}', KeyValue='{1}'", keyname, keyvalue); } else { - SqlClientEventSource.Log.Trace($" KeyName='{keyname}'\n"); + SqlClientEventSource.Log.Trace(" KeyName='{0}'", keyname); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs index 86c62b0386..6f5fa6007b 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -34,7 +34,7 @@ static private void TraceException( { try { - SqlClientEventSource.Log.Trace($"{trace}, StackTrace='{Environment.StackTrace}'"); + SqlClientEventSource.Log.Trace(", StackTrace='{0}'", Environment.StackTrace); } catch (System.Security.SecurityException) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index b045f47631..3d7ddbc0f1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -66,7 +66,7 @@ internal int ObjectID public void ClearAllPools() { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) + if (SqlClientEventSource.Log.IsScopeEnabled()) { scopeID = SqlClientEventSource.Log.ScopeEnter(""); } @@ -94,9 +94,9 @@ public void ClearPool(DbConnection connection) ADP.CheckArgumentNull(connection, "connection"); long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) + if (SqlClientEventSource.Log.IsScopeEnabled()) { - scopeID = SqlClientEventSource.Log.ScopeEnter($" {GetObjectId(connection)}#"); + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", GetObjectId(connection)); } try @@ -119,7 +119,7 @@ public void ClearPool(DbConnectionPoolKey key) ADP.CheckArgumentNull(key.ConnectionString, "key.ConnectionString"); long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) + if (SqlClientEventSource.Log.IsScopeEnabled()) { scopeID = SqlClientEventSource.Log.ScopeEnter(" connectionString"); } @@ -169,7 +169,7 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne } if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Non-pooled database connection created."); + SqlClientEventSource.Log.Trace(" {0}#, Non-pooled database connection created.", ObjectID); } return newConnection; } @@ -189,7 +189,7 @@ internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbCo if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Pooled database connection created."); + SqlClientEventSource.Log.Trace(" {0}#, Pooled database connection created.", ObjectID); } return newConnection; @@ -388,7 +388,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred."); + SqlClientEventSource.Log.Trace(" {0}#, GetConnection failed because a pool timeout occurred.", ObjectID); } // If GetConnection failed while the pool is running, the pool timeout occurred. @@ -410,7 +410,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, GetConnection failed because a pool timeout occurred and all retries were exhausted."); + SqlClientEventSource.Log.Trace(" {0}#, GetConnection failed because a pool timeout occurred and all retries were exhausted.", ObjectID); } // exhausted all retries or timed out - give up @@ -440,7 +440,7 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, DisabledPoolGroup={connectionPoolGroup.ObjectID}#"); + SqlClientEventSource.Log.Trace(" {0}#, DisabledPoolGroup={1}#", ObjectID, connectionPoolGroup.ObjectID); } // reusing existing pool option in case user originally used SetConnectionPoolOptions @@ -574,7 +574,7 @@ private void PruneConnectionPoolGroups(object state) if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { // when debugging this method, expect multiple threads at the same time - SqlClientEventSource.Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace(" {0}#", ObjectID); } // First, walk the pool release list and attempt to clear each @@ -598,7 +598,7 @@ private void PruneConnectionPoolGroups(object state) if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" { ObjectID}#, ReleasePool={pool.ObjectID}#"); + SqlClientEventSource.Log.Trace(" {0}#, ReleasePool={1}#", ObjectID, pool.ObjectID); } PerformanceCounters.NumberOfInactiveConnectionPools.Decrement(); @@ -628,7 +628,7 @@ private void PruneConnectionPoolGroups(object state) if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, ReleasePoolGroup={poolGroup.ObjectID}#"); + SqlClientEventSource.Log.Trace(" {0}#, ReleasePoolGroup={1}#", ObjectID, poolGroup.ObjectID); } PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Decrement(); @@ -698,7 +698,7 @@ internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) Debug.Assert(null != poolGroup, "null poolGroup?"); if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, poolGroup={poolGroup.ObjectID}#"); + SqlClientEventSource.Log.Trace(" {0}#, poolGroup={1}#", ObjectID, poolGroup.ObjectID); } lock (_poolGroupsToRelease) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index e3879eebf9..dc4da33138 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -165,7 +165,7 @@ protected internal SysTx.Transaction EnlistedTransaction { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) { - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {value.GetHashCode()}#, Enlisting."); + SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Enlisting.", ObjectID, value.GetHashCode()); } TransactionOutcomeEnlist(value); @@ -395,7 +395,7 @@ internal void ActivateConnection(SysTx.Transaction transaction) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Activating"); + SqlClientEventSource.Log.PoolerTrace(" {0}#, Activating", ObjectID); } #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); @@ -469,7 +469,9 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac Debug.Assert(null != connectionFactory, "null connectionFactory"); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}# Closing."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}# Closing.", ObjectID); + } // if an exception occurs after the state change but before the try block // the connection will be stuck in OpenBusy state. The commented out try-catch @@ -575,7 +577,9 @@ internal void DeactivateConnection() // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Deactivating"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Deactivating", ObjectID); + } #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); Debug.Assert(0 == activateCount, "activated multiple times?"); @@ -612,7 +616,7 @@ virtual internal void DelegatedTransactionEnded() if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Delegated Transaction Completed."); + SqlClientEventSource.Log.Trace(" {0}#, Delegated Transaction Completed.", ObjectID); } if (1 == _pooledCount) @@ -678,7 +682,9 @@ protected internal void DoNotPoolThisConnection() _cannotBePooled = true; if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Marking pooled object as non-poolable so it will be disposed"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Marking pooled object as non-poolable so it will be disposed", ObjectID); + } } /// Ensure that this connection cannot be put back into the pool. @@ -688,7 +694,9 @@ protected internal void DoomThisConnection() _connectionIsDoomed = true; if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Dooming"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Dooming", ObjectID); + } } // Reset connection doomed status so it can be re-connected and pooled. @@ -823,7 +831,9 @@ internal void PrePush(object expectedOwner) //DbConnection x = (expectedOwner as DbConnection); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Preparing to push into pool, owning connection {0}#, pooledCount={ _pooledCount}"); + { + SqlClientEventSource.Log.PoolerTrace(" {}#, Preparing to push into pool, owning connection {0}#, pooledCount={1}", ObjectID, _pooledCount); + } _pooledCount++; _owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2% @@ -856,7 +866,9 @@ internal void PostPop(object newOwner) //DbConnection x = (newOwner as DbConnection); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Preparing to pop from pool, owning connection {0}#, pooledCount={_pooledCount}"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Preparing to pop from pool, owning connection {1}#, pooledCount={2}", ObjectID, 0, _pooledCount); + } //3 // The following tests are retail assertions of things we can't allow to happen. if (null != Pool) @@ -915,7 +927,7 @@ internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitly { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})"); + SqlClientEventSource.Log.Trace(" {0}#, Transaction Completed. (pooledCount={1})", ObjectID, _pooledCount); } // potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new @@ -960,7 +972,7 @@ void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Transaction Completed. (pooledCount={_pooledCount})"); + SqlClientEventSource.Log.Trace(" {0}#, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); } CleanupTransactionOnCompletion(transaction); @@ -981,7 +993,9 @@ internal void SetInStasis() _isInStasis = true; if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID); + } PerformanceCounters.NumberOfStasisConnections.Increment(); } @@ -992,11 +1006,11 @@ private void TerminateStasis(bool returningToPool) { if (returningToPool) { - SqlClientEventSource.Log.PoolerTrace($" { ObjectID}#, Delegated Transaction has ended, connection is closed. Returning to general pool."); + SqlClientEventSource.Log.PoolerTrace(" {0}#, Delegated Transaction has ended, connection is closed. Returning to general pool.", ObjectID); } else { - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Delegated Transaction has ended, connection is closed/leaked. Disposing."); + SqlClientEventSource.Log.PoolerTrace(" {0}#, Delegated Transaction has ended, connection is closed/leaked. Disposing.", ObjectID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index f454ea4c0a..96ca456a34 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -19,7 +19,7 @@ namespace Microsoft.Data.ProviderBase using System.Threading.Tasks; using Microsoft.Data.Common; using Microsoft.Data.SqlClient; - + using SysTx = System.Transactions; sealed internal class DbConnectionPool @@ -84,7 +84,9 @@ internal TransactedConnectionPool(DbConnectionPool pool) _transactedCxns = new Dictionary(); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Constructed for connection pool {_pool.ObjectID}#"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Constructed for connection pool {1}#", ObjectID, _pool.ObjectID); + } } internal int ObjectID @@ -143,7 +145,7 @@ internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction) if (null != transactedObject && SqlClientEventSource.Log.IsPoolerTraceEnabled()) { - SqlClientEventSource.Log.PoolerTrace($" { ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Popped."); + SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } return transactedObject; } @@ -172,7 +174,9 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + } connections.Add(transactedObject); } @@ -210,7 +214,9 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Pushing."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + } connections.Add(transactedObject); } @@ -218,7 +224,9 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt else { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Adding List to transacted pool."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Adding List to transacted pool.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + } // add the connection/transacted object to the list newConnections.Add(transactedObject); @@ -248,7 +256,9 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt } if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Added."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Added.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + } } Pool.PerformanceCounters.NumberOfFreeConnections.Increment(); @@ -258,7 +268,9 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionInternal transactedObject) { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + } TransactedConnectionList connections; int entry = -1; @@ -294,7 +306,9 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern if (0 >= connections.Count) { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Removing List from transacted pool."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Removing List from transacted pool.", ObjectID, transaction.GetHashCode()); + } _transactedCxns.Remove(transaction); // we really need to dispose our connection list; it may have @@ -312,7 +326,9 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern { //Debug.Assert ( false, "TransactionCompletedEvent fired before PutTransactedObject put the connection in the transacted pool." ); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transacted pool not yet created prior to transaction completing. Connection may be leaked."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Transacted pool not yet created prior to transaction completing. Connection may be leaked.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + } } } @@ -541,7 +557,9 @@ internal DbConnectionPool( _state = State.Running; if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Constructed."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Constructed.", ObjectID); + } //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls // StartBackgroundCallbacks after pool is actually in the collection @@ -691,7 +709,9 @@ private void CleanupCallback(Object state) // at least one period but not more than two periods. if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#", ObjectID); + } // Destroy free objects that put us above MinPoolSize from old stack. while (Count > MinPoolSize) @@ -767,7 +787,9 @@ private void CleanupCallback(Object state) Debug.Assert(obj != null, "null connection is not expected"); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, ChangeStacks={obj.ObjectID}#"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, ChangeStacks={1}#", ObjectID, obj.ObjectID); + } Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); Debug.Assert(obj.CanBePooled, "pooled object is not poolable"); @@ -784,7 +806,9 @@ private void CleanupCallback(Object state) internal void Clear() { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Clearing."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Clearing.", ObjectID); + } DbConnectionInternal obj; @@ -823,7 +847,9 @@ internal void Clear() ReclaimEmancipatedObjects(); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Cleared."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Cleared.", ObjectID); + } } private Timer CreateCleanupTimer() @@ -915,7 +941,9 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio } if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {newObj.ObjectID}#, Added to pool."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Added to pool.", ObjectID, newObj.ObjectID); + } // Reset the error wait: _errorWait = ERROR_WAIT_DEFAULT; @@ -977,7 +1005,9 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio private void DeactivateObject(DbConnectionInternal obj) { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Deactivating."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Deactivating.", ObjectID, obj.ObjectID); + } obj.DeactivateConnection(); // we presume this operation is safe outside of a lock... @@ -1119,12 +1149,16 @@ internal void DestroyObject(DbConnectionInternal obj) if (obj.IsTxRootWaitingForTxEnd) { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Has Delegated Transaction, waiting to Dispose."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Has Delegated Transaction, waiting to Dispose.", ObjectID, obj.ObjectID); + } } else { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removing from pool."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Removing from pool.", ObjectID, obj.ObjectID); + } bool removed = false; lock (_objectList) @@ -1136,13 +1170,20 @@ internal void DestroyObject(DbConnectionInternal obj) if (removed) { - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Removed from pool."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Removed from pool.", ObjectID, obj.ObjectID); + } + PerformanceCounters.NumberOfPooledConnections.Decrement(); } + obj.Dispose(); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Disposed."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Disposed.", ObjectID, obj.ObjectID); + } PerformanceCounters.HardDisconnectsPerSecond.Increment(); } @@ -1151,7 +1192,9 @@ internal void DestroyObject(DbConnectionInternal obj) private void ErrorCallback(Object state) { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Resetting Error handling."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Resetting Error handling.", ObjectID); + } _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); @@ -1327,7 +1370,10 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource {ObjectID}#, DbConnectionInternal State != Running."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, DbConnectionInternal State != Running.", ObjectID); + } + connection = null; return true; } @@ -1374,7 +1420,9 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj PerformanceCounters.SoftConnectsPerSecond.Increment(); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Getting connection."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Getting connection.", ObjectID); + } // If automatic transaction enlistment is required, then we try to // get the connection from the transacted connection pool first. @@ -1429,7 +1477,9 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case WAIT_TIMEOUT: if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Wait timed out."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Wait timed out.", ObjectID); + } Interlocked.Decrement(ref _waitCount); connection = null; @@ -1437,14 +1487,20 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case ERROR_HANDLE: // Throw the error that PoolCreateRequest stashed. - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Errors are set."); + if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Errors are set.", ObjectID); + } + Interlocked.Decrement(ref _waitCount); throw TryCloneCachedException(); case CREATION_HANDLE: if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Creating new connection."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Creating new connection.", ObjectID); + } try { @@ -1499,7 +1555,9 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj if ((obj != null) && (!obj.IsConnectionAlive())) { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, found dead and removed.", ObjectID, obj.ObjectID); + } DestroyObject(obj); obj = null; // Setting to null in case creating a new object fails @@ -1512,7 +1570,9 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj try { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Creating new connection."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Creating new connection.", ObjectID); + } obj = UserCreateRequest(owningObject, userOptions); } @@ -1525,7 +1585,9 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj { // Timeout waiting for creation semaphore - return null if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Wait timed out."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Wait timed out.", ObjectID); + } connection = null; return false; @@ -1538,7 +1600,9 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj Debug.Assert(waitForMultipleObjectsExHR != 0, "WaitForMultipleObjectsEx failed but waitForMultipleObjectsExHR remained 0"); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Wait failed.\n"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Wait failed.", ObjectID); + } Interlocked.Decrement(ref _waitCount); Marshal.ThrowExceptionForHR(waitForMultipleObjectsExHR); @@ -1546,28 +1610,36 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case (WAIT_ABANDONED + SEMAPHORE_HANDLE): if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Semaphore handle abandonded."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Semaphore handle abandonded.", ObjectID); + } Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(SEMAPHORE_HANDLE, _waitHandles.PoolSemaphore); case (WAIT_ABANDONED + ERROR_HANDLE): if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Error handle abandonded."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Error handle abandonded.", ObjectID); + } Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(ERROR_HANDLE, _waitHandles.ErrorEvent); case (WAIT_ABANDONED + CREATION_HANDLE): if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Creation handle abandoned."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Creation handle abandoned.", ObjectID); + } Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(CREATION_HANDLE, _waitHandles.CreationSemaphore); default: if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, WaitForMultipleObjects={waitResult}"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, WaitForMultipleObjects={1}", ObjectID, waitResult); + } Interlocked.Decrement(ref _waitCount); throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult); @@ -1635,7 +1707,9 @@ internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbCon PerformanceCounters.SoftConnectsPerSecond.Increment(); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, replacing connection."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, replacing connection.", ObjectID); + } DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); @@ -1679,7 +1753,9 @@ private DbConnectionInternal GetFromGeneralPool() if (null != obj) { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from general pool."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Popped from general pool.", ObjectID, obj.ObjectID); + } PerformanceCounters.NumberOfFreeConnections.Decrement(); } @@ -1698,7 +1774,9 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac if (null != obj) { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Popped from transacted pool."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Popped from transacted pool.", ObjectID, obj.ObjectID); + } PerformanceCounters.NumberOfFreeConnections.Decrement(); @@ -1711,7 +1789,9 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac catch { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, found dead and removed.", ObjectID, obj.ObjectID); + } DestroyObject(obj); throw; @@ -1720,7 +1800,9 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac else if (!obj.IsConnectionAlive()) { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, found dead and removed."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, found dead and removed.", ObjectID, obj.ObjectID); + } DestroyObject(obj); obj = null; @@ -1738,9 +1820,9 @@ private void PoolCreateRequest(object state) // creation mutex has not been obtained long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) + if (SqlClientEventSource.Log.IsScopeEnabled()) { - scopeID = SqlClientEventSource.Log.PoolerScopeEnter($" {ObjectID}#"); + scopeID = SqlClientEventSource.Log.PoolerScopeEnter(" {0}#", ObjectID); } try @@ -1828,7 +1910,9 @@ private void PoolCreateRequest(object state) { // trace waitResult and ignore the failure if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called WaitForSingleObject failed {waitResult}"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, PoolCreateRequest called WaitForSingleObject failed {1}", ObjectID, waitResult); + } } } catch (Exception e) @@ -1843,7 +1927,9 @@ private void PoolCreateRequest(object state) // There is no further action we can take beyond tracing. The error will be // thrown to the user the next time they request a connection. if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, PoolCreateRequest called CreateConnection which threw an exception: {e}"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, PoolCreateRequest called CreateConnection which threw an exception: {1}", ObjectID, e); + } } finally { @@ -1878,7 +1964,9 @@ internal void PutNewObject(DbConnectionInternal obj) // Debug.Assert(obj.CanBePooled, "non-poolable object in pool"); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Pushing to general pool."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Pushing to general pool.", ObjectID, obj.ObjectID); + } _stackNew.Push(obj); _waitHandles.PoolSemaphore.Release(1); @@ -1929,7 +2017,9 @@ internal void PutObjectFromTransactedPool(DbConnectionInternal obj) // done and all transactions are ended. if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Transaction has ended."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Transaction has ended.", ObjectID, obj.ObjectID); + } if (_state == State.Running && obj.CanBePooled) { @@ -1956,7 +2046,9 @@ private bool ReclaimEmancipatedObjects() bool emancipatedObjectFound = false; if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#", ObjectID); + } List reclaimedObjects = new List(); int count; @@ -2011,7 +2103,9 @@ private bool ReclaimEmancipatedObjects() DbConnectionInternal obj = reclaimedObjects[i]; if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Connection {obj.ObjectID}#, Reclaiming."); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Reclaiming.", ObjectID, obj.ObjectID); + } PerformanceCounters.NumberOfReclaimedConnections.Increment(); @@ -2026,7 +2120,9 @@ private bool ReclaimEmancipatedObjects() internal void Startup() { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, CleanupWait={_cleanupWait}"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, CleanupWait={1}", ObjectID, _cleanupWait); + } _cleanupTimer = CreateCleanupTimer(); if (NeedToReplenish) @@ -2038,7 +2134,9 @@ internal void Startup() internal void Shutdown() { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#\n"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#", ObjectID); + } _state = State.ShuttingDown; @@ -2062,7 +2160,9 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern // Note: connection may still be associated with transaction due to Explicit Unbinding requirement. if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Transaction {transaction.GetHashCode()}#, Connection {transactedObject.ObjectID}#, Transaction Completed"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + } // called by the internal connection when it get's told that the // transaction is completed. We tell the transacted pool to remove diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs index 8a8b7df99d..8511aab5eb 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -276,7 +276,7 @@ private bool MarkPoolGroupAsActive() if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Active"); + SqlClientEventSource.Log.Trace(" {0}#, Active", ObjectID); } } return (PoolGroupStateActive == _state); @@ -342,7 +342,7 @@ internal bool Prune() if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Idle"); + SqlClientEventSource.Log.Trace(" {0}#, Idle", ObjectID); } } else if (PoolGroupStateIdle == _state) @@ -351,7 +351,7 @@ internal bool Prune() if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Disabled"); + SqlClientEventSource.Log.Trace(" {0}#, Disabled", ObjectID); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs index 2c91a20711..2c5197a236 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs @@ -12,7 +12,7 @@ namespace Microsoft.Data.SqlClient using System.Threading; using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; - + using SysTx = System.Transactions; public sealed partial class SqlConnection : DbConnection @@ -89,7 +89,7 @@ private string ConnectionString_Get() { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace(" {0}#", ObjectID); } bool hidePassword = InnerConnection.ShouldHidePassword; @@ -139,7 +139,7 @@ private void ConnectionString_Set(DbConnectionPoolKey key) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, '{cstr}'"); + SqlClientEventSource.Log.Trace(" {0}#, '{1}'", ObjectID, cstr); } } @@ -192,11 +192,11 @@ internal void Abort(Exception e) { if (e is OutOfMemoryException) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {"OutOfMemory"}"); + SqlClientEventSource.Log.Trace(" {0}#, Aborting operation due to asynchronous exception: {'OutOfMemory'}", ObjectID); } else { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Aborting operation due to asynchronous exception: {e.ToString()}"); + SqlClientEventSource.Log.Trace(" {0}#, Aborting operation due to asynchronous exception: {1}", ObjectID, e.ToString()); } } } @@ -214,7 +214,7 @@ override protected DbCommand CreateDbCommand() long scopeID = 0; if (SqlClientEventSource.Log.IsEnabled()) { - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); } try @@ -264,7 +264,7 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection enlisting in a transaction."); + SqlClientEventSource.Log.Trace(" {0}#, Connection enlisting in a transaction.", ObjectID); } SysTx.Transaction indigoTransaction = null; @@ -294,7 +294,7 @@ override public void EnlistTransaction(SysTx.Transaction transaction) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection enlisting in a transaction."); + SqlClientEventSource.Log.Trace(" {0}#, Connection enlisting in a transaction.", ObjectID); } // If we're currently enlisted in a transaction and we were called diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs index a6e8cc1e1d..ddf5925e9a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs @@ -123,7 +123,7 @@ static LocalDBCreateInstanceDelegate LocalDBCreateInstance if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" GetProcAddress for LocalDBCreateInstance error 0x{hResult}"); + SqlClientEventSource.Log.Trace(" GetProcAddress for LocalDBCreateInstance error 0x{0}", hResult); } throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); @@ -170,7 +170,7 @@ static LocalDBFormatMessageDelegate LocalDBFormatMessage if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" GetProcAddress for LocalDBFormatMessage error 0x{hResult}"); + SqlClientEventSource.Log.Trace(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); } throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); @@ -361,7 +361,7 @@ internal static void CreateLocalDBInstance(string instance) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Starting creation of instance {instance} version {instanceInfo.version}"); + SqlClientEventSource.Log.Trace(" Starting creation of instance {0} version {1}", instance, instanceInfo.version); } if (hr < 0) @@ -371,7 +371,7 @@ internal static void CreateLocalDBInstance(string instance) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Finished creation of instance {instance}"); + SqlClientEventSource.Log.Trace(" Finished creation of instance {0}", instance); } instanceInfo.created = true; // mark instance as created } // CreateLocalDbInstance diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs index 433d7ccc01..a6f8e8d78e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs @@ -269,7 +269,7 @@ internal override void MessagePosted(int number, byte state, byte errorClass, st { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {0}#, number={number} state={state} errorClass={errorClass} server='{server ?? ""}' message='{message ?? ""}' procedure='{procedure ?? ""}' linenumber={lineNumber}."); + SqlClientEventSource.Log.Trace(" {0}#, number={1} state={2} errorClass={3} server='{4}' message='{5}' procedure='{6}' linenumber={7}.", 0, number, state, errorClass, server ?? "", message ?? "", procedure ?? "", lineNumber); } SqlError error = new SqlError(number, state, errorClass, server, message, procedure, lineNumber); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index c4bb8ab87f..2bcedd8b88 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs @@ -597,14 +597,13 @@ private Task CreateAndExecuteInitialQueryAsync(out Bulk if (SqlClientEventSource.Log.IsTraceEnabled()) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace($" Initial Query: '{TDSCommand}'"); - } + SqlClientEventSource.Log.Trace(" Initial Query: '{0}'", TDSCommand); } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID %ls", ObjectID); + } Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); @@ -896,7 +895,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i private Task SubmitUpdateBulkCommand(string TDSCommand) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}\n"); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 135fd12de9..aba11927f3 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -27,6 +27,7 @@ public class SqlClientEventSource : EventSource private const int PoolerScopeEnterId = 8; private const int PoolerTraceId = 9; + #region Keywords /// public class Keywords { @@ -57,7 +58,9 @@ public class Keywords /// public const EventKeywords Advanced = (EventKeywords)512; } + #endregion + #region Enable/Disable Events [NonEvent] internal bool IsTraceEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Trace); @@ -83,8 +86,181 @@ public class Keywords internal bool IsPoolerTraceEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.PoolerTrace); [NonEvent] - internal bool IsAdvanceTraceOn() => SqlClientEventSource.Log.IsEnabled(EventLevel.LogAlways, Keywords.Advanced); + internal bool IsAdvanceTraceOn() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Advanced); + #endregion + #region overloads + [NonEvent] + internal void Trace(string message, T0 args0) + { + if (Log.IsTraceEnabled()) + { + Trace(string.Format(message), args0); + } + } + + [NonEvent] + internal void Trace(string message, T0 args0, T1 args1) + { + if (Log.IsTraceEnabled()) + { + Trace(string.Format(message, args0, args1)); + } + } + + [NonEvent] + internal void Trace(string message, T0 args0, T1 args1, T2 args2) + { + if (Log.IsTraceEnabled()) + { + Trace(string.Format(message, args0, args1, args2)); + } + } + + [NonEvent] + internal void Trace(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + if (Log.IsTraceEnabled()) + { + Trace(string.Format(message, args0, args1, args2, args3)); + } + } + + [NonEvent] + internal void Trace(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) + { + if (Log.IsTraceEnabled()) + { + Trace(string.Format(message, args0, args1, args2, args3, args4, args5)); + } + } + + [NonEvent] + internal void Trace(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5, T6 args6, T7 args7) + { + if (Log.IsTraceEnabled()) + { + Trace(string.Format(message, args0, args1, args2, args3, args4, args5, args6, args7)); + } + } + + [NonEvent] + internal long ScopeEnter(string message, T0 args0) + { + return ScopeEnter(string.Format(message, args0)); + } + + [NonEvent] + internal long ScopeEnter(string message, T0 args0, T1 args1) + { + return ScopeEnter(string.Format(message, args0, args1)); + } + + [NonEvent] + internal long ScopeEnter(string message, T0 args0, T1 args1, T2 args2) + { + return ScopeEnter(string.Format(message, args0, args1, args2)); + } + + [NonEvent] + internal long ScopeEnter(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + return ScopeEnter(string.Format(message, args0, args1, args2, args3)); + } + + [NonEvent] + + internal long PoolerScopeEnter(string message, T0 args0) + { + return PoolerScopeEnter(string.Format(message, args0)); + } + + [NonEvent] + internal long NotificationsScopeEnter(string message, T0 args0) + { + return NotificationsScopeEnter(string.Format(message, args0)); + } + + [NonEvent] + internal long NotificationsScopeEnter(string message, T0 args0, T1 args1) + { + return NotificationsScopeEnter(string.Format(message, args0, args1)); + } + + [NonEvent] + internal long NotificationsScopeEnter(string message, T0 args0, T1 args1, T2 args2) + { + return NotificationsScopeEnter(string.Format(message, args0, args1, args2)); + } + + [NonEvent] + internal long NotificationsScopeEnter(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + return NotificationsScopeEnter(string.Format(message, args0, args1, args2, args3)); + } + + [NonEvent] + internal void PoolerTrace(string message, T0 args0) + { + PoolerTrace(string.Format(message, args0)); + } + + [NonEvent] + internal void PoolerTrace(string message, T0 args0, T1 args1) + { + PoolerTrace(string.Format(message, args0, args1)); + } + + [NonEvent] + internal void PoolerTrace(string message, T0 args0, T1 args1, T2 args2) + { + PoolerTrace(string.Format(message, args0, args1, args2)); + } + + [NonEvent] + internal void PoolerTrace(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + PoolerTrace(string.Format(message, args0, args1, args2, args3)); + } + + [NonEvent] + internal void CorrelationTrace(string message, T0 args0) + { + CorrelationTrace(string.Format(message, args0)); + } + + [NonEvent] + internal void CorrelationTrace(string message, T0 args0, T1 args1) + { + CorrelationTrace(string.Format(message, args0, args1)); + } + + [NonEvent] + internal void NotificationsTrace(string message, T0 args0) + { + NotificationsTrace(string.Format(message, args0)); + } + + [NonEvent] + internal void NotificationsTrace(string message, T0 args0, T1 args1) + { + NotificationsTrace(string.Format(message, args0, args1)); + } + + [NonEvent] + internal void NotificationsTrace(string message, T0 args0, T1 args1, T2 args2) + { + NotificationsTrace(string.Format(message, args0, args1, args2)); + } + + [NonEvent] + internal void NotificationsTrace(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + NotificationsTrace(string.Format(message, args0, args1, args2, args3)); + } + #endregion + + #region Events [Event(TraceEventId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] internal void Trace(string message) { @@ -97,9 +273,8 @@ internal long ScopeEnter(string message) long scopeId = 0; if (SqlClientEventSource.Log.IsEnabled()) { - StringBuilder MsgstrBldr = new StringBuilder(message); scopeId = Interlocked.Increment(ref s_nextScopeId); - WriteEvent(EnterScopeId, MsgstrBldr.Append($" Scope ID ='[{ scopeId}]'")); + WriteEvent(EnterScopeId, scopeId, message); } return scopeId; } @@ -164,5 +339,6 @@ internal void PoolerTrace(string message) { WriteEvent(PoolerTraceId, message); } + #endregion } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index 0e82c45e21..a6e28d491e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -345,9 +345,9 @@ internal CommandEventSink(SqlCommand command) : base() internal override void StatementCompleted(int rowsAffected) { - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {_command.ObjectID}#, rowsAffected={rowsAffected}."); + SqlClientEventSource.Log.Trace(" {0}#, rowsAffected={1}.", _command.ObjectID, rowsAffected); } _command.InternalRecordsAffected = rowsAffected; @@ -361,25 +361,24 @@ internal override void StatementCompleted(int rowsAffected) internal override void BatchCompleted() { - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {_command.ObjectID}#."); + SqlClientEventSource.Log.Trace(" {0}#.", _command.ObjectID); } } internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 parameterValues) { - - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {_command.ObjectID}# metaData.Length={((null != metaData) ? metaData.Length : -1)}."); + SqlClientEventSource.Log.Trace(" {0}# metaData.Length={1}.", _command.ObjectID, (null != metaData) ? metaData.Length : -1); } if (null != metaData && SqlClientEventSource.Log.IsTraceEnabled()) { for (int i = 0; i < metaData.Length; i++) { - SqlClientEventSource.Log.Trace($" {_command.ObjectID}#, metaData[{i}] is {metaData[i].GetType().ToString()}{metaData[i].TraceString()}"); + SqlClientEventSource.Log.Trace(" {0}#, metaData[{1}] is {2}{3}", _command.ObjectID, i, metaData[i].GetType().ToString(), metaData[i].TraceString()); } } @@ -389,9 +388,9 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter parameterValues, int ordinal) { - if (null != metaData && SqlClientEventSource.Log.IsTraceEnabled()) + if (null != metaData && SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {_command.ObjectID}#, metaData[{ordinal}] is {metaData.GetType().ToString()}{ metaData.TraceString()}"); + SqlClientEventSource.Log.Trace(" {0}#, metaData[{1}] is {2}{ 3}", _command.ObjectID, ordinal, metaData.GetType().ToString(), metaData.TraceString()); } Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion); @@ -580,7 +579,7 @@ private SqlCommand(SqlCommand from) : this() if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, {((null != value) ? value.ObjectID : -1)}#"); + SqlClientEventSource.Log.Trace(" {0}#, {1}#", ObjectID, (null != value) ? value.ObjectID : -1); } } } @@ -661,7 +660,7 @@ public SqlNotificationRequest Notification { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace(" {0}#", ObjectID); } _sqlDep = null; @@ -715,7 +714,7 @@ internal SqlStatistics Statistics // TODO: Add objid here if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace(" {0}#", ObjectID); } _transaction = value; } @@ -753,7 +752,7 @@ override public string CommandText { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, String Value = '{value}'"); + SqlClientEventSource.Log.Trace(" {0}#, String Value = '{1}'", ObjectID, value); } if (0 != ADP.SrcCompare(_commandText, value)) @@ -794,7 +793,7 @@ override public int CommandTimeout { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, {value}"); + SqlClientEventSource.Log.Trace(" {0}#, {1}", ObjectID, value); } if (value < 0) @@ -843,7 +842,7 @@ override public CommandType CommandType { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, {(int)value}{_commandType}"); + SqlClientEventSource.Log.Trace(" {0}#, {1}{2}", ObjectID, (int)value, _commandType); } if (_commandType != value) { @@ -989,7 +988,7 @@ internal void OnStatementCompleted(int recordCount) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, recordCount={recordCount}"); + SqlClientEventSource.Log.Trace(" {0}#, recordCount={1}", ObjectID, recordCount); } handler(this, new StatementCompletedEventArgs(recordCount)); @@ -1031,11 +1030,13 @@ override public void Prepare() SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); statistics = SqlStatistics.StartTimer(Statistics); @@ -1203,7 +1204,7 @@ internal void Unprepare() _cachedMetaData = null; if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Command unprepared."); + SqlClientEventSource.Log.Trace(" {0}#, Command unprepared.", ObjectID); } } @@ -1215,11 +1216,15 @@ internal void Unprepare() override public void Cancel() { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($"< sc.SqlCommand.Cancel | API > {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } SqlStatistics statistics = null; try @@ -1383,11 +1388,15 @@ override public object ExecuteScalar() SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } bool success = false; int? sqlExceptionNumber = null; @@ -1456,11 +1465,15 @@ override public int ExecuteNonQuery() SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } bool success = false; int? sqlExceptionNumber = null; @@ -1499,8 +1512,10 @@ internal void ExecuteToPipe(SmiContext pipeContext) SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } try { @@ -1528,7 +1543,9 @@ public IAsyncResult BeginExecuteNonQuery() public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } SqlConnection.ExecutePermission.Demand(); return BeginExecuteNonQueryInternal(0, callback, stateObject, 0, inRetry: false); @@ -1756,7 +1773,9 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) finally { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } } } @@ -1775,7 +1794,9 @@ private void ThrowIfReconnectionHasBeenCanceled() private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); @@ -2039,7 +2060,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Command executed as RPC."); + SqlClientEventSource.Log.Trace(" {0}#, Command executed as RPC.", ObjectID); } SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, methodName, completion, timeout, out task, out usedCache, asyncWrite, inRetry); @@ -2095,11 +2116,15 @@ public XmlReader ExecuteXmlReader() SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } bool success = false; int? sqlExceptionNumber = null; @@ -2141,7 +2166,9 @@ public IAsyncResult BeginExecuteXmlReader() public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID); + } SqlConnection.ExecutePermission.Demand(); return BeginExecuteXmlReaderInternal(CommandBehavior.SequentialAccess, callback, stateObject, 0, inRetry: false); @@ -2296,14 +2323,18 @@ public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) finally { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{}#, ActivityID {1}", ObjectID); + } } } private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); @@ -2424,7 +2455,9 @@ public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObjec override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } return ExecuteReader(behavior, ADP.ExecuteReader); } @@ -2435,11 +2468,15 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } try { @@ -2456,10 +2493,16 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) /// new public SqlDataReader ExecuteReader(CommandBehavior behavior) { - var scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, behavior={(int)behavior}"); + var scopeID = 0; + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + SqlClientEventSource.Log.ScopeEnter(" {0}#, behavior={1}", ObjectID, (int)behavior); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{ObjectID}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior); + } try { @@ -2483,7 +2526,9 @@ public IAsyncResult BeginExecuteReader(CommandBehavior behavior) public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior); + } SqlConnection.ExecutePermission.Demand(); return BeginExecuteReaderInternal(behavior, callback, stateObject, 0, inRetry: false); @@ -2567,14 +2612,18 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) finally { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } } } private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); @@ -2977,7 +3026,9 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } SqlConnection.ExecutePermission.Demand(); @@ -3064,7 +3115,9 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b new public Task ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, behavior={(int)behavior}, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior); + } SqlConnection.ExecutePermission.Demand(); @@ -3200,8 +3253,9 @@ public Task ExecuteXmlReaderAsync() public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); - + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3811,7 +3865,7 @@ private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, b if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Command executed as SQLBATCH."); + SqlClientEventSource.Log.Trace(" {0}#, Command executed as SQLBATCH.", ObjectID); } Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(this.CommandText, timeout, this.Notification, _stateObj, sync: true); @@ -3875,9 +3929,9 @@ private void RunExecuteNonQuerySmi(bool sendToPipe) SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, cmdBehavior={(int)CommandBehavior.Default}."); + SqlClientEventSource.Log.Trace(" {0}#, innerConnection={1}#, transactionId=0x{2}, cmdBehavior={3}.", ObjectID, innerConnection.ObjectID, transactionId, (int)CommandBehavior.Default); } if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) @@ -5357,7 +5411,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi Debug.Assert(!IsUserPrepared, "CommandType.Text with no params should not be prepared!"); if (returnStream && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Command executed as SQLBATCH."); + SqlClientEventSource.Log.Trace(" {0}#, Command executed as SQLBATCH.", ObjectID); } string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior); @@ -5422,7 +5476,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi rpc.options = TdsEnums.RPC_NOMETADATA; if (returnStream && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Command executed as RPC."); + SqlClientEventSource.Log.Trace(" {0}#, Command executed as RPC.", ObjectID); } // TODO: Medusa: Unprepare only happens for SQL 7.0 which may be broken anyway (it's not re-prepared). Consider removing the reset here if we're really dropping 7.0 support. @@ -5445,7 +5499,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi optionSettings = GetSetOptionsString(cmdBehavior); if (returnStream && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Command executed as RPC."); + SqlClientEventSource.Log.Trace(" {0}#, Command executed as RPC.", ObjectID); } // turn set options ON if (null != optionSettings) @@ -5540,9 +5594,9 @@ private SqlDataReader RunExecuteReaderSmi(CommandBehavior cmdBehavior, RunBehavi SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, innerConnection={innerConnection.ObjectID}#, transactionId=0x{transactionId}, commandBehavior={(int)cmdBehavior}."); + SqlClientEventSource.Log.Trace(" {0}#, innerConnection={1}#, transactionId=0x{2}, commandBehavior={(int)cmdBehavior}.", ObjectID, innerConnection.ObjectID, transactionId); } if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) @@ -5766,7 +5820,7 @@ public SqlCommand Clone() if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, clone={clone.ObjectID}#"); + SqlClientEventSource.Log.Trace(" {0}#, clone={1}#", ObjectID, clone.ObjectID); } return clone; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index 8c71c131ff..8277c81cb8 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -1102,8 +1102,10 @@ public SqlTransaction BeginTransaction(string transactionName) override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, isolationLevel={(int)isolationLevel}"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#, isolationLevel={1}", ObjectID, (int)isolationLevel); + } try { @@ -1131,8 +1133,10 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, iso={(int)iso}, transactionName='{(ADP.IsEmpty(transactionName) ? "None" : transactionName)}'"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#, iso={1}, transactionName='{2}'", ObjectID, (int)iso, (ADP.IsEmpty(transactionName) ? "None" : transactionName)); + } try { @@ -1172,7 +1176,9 @@ override public void ChangeDatabase(string database) RepairInnerConnection(); if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, EventSource.GetGuid(typeof(SqlClientEventSource))); + } TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -1267,11 +1273,15 @@ void CloseInnerConnection() override public void Close() { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, EventSource.GetGuid(typeof(SqlClientEventSource))); + } try { @@ -1354,6 +1364,7 @@ override public void Close() { SqlDebugContext sdc = _sdc; _sdc = null; + SqlClientEventSource.Log.ScopeLeave(scopeID); if (sdc != null) @@ -1409,11 +1420,15 @@ public void EnlistDistributedTransaction(System.EnterpriseServices.ITransaction override public void Open() { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" ObjectID: {ObjectID}, ActivityID {SqlClientEventSource.Log.Guid}"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" ObjectID: {0}, ActivityID {1}", ObjectID); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, EventSource.GetGuid(typeof(SqlClientEventSource))); + } try { @@ -1483,7 +1498,7 @@ private async Task ReconnectAsync(int timeout) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Orginal ClientConnectionID: {_originalConnectionId.ToString()} - reconnection cancelled."); + SqlClientEventSource.Log.Trace(" Orginal ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId.ToString()); } return; } @@ -1508,7 +1523,7 @@ private async Task ReconnectAsync(int timeout) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Reconnection suceeded. ClientConnectionID {_originalConnectionId.ToString()} -> {ClientConnectionId.ToString()}"); + SqlClientEventSource.Log.Trace(" Reconnection suceeded. ClientConnectionID {0} -> {1}", _originalConnectionId.ToString(), ClientConnectionId.ToString()); } return; } @@ -1516,14 +1531,14 @@ private async Task ReconnectAsync(int timeout) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Orginal ClientConnectionID {_originalConnectionId} - reconnection attempt failed error {e.Message}"); + SqlClientEventSource.Log.Trace(" Orginal ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message); } if (attempt == retryCount - 1) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Orginal ClientConnectionID {_originalConnectionId.ToString()} - give up reconnection"); + SqlClientEventSource.Log.Trace(" Orginal ClientConnectionID {0} - give up reconnection", _originalConnectionId.ToString()); } throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); @@ -1594,7 +1609,7 @@ internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Connection ClientConnectionID {_originalConnectionId.ToString()} is invalid, reconnecting"); + SqlClientEventSource.Log.Trace(" Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId.ToString()); } _recoverySessionData = cData; if (beforeDisconnect != null) @@ -1688,11 +1703,15 @@ void CancelOpenAndWait() public override Task OpenAsync(CancellationToken cancellationToken) { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.PoolerScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.PoolerScopeEnter(" {0}#", ObjectID); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, EventSource.GetGuid(typeof(SqlClientEventSource))); + } try { @@ -1793,7 +1812,7 @@ internal void Retry(Task retryTask) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {_parent.ObjectID}#"); + SqlClientEventSource.Log.Trace(" {0}#", _parent.ObjectID); } _registration.Dispose(); try @@ -2143,7 +2162,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {ObjectID}#, Connection broken."); + SqlClientEventSource.Log.Trace(" {0}#, Connection broken.", ObjectID); } Close(); @@ -2156,7 +2175,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {ObjectID}#, Connection broken."); + SqlClientEventSource.Log.Trace(" {0}#, Connection broken.", ObjectID); } Close(); } @@ -2268,7 +2287,7 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Message='{imeventValue}'"); + SqlClientEventSource.Log.Trace(" {0}#, Message='{1}'", ObjectID, imeventValue); } SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage]; @@ -2484,11 +2503,15 @@ private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, s public static void ChangePassword(string connectionString, string newPassword) { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) + if (SqlClientEventSource.Log.IsScopeEnabled()) + { scopeID = SqlClientEventSource.Log.ScopeEnter(""); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ActivityID {0}", EventSource.GetGuid(typeof(SqlClientEventSource))); + } try { @@ -2536,11 +2559,15 @@ public static void ChangePassword(string connectionString, string newPassword) public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) + if (SqlClientEventSource.Log.IsScopeEnabled()) + { scopeID = SqlClientEventSource.Log.ScopeEnter(""); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ActivityID {EventSource.GetGuid(typeof(SqlClientEventSource))}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ActivityID {0}", EventSource.GetGuid(typeof(SqlClientEventSource))); + } try { @@ -2711,7 +2738,7 @@ private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) { if (asmRef.Version != TypeSystemAssemblyVersion && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" SQL CLR type version change: Server sent {asmRef.Version.ToString()}, client will instantiate {TypeSystemAssemblyVersion.ToString()}"); + SqlClientEventSource.Log.Trace(" SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version.ToString(), TypeSystemAssemblyVersion.ToString()); } asmRef.Version = TypeSystemAssemblyVersion; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs index 88e72daaaf..25000ded38 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs @@ -196,7 +196,7 @@ override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($"Set connection pool CreateTimeout={connectionTimeout} when AD Interactive is in use."); + SqlClientEventSource.Log.Trace("Set connection pool CreateTimeout={0} when AD Interactive is in use.", connectionTimeout); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs index c0273caf68..cd1553ef1e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs @@ -58,7 +58,7 @@ internal void AliasCheck(string server) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" alias change detected. Clearing PoolGroup"); + SqlClientEventSource.Log.Trace(" alias change detected. Clearing PoolGroup"); } base.PoolGroup.Clear(); @@ -106,7 +106,7 @@ internal void FailoverCheck(SqlInternalConnection connection, bool actualUseFail // TODO: will connections in progress somehow be active for two different datasources? if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Failover detected. failover partner='{actualFailoverPartner}'. Clearing PoolGroup"); + SqlClientEventSource.Log.Trace(" Failover detected. failover partner='{0}'. Clearing PoolGroup", actualFailoverPartner); } base.PoolGroup.Clear(); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index 8ae19e4fc4..bb2eb5ac3b 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -145,7 +145,7 @@ override public int UpdateBatchSize if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, {value}"); + SqlClientEventSource.Log.Trace(" {0}#, {1}", ObjectID, value); } } } @@ -255,7 +255,7 @@ override protected int ExecuteBatch() Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID %ls"); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); return _commandSet.ExecuteNonQuery(); } @@ -281,7 +281,7 @@ override protected void InitializeBatching() { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace(" {0}#", ObjectID); } _commandSet = new SqlCommandSet(); SqlCommand command = SelectCommand; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs index 871c69760c..e64f15c448 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -941,8 +941,10 @@ override public void Close() SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } try { @@ -1675,8 +1677,10 @@ override public DataTable GetSchemaTable() SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } try { @@ -3610,8 +3614,8 @@ private bool TryNextResult(out bool more) SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -3819,8 +3823,8 @@ private bool TryReadInternal(bool setTimeout, out bool more) SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -4488,7 +4492,9 @@ private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateO if (parser.State == TdsParserState.OpenLoggedIn) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID '{SqlClientEventSource.Log.Guid}'"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID '{1}'", ObjectID); + } Task executeTask = parser.TdsExecuteSQLBatch(_resetOptionsString, (_command != null) ? _command.CommandTimeout : 0, null, stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -4802,8 +4808,10 @@ private void AssertReaderState(bool requireData, bool permitAsync, int? columnIn public override Task NextResultAsync(CancellationToken cancellationToken) { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } try { @@ -4851,7 +4859,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" attempt retry {ObjectID}#"); + SqlClientEventSource.Log.Trace(" attempt retry {0}#", ObjectID); } PrepareForAsyncContinuation(); } @@ -4936,7 +4944,7 @@ internal Task GetBytesAsync(int i, byte[] buffer, int index, int length, in { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" attempt retry {ObjectID}#"); + SqlClientEventSource.Log.Trace(" attempt retry {0}#", ObjectID); } PrepareForAsyncContinuation(); @@ -5110,8 +5118,10 @@ private Task GetBytesAsyncReadDataStage(int i, byte[] buffer, int index, in public override Task ReadAsync(CancellationToken cancellationToken) { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } try { @@ -5234,7 +5244,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" attempt retry {ObjectID}#"); + SqlClientEventSource.Log.Trace(" attempt retry {0}#", ObjectID); } PrepareForAsyncContinuation(); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs index b125223dbb..3526f05887 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs @@ -377,8 +377,10 @@ public override void Close() private void CloseInternal(bool closeConnection) { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } bool processFinallyBlock = true; try @@ -440,7 +442,10 @@ internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) { long scopeID = 0; if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } + try { _hasRows = false; @@ -474,7 +479,9 @@ internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) finally { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + { SqlClientEventSource.Log.ScopeLeave(scopeID); + } } } @@ -496,7 +503,9 @@ internal unsafe bool InternalRead(bool ignoreNonFatalErrors) { long scopeID = 0; if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } try { @@ -537,7 +546,9 @@ internal unsafe bool InternalRead(bool ignoreNonFatalErrors) finally { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + { SqlClientEventSource.Log.ScopeLeave(scopeID); + } } } @@ -1331,14 +1342,14 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {reader.ObjectID}#, md.Length={mdLength} nextEventIsRow={nextEventIsRow}."); + SqlClientEventSource.Log.Trace(" {0}#, md.Length={1} nextEventIsRow={2}.", reader.ObjectID, mdLength, nextEventIsRow); if (null != md) { for (int i = 0; i < md.Length; i++) { - SqlClientEventSource.Log.Trace($" {reader.ObjectID}#, metaData[{i}] is {md[i].GetType().ToString()}{md[i].TraceString()}"); + SqlClientEventSource.Log.Trace(" {0}#, metaData[{1}] is {2}{3}", reader.ObjectID, i, md[i].GetType().ToString(), md[i].TraceString()); } } } @@ -1350,7 +1361,7 @@ internal override void RowAvailable(ITypedGetters row) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {reader.ObjectID}# (v2)."); + SqlClientEventSource.Log.Trace(" {0}# (v2).", reader.ObjectID); } this.reader.RowAvailable(row); } @@ -1359,7 +1370,7 @@ internal override void RowAvailable(ITypedGettersV3 row) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {reader.ObjectID}# (ITypedGettersV3)."); + SqlClientEventSource.Log.Trace(" {0}# (ITypedGettersV3).", reader.ObjectID); } this.reader.RowAvailable(row); } @@ -1368,7 +1379,7 @@ internal override void RowAvailable(SmiTypedGetterSetter rowData) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {reader.ObjectID}# (SmiTypedGetterSetter)."); + SqlClientEventSource.Log.Trace(" {0}# (SmiTypedGetterSetter).", reader.ObjectID); } this.reader.RowAvailable(rowData); } @@ -1377,7 +1388,7 @@ internal override void StatementCompleted(int recordsAffected) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {reader.ObjectID}# recordsAffected= {recordsAffected}."); + SqlClientEventSource.Log.Trace(" {0}# recordsAffected= {1}.", reader.ObjectID, recordsAffected); } // devnote: relies on SmiEventSink_Default to pass event to parent @@ -1391,7 +1402,7 @@ internal override void BatchCompleted() { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {reader.ObjectID}#."); + SqlClientEventSource.Log.Trace(" {0}#.", reader.ObjectID); } // devnote: relies on SmiEventSink_Default to pass event to parent diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs index 61df7c5d73..1d3a6396ab 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs @@ -91,7 +91,7 @@ public void Initialize() SqlConnection usersConnection = connection.Connection; if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, delegating transaction."); + SqlClientEventSource.Log.Trace(" {0}#, Connection {1}#, delegating transaction.", ObjectID, connection.ObjectID); } RuntimeHelpers.PrepareConstrainedRegions(); @@ -101,7 +101,8 @@ public void Initialize() TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -110,7 +111,7 @@ public void Initialize() { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, was enlisted, now defecting."); + SqlClientEventSource.Log.Trace(" {0}#, Connection {1}#, was enlisted, now defecting.", ObjectID, connection.ObjectID); } // defect first @@ -131,7 +132,8 @@ public void Initialize() _active = true; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -175,7 +177,7 @@ public Byte[] Promote() if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, promoting transaction."); + SqlClientEventSource.Log.Trace(" {0}#, Connection {1}#, promoting transaction.", ObjectID, connection.ObjectID); } RuntimeHelpers.PrepareConstrainedRegions(); @@ -185,7 +187,8 @@ public Byte[] Promote() TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -238,7 +241,8 @@ public Byte[] Promote() } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -277,7 +281,7 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, aborting transaction."); + SqlClientEventSource.Log.Trace(" {0}#, Connection {1}#, aborting transaction.", ObjectID, connection.ObjectID); } RuntimeHelpers.PrepareConstrainedRegions(); @@ -287,7 +291,8 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -341,7 +346,8 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) enlistment.Aborted(); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -373,7 +379,7 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, committing transaction."); + SqlClientEventSource.Log.Trace(" {0}#, Connection {1}#, committing transaction.", ObjectID, connection.ObjectID); } RuntimeHelpers.PrepareConstrainedRegions(); @@ -383,7 +389,8 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -472,7 +479,8 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -506,7 +514,7 @@ internal void TransactionEnded(SysTx.Transaction transaction) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Connection {connection.ObjectID}#, transaction completed externally."); + SqlClientEventSource.Log.Trace(" {0}#, Connection {1}#, transaction completed externally.", ObjectID, connection.ObjectID); } lock (connection) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs index 2e79b11407..48685daec1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -318,7 +318,9 @@ public SqlDependency(SqlCommand command, string options, int timeout) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, options: '{options}', timeout: '{timeout}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, options: '{1}', timeout: '{2}'", ObjectID, options, timeout); + } try { @@ -441,7 +443,10 @@ public event OnChangeEventHandler OnChange { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { if (null != value) @@ -454,14 +459,18 @@ public event OnChangeEventHandler OnChange { // If fired, fire the new event immediately. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Dependency already fired, firing new event."); + { + SqlClientEventSource.Log.NotificationsTrace(" Dependency already fired, firing new event."); + } sqlNotificationEvent = new SqlNotificationEventArgs(SqlNotificationType.Subscribe, SqlNotificationInfo.AlreadyChanged, SqlNotificationSource.Client); } else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Dependency has not fired, adding new event."); + { + SqlClientEventSource.Log.NotificationsTrace(" Dependency has not fired, adding new event."); + } EventContextPair pair = new EventContextPair(value, this); if (!_eventList.Contains(pair)) @@ -490,7 +499,10 @@ public event OnChangeEventHandler OnChange { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { if (null != value) @@ -527,7 +539,9 @@ public void AddCommandDependency(SqlCommand command) // and listen for a notification for the added commands. long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } try { @@ -567,11 +581,15 @@ private static void ObtainProcessDispatcher() if (nativeStorage == null) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher."); + { + SqlClientEventSource.Log.NotificationsTrace(" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher."); + } #if DEBUG // Possibly expensive, limit to debug. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); + { + SqlClientEventSource.Log.NotificationsTrace(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); + } #endif _AppDomain masterDomain = SNINativeMethodWrapper.GetDefaultAppDomain(); @@ -597,7 +615,9 @@ private static void ObtainProcessDispatcher() else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" ERROR - ObjectHandle.Unwrap returned null!"); + { + SqlClientEventSource.Log.NotificationsTrace(" ERROR - ObjectHandle.Unwrap returned null!"); + } throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyObtainProcessDispatcherFailureObjectHandle); } @@ -605,7 +625,9 @@ private static void ObtainProcessDispatcher() else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!"); + } throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureCreateInstance); } @@ -613,7 +635,9 @@ private static void ObtainProcessDispatcher() else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ERROR - unable to obtain default AppDomain!"); + } throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureAppDomain); } @@ -621,18 +645,24 @@ private static void ObtainProcessDispatcher() else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher."); + } #if DEBUG // Possibly expensive, limit to debug. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); + { + SqlClientEventSource.Log.NotificationsTrace(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); + } #endif BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(nativeStorage); _processDispatcher = GetDeserializedObject(formatter, stream); // Deserialize and set for appdomain. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" processDispatcher obtained, ID: {_processDispatcher.ObjectID}"); + { + SqlClientEventSource.Log.NotificationsTrace(" processDispatcher obtained, ID: {0}", _processDispatcher.ObjectID); + } } } @@ -681,7 +711,10 @@ internal static bool Start(string connectionString, string queue, bool useDefaul { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); + } + try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -755,7 +788,9 @@ internal static bool Start(string connectionString, string queue, bool useDefaul out errorOccurred, out appDomainStart); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Start (defaults) returned: '{result}', with service: '{service}', server: '{server}', database: '{database}'"); + { + SqlClientEventSource.Log.NotificationsTrace(" Start (defaults) returned: '{0}', with service: '{1}', server: '{2}', database: '{3}'", result, service, server, database); + } } finally { @@ -779,7 +814,9 @@ internal static bool Start(string connectionString, string queue, bool useDefaul ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" Exception occurred from Stop() after duplicate was found on Start()."); + } } throw SQL.SqlDependencyDuplicateStart(); } @@ -793,7 +830,9 @@ internal static bool Start(string connectionString, string queue, bool useDefaul _appDomainKey, SqlDependencyPerAppDomainDispatcher.SingletonInstance); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Start (user provided queue) returned: '{result}'"); + { + SqlClientEventSource.Log.NotificationsTrace(" Start (user provided queue) returned: '{0}'", result); + } // No need to call AddToServerDatabaseHash since if not using default queue user is required // to provide options themselves. @@ -809,7 +848,9 @@ internal static bool Start(string connectionString, string queue, bool useDefaul ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); + { + SqlClientEventSource.Log.NotificationsTrace(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); + } throw; } @@ -841,7 +882,10 @@ internal static bool Stop(string connectionString, string queue, bool useDefault { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" AppDomainKey: '{AppDomainKey}', queue: '{queue}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); + } + try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -963,7 +1007,9 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + } try { bool result = false; @@ -975,7 +1021,9 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!_serverUserHash.ContainsKey(server)) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" Hash did not contain server, adding."); + } identityDatabaseHash = new Dictionary>(); _serverUserHash.Add(server, identityDatabaseHash); @@ -990,7 +1038,9 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!identityDatabaseHash.ContainsKey(identityUser)) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" Hash contained server but not user, adding user."); + } databaseServiceList = new List(); identityDatabaseHash.Add(identityUser, databaseServiceList); @@ -1002,14 +1052,16 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!databaseServiceList.Contains(databaseService)) { - SqlClientEventSource.Log.NotificationsTrace(" Adding database.\n"); + SqlClientEventSource.Log.NotificationsTrace(" Adding database."); databaseServiceList.Add(databaseService); result = true; } else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash already contained server, user, and database - we will throw!."); + } } } @@ -1025,7 +1077,10 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" server: '{server}', database: '{databaseService.Database}', service: '{databaseService.Service}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + } + try { lock (_serverUserHash) @@ -1046,21 +1101,27 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair if (index >= 0) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" Hash contained server, user, and database - removing database."); + } databaseServiceList.RemoveAt(index); if (databaseServiceList.Count == 0) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" databaseServiceList count 0, removing the list for this server and user."); + } identityDatabaseHash.Remove(identityUser); if (identityDatabaseHash.Count == 0) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" identityDatabaseHash count 0, removing the hash for this server."); + } _serverUserHash.Remove(server); } @@ -1077,7 +1138,9 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash contained server but not user!"); + } Debug.Assert(false, "Unexpected state - hash did not contain user!"); } @@ -1085,7 +1148,9 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash did not contain server!"); + } Debug.Assert(false, "Unexpected state - hash did not contain server!"); } @@ -1103,7 +1168,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS // for the given user or database passed. That is ambiguious and we must fail. long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" server: '{server}', failoverServer: '{failoverServer}', database: '{database}'"); + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" server: '{0}', failoverServer: '{1}', database: '{2}'", server, failoverServer, database); try { @@ -1117,7 +1182,9 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { // Special error for no calls to start. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ERROR - no start calls have been made, about to throw."); + } throw SQL.SqlDepDefaultOptionsButNoStart(); } @@ -1129,7 +1196,10 @@ internal static string GetDefaultComposedOptions(string server, string failoverS else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ERROR - not listening to this server, about to throw."); + } + throw SQL.SqlDependencyNoMatchingServerStart(); } } @@ -1143,8 +1213,11 @@ internal static string GetDefaultComposedOptions(string server, string failoverS if (identityDatabaseHash.Count > 1) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ERROR - not listening for this user, " + "but listening to more than one other user, about to throw."); + } + throw SQL.SqlDependencyNoMatchingServerStart(); } else @@ -1192,7 +1265,9 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { // More than one database for given server, ambiguous - fail the default case! if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); + } throw SQL.SqlDependencyNoMatchingServerDatabaseStart(); } @@ -1200,8 +1275,11 @@ internal static string GetDefaultComposedOptions(string server, string failoverS } Debug.Assert(!ADP.IsEmpty(result), "GetDefaultComposedOptions should never return null or empty string!"); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" resulting options: '{result}'."); + { + SqlClientEventSource.Log.NotificationsTrace(" resulting options: '{0}'.", result); + } return result; } @@ -1221,7 +1299,10 @@ internal void AddToServerList(string server) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, server: '{1}'", ObjectID, server); + } + try { lock (_serverList) @@ -1230,7 +1311,9 @@ internal void AddToServerList(string server) if (0 > index) { // If less than 0, item was not found in list. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Server not present in hashtable, adding server: '{server}'."); + { + SqlClientEventSource.Log.NotificationsTrace(" Server not present in hashtable, adding server: '{0}'.", server); + } index = ~index; // BinarySearch returns the 2's compliment of where the item should be inserted to preserver a sorted list after insertion. _serverList.Insert(index, server); @@ -1256,7 +1339,9 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, SqlCommand: {1}#", ObjectID, command.ObjectID); + } try { // Create a string representing the concatenation of the connection string, command text and .ToString on all parameter values. @@ -1272,7 +1357,10 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) string idString = SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddCommandEntry(commandHash, this); // Add to map. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" computed id string: '{idString}'."); + { + SqlClientEventSource.Log.NotificationsTrace(" computed id string: '{0}'.", idString); + } + return idString; } finally @@ -1285,7 +1373,9 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } try { @@ -1305,14 +1395,18 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql // server in this case, we will hit this code path. // It is safe to ignore this race condition because no event is sent to user and no leak happens. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ignore notification received after timeout!"); + } } else { Debug.Assert(false, "Received notification twice - we should never enter this state!"); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ERROR - notification received twice - we should never enter this state!"); + } } } else @@ -1327,7 +1421,9 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (eventList != null) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" Firing events."); + } foreach (EventContextPair pair in eventList) { @@ -1346,13 +1442,18 @@ internal void StartTimer(SqlNotificationRequest notificationRequest) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { if (_expirationTime == DateTime.MaxValue) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" We've timed out, executing logic."); + } int seconds = SQL.SqlDependencyServerTimeout; if (0 != _timeout) @@ -1386,7 +1487,9 @@ private void AddCommandInternal(SqlCommand cmd) // Don't bother with BID if command null. long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {cmd.ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, SqlCommand: {1}#", ObjectID, cmd.ObjectID); + } try { @@ -1398,7 +1501,9 @@ private void AddCommandInternal(SqlCommand cmd) if (cmd._sqlDep == null || cmd._sqlDep != this) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception."); + } throw SQL.SqlCommandHasExistingSqlNotificationRequest(); } @@ -1432,7 +1537,10 @@ private void AddCommandInternal(SqlCommand cmd) { // Keep logic just in case. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { SqlClientEventSource.Log.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point."); + } + needToInvalidate = true; // Delay invalidation until outside of lock. } } @@ -1455,7 +1563,10 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, SqlCommand: {command.ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, SqlCommand: {1}#", ObjectID, command.ObjectID); + } + try { // Create a string representing the concatenation of the connection string, the command text and .ToString on all its parameter values. @@ -1514,7 +1625,9 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) string result = builder.ToString(); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" ComputeCommandHash result: '{result}'."); + { + SqlClientEventSource.Log.NotificationsTrace(" ComputeCommandHash result: '{0}'.", result); + } return result; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index b1cfe3a938..056956b9c4 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -81,7 +81,9 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, queue: '{hashHelper.Queue}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, queue: '{1}'", ObjectID, HashHelper.Queue); + } bool setupCompleted = false; @@ -107,7 +109,9 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str SqlConnectionString connectionStringOptions = new SqlConnectionString(_hashHelper.ConnectionStringBuilder.ConnectionString); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); + { + SqlClientEventSource.Log.NotificationsTrace(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + } #endif // Always use ConnectionStringBuilder since in default case it is different from the @@ -284,7 +288,9 @@ internal bool AppDomainUnload(string appDomainKey) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, AppDomainKey: '{ appDomainKey}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, AppDomainKey: '{1}'", ObjectID, appDomainKey); + } try { @@ -298,12 +304,16 @@ internal bool AppDomainUnload(string appDomainKey) { // Do nothing if AppDomain did not call Start! if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}'."); + { + SqlClientEventSource.Log.NotificationsTrace(" _appDomainKeyHash contained AppDomainKey: '{0}'.", appDomainKey); + } int value = _appDomainKeyHash[appDomainKey]; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{appDomainKey}' count: '{value}'."); + { + SqlClientEventSource.Log.NotificationsTrace("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{0}' count: '{1}'.", appDomainKey, value); + } Debug.Assert(value > 0, "Why is value 0 or less?"); @@ -322,18 +332,24 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{appDomainKey}' entry not removed from hash. Count: {_appDomainKeyHash[appDomainKey]}'"); + { + SqlClientEventSource.Log.NotificationsTrace("SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{0}' entry not removed from hash. Count: {1}'", appDomainKey, _appDomainKeyHash[appDomainKey]); + } } } else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}'."); + { + SqlClientEventSource.Log.NotificationsTrace("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{0}'.", appDomainKey); + } } } if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{_stopped}'."); + { + SqlClientEventSource.Log.NotificationsTrace("SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{0}'.", _stopped); + } return _stopped; } @@ -347,7 +363,9 @@ private void AsynchronouslyQueryServiceBrokerQueue() { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } try { @@ -364,7 +382,10 @@ private void AsyncResultCallback(IAsyncResult asyncResult) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { using (SqlDataReader reader = _com.EndExecuteReader(asyncResult)) @@ -392,7 +413,9 @@ private void AsyncResultCallback(IAsyncResult asyncResult) } if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Exception occurred."); + { + SqlClientEventSource.Log.NotificationsTrace(" Exception occurred."); + } if (!_stop) { // Only assert if not in cancel path. @@ -420,7 +443,10 @@ private void CreateQueueAndService(bool restart) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { SqlCommand com = new SqlCommand(); @@ -558,14 +584,19 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { appDomainStart = false; // Reset out param. int result = Interlocked.Increment(ref _startCount); // Add to refCount. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> {_staticInstance.ObjectID}#, incremented _startCount: {result}"); + { + SqlClientEventSource.Log.NotificationsTrace("SqlConnectionContainer.IncrementStartCount|DEP> {0}#, incremented _startCount: {1}", _staticInstance.ObjectID, result); + } // Dictionary used to track how many times start has been called per app domain. // For each increment, add to count, and create entry if not present. @@ -576,7 +607,9 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) _appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', incremented count: '{_appDomainKeyHash[appDomainKey]}'."); + { + SqlClientEventSource.Log.NotificationsTrace("SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{0}', incremented count: '{1}'.", appDomainKey, _appDomainKeyHash[appDomainKey]); + } } else { @@ -584,7 +617,9 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) appDomainStart = true; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" _appDomainKeyHash did not contain AppDomainKey: '{appDomainKey}', added to hashtable and value set to 1."); + { + SqlClientEventSource.Log.NotificationsTrace(" _appDomainKeyHash did not contain AppDomainKey: '{0}', added to hashtable and value set to 1.", appDomainKey); + } } } } @@ -598,7 +633,10 @@ private void ProcessNotificationResults(SqlDataReader reader) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { Guid handle = Guid.Empty; // Conversation_handle. Always close this! @@ -609,19 +647,25 @@ private void ProcessNotificationResults(SqlDataReader reader) while (reader.Read()) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Row read."); + { + SqlClientEventSource.Log.NotificationsTrace(" Row read."); + } #if DEBUG for (int i = 0; i < reader.FieldCount; i++) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" column: {reader.GetName(i)}, value: {reader.GetValue(i).ToString()}"); + { + SqlClientEventSource.Log.NotificationsTrace(" column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i).ToString()); + } } #endif string msgType = reader.GetString(0); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" msgType: '{ msgType}'"); + { + SqlClientEventSource.Log.NotificationsTrace(" msgType: '{0}'", msgType); + } handle = reader.GetGuid(1); // SqlClientEventSource.SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.ProcessNotificationResults(SqlDataReader)|DEP> conversationHandle: '%p(GUID)'", conversationHandle); @@ -638,7 +682,9 @@ private void ProcessNotificationResults(SqlDataReader reader) string key = notification.Key; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Key: '{key}'"); + { + SqlClientEventSource.Log.NotificationsTrace(" Key: '{0}'", key); + } int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash" @@ -670,7 +716,9 @@ private void ProcessNotificationResults(SqlDataReader reader) Debug.Assert(false, "Received notification but do not have an associated PerAppDomainDispatcher!"); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Received notification but do not have an associated PerAppDomainDispatcher!"); + { + SqlClientEventSource.Log.NotificationsTrace(" Received notification but do not have an associated PerAppDomainDispatcher!"); + } } } else @@ -678,7 +726,9 @@ private void ProcessNotificationResults(SqlDataReader reader) Debug.Assert(false, "Unexpected ID format received!"); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Unexpected ID format received!"); + { + SqlClientEventSource.Log.NotificationsTrace(" Unexpected ID format received!"); + } } } else @@ -686,7 +736,9 @@ private void ProcessNotificationResults(SqlDataReader reader) Debug.Assert(false, "Null notification returned from ProcessMessage!"); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Null notification returned from ProcessMessage!"); + { + SqlClientEventSource.Log.NotificationsTrace(" Null notification returned from ProcessMessage!"); + } } } else @@ -694,7 +746,9 @@ private void ProcessNotificationResults(SqlDataReader reader) Debug.Assert(false, "Null payload for QN notification type!"); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Null payload for QN notification type!"); + { + SqlClientEventSource.Log.NotificationsTrace(" Null payload for QN notification type!"); + } } } else @@ -704,7 +758,9 @@ private void ProcessNotificationResults(SqlDataReader reader) // Debug.Assert(false, "Unexpected message format received!"); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Unexpected message format received!"); + { + SqlClientEventSource.Log.NotificationsTrace(" Unexpected message format received!"); + } } } } @@ -749,7 +805,10 @@ private void Restart(object unused) // Unused arg required by TimerCallback. long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { try @@ -919,7 +978,10 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { appDomainStop = false; @@ -941,7 +1003,9 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) Debug.Assert(value > 0, "Unexpected count for appDomainKey"); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" _appDomainKeyHash contained AppDomainKey: '{appDomainKey}', pre-decrement Count: '{value}'."); + { + SqlClientEventSource.Log.NotificationsTrace(" _appDomainKeyHash contained AppDomainKey: '{0}', pre-decrement Count: '{1}'.", appDomainKey, value); + } if (value > 0) { @@ -950,7 +1014,9 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" ERROR pre-decremented count <= 0!"); + { + SqlClientEventSource.Log.NotificationsTrace(" ERROR pre-decremented count <= 0!"); + } Debug.Assert(false, "Unexpected AppDomainKey count in Stop()"); } @@ -964,7 +1030,9 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" ERROR appDomainKey not null and not found in hash!"); + { + SqlClientEventSource.Log.NotificationsTrace(" ERROR appDomainKey not null and not found in hash!"); + } Debug.Assert(false, "Unexpected state on Stop() - no AppDomainKey entry in hashtable!"); } @@ -979,7 +1047,9 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) // Lock to ensure Cancel() complete prior to other thread calling TearDown. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Reached 0 count, cancelling and waiting."); + { + SqlClientEventSource.Log.NotificationsTrace(" Reached 0 count, cancelling and waiting."); + } lock (this) { @@ -1024,7 +1094,9 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) if (_errorState || retryStopwatch.Elapsed.Seconds >= 30) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" forcing cleanup. elapsedSeconds: '{retryStopwatch.Elapsed.Seconds}', _errorState: '{_errorState}'."); + { + SqlClientEventSource.Log.NotificationsTrace(" forcing cleanup. elapsedSeconds: '{0}', _errorState: '{1}'.", retryStopwatch.Elapsed.Seconds, _errorState); + } Timer retryTimer = _retryTimer; _retryTimer = null; @@ -1045,7 +1117,9 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" _startCount not 0 after decrement. _startCount: '{_startCount}'."); + { + SqlClientEventSource.Log.NotificationsTrace(" _startCount not 0 after decrement. _startCount: '{0}'.", _startCount); + } } Debug.Assert(0 <= _startCount, "Invalid start count state"); @@ -1062,7 +1136,9 @@ private void SynchronouslyQueryServiceBrokerQueue() { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } try { @@ -1082,7 +1158,10 @@ private void TearDownAndDispose() { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { lock (this) @@ -1302,7 +1381,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Exception thrown - Enum.Parse failed to parse the value '{xmlReader.Value}' of the attribute '{xmlReader.LocalName}'."); + SqlClientEventSource.Log.Trace(" Exception thrown - Enum.Parse failed to parse the value '{0}' of the attribute '{1}'.", xmlReader.Value, xmlReader.LocalName); } return null; } @@ -1312,7 +1391,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Not all expected attributes in Message; messageAttributes = '{(int)messageAttributes}'."); + SqlClientEventSource.Log.Trace(" Not all expected attributes in Message; messageAttributes = '{0}'.", (int)messageAttributes); } return null; } @@ -1322,7 +1401,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1332,7 +1411,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1342,7 +1421,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1352,7 +1431,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1365,7 +1444,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1379,7 +1458,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); } return null; } @@ -1391,7 +1470,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); } return null; // failure } @@ -1575,13 +1654,18 @@ private SqlDependencyProcessDispatcher(object dummyVariable) long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { #if DEBUG // Possibly expensive, limit to debug. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); + { + SqlClientEventSource.Log.NotificationsTrace(" {0}#, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); + } #endif _connectionContainers = new Dictionary(); _sqlDependencyPerAppDomainDispatchers = new Dictionary(); @@ -1598,14 +1682,19 @@ public SqlDependencyProcessDispatcher() { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { // Empty constructor and object - dummy to obtain singleton. #if DEBUG // Possibly expensive, limit to debug. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, AppDomain.CurrentDomain.FriendlyName: {AppDomain.CurrentDomain.FriendlyName}"); + { + SqlClientEventSource.Log.NotificationsTrace(" {0}#, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); + } #endif } finally @@ -1638,7 +1727,9 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {_staticInstance.ObjectID}#, queue: {queue}"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, queue: {1}", _staticInstance.ObjectID, queue); + } try { @@ -1686,7 +1777,9 @@ private void Invalidate(string server, SqlNotification sqlNotification) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, server: {server}"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, server: {1}", ObjectID, server); + } try { @@ -1738,7 +1831,9 @@ private void AppDomainUnloading(object state) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } try { @@ -1840,7 +1935,10 @@ private bool Start(string connectionString, { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, queue: '{ queueService}', appDomainKey: '{appDomainKey}', perAppDomainDispatcher ID: '{dispatcher.ObjectID}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, queue: '{1}', appDomainKey: '{2}', perAppDomainDispatcher ID: '{3}'", ObjectID, queueService, appDomainKey, dispatcher.ObjectID); + } + try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1869,7 +1967,9 @@ private bool Start(string connectionString, SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); + { + SqlClientEventSource.Log.NotificationsTrace(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + } #endif bool started = false; @@ -1880,7 +1980,9 @@ private bool Start(string connectionString, if (!_connectionContainers.ContainsKey(hashHelper)) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, hashtable miss, creating new container."); + { + SqlClientEventSource.Log.NotificationsTrace(" {0}#, hashtable miss, creating new container.", ObjectID); + } container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults); _connectionContainers.Add(hashHelper, container); @@ -1890,11 +1992,18 @@ private bool Start(string connectionString, else { container = _connectionContainers[hashHelper]; - SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}"); + + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { + SqlClientEventSource.Log.NotificationsTrace(" {0}#, hashtable hit, container: {1}", ObjectID, container.ObjectID); + } + if (container.InErrorState) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, container: {container.ObjectID} is in error state!"); + { + SqlClientEventSource.Log.NotificationsTrace(" {0}#, container: {1} is in error state!", ObjectID, container.ObjectID); + } errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start(). } @@ -1912,11 +2021,15 @@ private bool Start(string connectionString, queueService = container.Queue; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, default service: '{queueService}', server: '{server}', database: '{database}'"); + { + SqlClientEventSource.Log.NotificationsTrace(" {0}#, default service: '{1}', server: '{2}', database: '{3}'", ObjectID, queueService, server, database); + } } if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, started: {started}"); + { + SqlClientEventSource.Log.NotificationsTrace(" {0}#, started: {1}", ObjectID, started); + } return started; } @@ -1941,8 +2054,10 @@ internal bool Stop(string connectionString, { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, queue: '{queueService}'"); - + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, queue: '{1}'", ObjectID, queueService); + } + try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1962,7 +2077,9 @@ internal bool Stop(string connectionString, SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Modified connection string: '{connectionStringOptions.UsersConnectionStringForTrace()}'"); + { + SqlClientEventSource.Log.NotificationsTrace(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + } #endif bool stopped = false; @@ -1974,7 +2091,9 @@ internal bool Stop(string connectionString, SqlConnectionContainer container = _connectionContainers[hashHelper]; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, hashtable hit, container: {container.ObjectID}"); + { + SqlClientEventSource.Log.NotificationsTrace(" {0}#, hashtable hit, container: {1}", ObjectID, container.ObjectID); + } server = container.Server; // Return server, database, and queue info for use by calling SqlDependency. database = container.Database; @@ -1988,12 +2107,16 @@ internal bool Stop(string connectionString, else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" {ObjectID}#, hashtable miss."); + { + SqlClientEventSource.Log.NotificationsTrace(" {0}#, hashtable miss.", ObjectID); + } } } if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" %d#, stopped: {stopped}"); + { + SqlClientEventSource.Log.NotificationsTrace(" {0}#, stopped: {1}", ObjectID, stopped); + } return stopped; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs index 6cdad9107f..011dc7ac40 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs @@ -94,7 +94,9 @@ private SqlDependencyPerAppDomainDispatcher() { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } try { @@ -129,7 +131,10 @@ private void UnloadEventHandler(object sender, EventArgs e) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); + } + try { // Make non-blocking call to ProcessDispatcher to ThreadPool.QueueUserWorkItem to complete @@ -157,7 +162,10 @@ internal void AddDependencyEntry(SqlDependency dep) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, SqlDependency: {1}#", ObjectID, dep.ObjectID); + } + try { lock (this) @@ -178,7 +186,9 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{commandHash}', SqlDependency: {dep.ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, commandHash: '{1}', SqlDependency: {2}#", ObjectID, commandHash, dep.ObjectID); + } try { @@ -188,7 +198,9 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) { // Determine if depId->dep hashtable contains dependency. If not, it's been invalidated. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Dependency not present in depId->dep hash, must have been invalidated."); + { + SqlClientEventSource.Log.NotificationsTrace(" Dependency not present in depId->dep hash, must have been invalidated."); + } } else { @@ -210,14 +222,18 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) if (!dependencyList.Contains(dep)) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Dependency not present for commandHash, adding."); + { + SqlClientEventSource.Log.NotificationsTrace(" Dependency not present for commandHash, adding."); + } dependencyList.Add(dep); } else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Dependency already present for commandHash."); + { + SqlClientEventSource.Log.NotificationsTrace(" Dependency already present for commandHash."); + } } } else @@ -233,7 +249,9 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) ); if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Creating new Dependencies list for commandHash."); + { + SqlClientEventSource.Log.NotificationsTrace(" Creating new Dependencies list for commandHash."); + } DependencyList dependencyList = new DependencyList(commandHash); dependencyList.Add(dep); @@ -267,7 +285,9 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{sqlNotification.Key}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, commandHash: '{1}'", ObjectID, sqlNotification.Key); + } try { @@ -280,7 +300,9 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) if (null != dependencyList) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" commandHash found in hashtable."); + { + SqlClientEventSource.Log.NotificationsTrace(" commandHash found in hashtable."); + } foreach (SqlDependency dependency in dependencyList) { @@ -294,7 +316,9 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" commandHash NOT found in hashtable."); + { + SqlClientEventSource.Log.NotificationsTrace(" commandHash NOT found in hashtable."); + } } } @@ -304,7 +328,9 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) foreach (SqlDependency dependency in dependencyList) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Dependency found in commandHash dependency ArrayList - calling invalidate."); + { + SqlClientEventSource.Log.NotificationsTrace(" Dependency found in commandHash dependency ArrayList - calling invalidate."); + } try { @@ -335,7 +361,9 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, server: '{server}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, server: '{1}'", ObjectID, server); + } try { @@ -392,7 +420,9 @@ internal SqlDependency LookupDependencyEntry(string id) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, Key: '{id}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, Key: '{1}'", ObjectID, id); + } try { @@ -416,7 +446,9 @@ internal SqlDependency LookupDependencyEntry(string id) else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" ERROR - dependency ID mismatch - not throwing."); + { + SqlClientEventSource.Log.NotificationsTrace(" ERROR - dependency ID mismatch - not throwing."); + } } } @@ -433,8 +465,10 @@ private void LookupDependencyEntryWithRemove(string id) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, id: '{id}'"); - + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, id: '{1}'", ObjectID, id); + } + try { lock (this) @@ -442,7 +476,9 @@ private void LookupDependencyEntryWithRemove(string id) if (_dependencyIdToDependencyHash.ContainsKey(id)) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Entry found in hashtable - removing."); + { + SqlClientEventSource.Log.NotificationsTrace(" Entry found in hashtable - removing."); + } _dependencyIdToDependencyHash.Remove(id); @@ -456,7 +492,9 @@ private void LookupDependencyEntryWithRemove(string id) else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Entry NOT found in hashtable."); + { + SqlClientEventSource.Log.NotificationsTrace(" Entry NOT found in hashtable."); + } } } } @@ -471,7 +509,10 @@ private List LookupCommandEntryWithRemove(string notificationId) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, commandHash: '{notificationId}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, commandHash: '{1}'", ObjectID, notificationId); + } + try { DependencyList entry = null; @@ -481,7 +522,9 @@ private List LookupCommandEntryWithRemove(string notificationId) if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry)) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Entries found in hashtable - removing."); + { + SqlClientEventSource.Log.NotificationsTrace(" Entries found in hashtable - removing."); + } // update the tables - do it inside finally block to avoid ThreadAbort exception interrupt this operation try @@ -496,7 +539,9 @@ private List LookupCommandEntryWithRemove(string notificationId) else { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Entries NOT found in hashtable."); + { + SqlClientEventSource.Log.NotificationsTrace(" Entries NOT found in hashtable."); + } } Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!"); @@ -515,7 +560,10 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dependency.ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, SqlDependency: {1}#", ObjectID, dependency.ObjectID); + } + try { lock (this) @@ -529,7 +577,9 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende if (dependencies.Remove(dependency)) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Removed SqlDependency: {dependency.ObjectID}#, with ID: '{dependency.Id}'."); + { + SqlClientEventSource.Log.NotificationsTrace(" Removed SqlDependency: {0}#, with ID: '{1}'.", dependency.ObjectID, dependency.Id); + } if (dependencies.Count == 0) { @@ -575,7 +625,10 @@ internal void StartTimer(SqlDependency dep) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" {ObjectID}#, SqlDependency: {dep.ObjectID}#"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, SqlDependency: {1}#", ObjectID, dep.ObjectID); + } + try { // If this dependency expires sooner than the current next timeout, change @@ -587,7 +640,9 @@ internal void StartTimer(SqlDependency dep) if (!_SqlDependencyTimeOutTimerStarted) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Timer not yet started, starting."); + { + SqlClientEventSource.Log.NotificationsTrace(" Timer not yet started, starting."); + } _timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */); @@ -598,7 +653,9 @@ internal void StartTimer(SqlDependency dep) else if (_nextTimeout > dep.ExpirationTime) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" Timer already started, resetting time."); + { + SqlClientEventSource.Log.NotificationsTrace(" Timer already started, resetting time."); + } // Save this as the earlier timeout to come. _nextTimeout = dep.ExpirationTime; @@ -615,7 +672,10 @@ private static void TimeoutTimerCallback(object state) { long scopeID = 0; if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter($" AppDomainKey: '{SqlDependency.AppDomainKey}'"); + { + scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" AppDomainKey: '{0}'", SqlDependency.AppDomainKey); + } + try { SqlDependency[] dependencies; @@ -629,13 +689,17 @@ private static void TimeoutTimerCallback(object state) { // Nothing to check. if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" No dependencies, exiting."); + { + SqlClientEventSource.Log.NotificationsTrace(" No dependencies, exiting."); + } return; } if (SingletonInstance._nextTimeout > DateTime.UtcNow) { if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace($" No timeouts expired, exiting."); + { + SqlClientEventSource.Log.NotificationsTrace(" No timeouts expired, exiting."); + } // No dependency timed-out yet. return; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs index 659a34b775..a1f2a87334 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs @@ -43,7 +43,7 @@ internal SqlError(int infoNumber, byte errorState, byte errorClass, string serve { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" infoNumber={infoNumber}, errorState={(int)errorState}, errorClass={(int)errorClass}, errorMessage='{errorMessage}', procedure='{procedure ?? "None"}', lineNumber={(int)lineNumber}"); + SqlClientEventSource.Log.Trace(" infoNumber={0}, errorState={1}, errorClass={2}, errorMessage='{3}', procedure='{4}', lineNumber={5}", infoNumber, (int)errorState, (int)errorClass, errorMessage, procedure ?? "None", (int)lineNumber); } } this.win32ErrorCode = 0; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index 46f50613cc..aa578c9394 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -314,7 +314,9 @@ override protected DbReferenceCollection CreateReferenceCollection() override protected void Deactivate() { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - SqlClientEventSource.Log.Trace($" {ObjectID}# deactivating"); + { + SqlClientEventSource.Log.Trace(" {0}# deactivating", ObjectID); + } TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -439,14 +441,18 @@ private void EnlistNonNull(SysTx.Transaction tx) Debug.Assert(null != tx, "null transaction?"); if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - SqlClientEventSource.Log.Trace($" {ObjectID}#, transaction {tx.GetHashCode()}#."); + { + SqlClientEventSource.Log.Trace(" {0}#, transaction {1}#.", ObjectID, tx.GetHashCode()); + } bool hasDelegatedTransaction = false; if (IsYukonOrNewer) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - SqlClientEventSource.Log.Trace($" {ObjectID}#, attempting to delegate"); + { + SqlClientEventSource.Log.Trace(" {0}#, attempting to delegate", ObjectID); + } // Promotable transactions are only supported on Yukon // servers or newer. @@ -516,7 +522,9 @@ private void EnlistNonNull(SysTx.Transaction tx) this.DelegatedTransaction = delegatedTransaction; if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - SqlClientEventSource.Log.Trace($" {ObjectID}#, delegated to transaction {(null != CurrentTransaction? CurrentTransaction.ObjectID:0)}# with transactionId=0x{(null != CurrentTransaction? CurrentTransaction.TransactionId:SqlInternalTransaction.NullTransactionId)}"); + { + SqlClientEventSource.Log.Trace(" {0}#, delegated to transaction {1}# with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); + } } } catch (SqlException e) @@ -550,7 +558,9 @@ private void EnlistNonNull(SysTx.Transaction tx) if (!hasDelegatedTransaction) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - SqlClientEventSource.Log.Trace($" {ObjectID}#, delegation not possible, enlisting."); + { + SqlClientEventSource.Log.Trace(" {0}#, delegation not possible, enlisting.", ObjectID); + } byte[] cookie = null; @@ -592,7 +602,9 @@ private void EnlistNonNull(SysTx.Transaction tx) } if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - SqlClientEventSource.Log.Trace($" {ObjectID}#, enlisted with transaction {transactionObjectID}# with transactionId=0x{transactionId}"); + { + SqlClientEventSource.Log.Trace(" {0}#, enlisted with transaction {1}# with transactionId=0x{2}", ObjectID, transactionObjectID, transactionId); + } } EnlistedTransaction = tx; // Tell the base class about our enlistment @@ -617,7 +629,9 @@ private void EnlistNonNull(SysTx.Transaction tx) internal void EnlistNull() { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - SqlClientEventSource.Log.Trace($" {ObjectID}#, unenlisting."); + { + SqlClientEventSource.Log.Trace(" {0}#, unenlisting.", ObjectID); + } // We were in a transaction, but now we are not - so send // message to server with empty transaction - confirmed proper @@ -637,7 +651,9 @@ internal void EnlistNull() EnlistedTransaction = null; // Tell the base class about our enlistment if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - SqlClientEventSource.Log.Trace($" {ObjectID}#, unenlisted."); + { + SqlClientEventSource.Log.Trace(" {0}#, unenlisted.", ObjectID); + } // The EnlistTransaction above will return an TransactionEnded event, // which causes the TdsParser or SmiEventSink should to clear the diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs index 7f32e8324f..1a49a86695 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs @@ -67,7 +67,7 @@ internal override void DefaultDatabaseChanged(string databaseName) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, databaseName='{databaseName}'."); + SqlClientEventSource.Log.Trace(" {0}#, databaseName='{1}'.", _connection.ObjectID, databaseName); } _connection.CurrentDatabase = databaseName; } @@ -76,7 +76,7 @@ internal override void TransactionCommitted(long transactionId) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); + SqlClientEventSource.Log.Trace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); } _connection.TransactionEnded(transactionId, TransactionState.Committed); } @@ -85,7 +85,7 @@ internal override void TransactionDefected(long transactionId) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); + SqlClientEventSource.Log.Trace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); } _connection.TransactionEnded(transactionId, TransactionState.Unknown); } @@ -94,7 +94,7 @@ internal override void TransactionEnlisted(long transactionId) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, transactionId=0x%{transactionId}."); + SqlClientEventSource.Log.Trace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); } _connection.TransactionStarted(transactionId, true); // distributed; } @@ -103,7 +103,7 @@ internal override void TransactionEnded(long transactionId) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); + SqlClientEventSource.Log.Trace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); } _connection.TransactionEndedByServer(transactionId, TransactionState.Unknown); } @@ -112,7 +112,7 @@ internal override void TransactionRolledBack(long transactionId) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); + SqlClientEventSource.Log.Trace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); } // Dev11 1066: ensure delegated transaction is rolled back @@ -123,7 +123,7 @@ internal override void TransactionStarted(long transactionId) { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {_connection.ObjectID}#, transactionId=0x{transactionId}."); + SqlClientEventSource.Log.Trace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); } _connection.TransactionStarted(transactionId, false); // not distributed; } @@ -143,7 +143,7 @@ internal SqlInternalConnectionSmi(SqlConnectionString connectionOptions, SmiCont if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, constructed new SMI internal connection"); + SqlClientEventSource.Log.Trace(" {0}#, constructed new SMI internal connection", ObjectID); } } @@ -297,7 +297,7 @@ internal void AutomaticEnlistment() if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, contextTransactionId=0x{contextTransactionId}, contextTransaction={((null != contextTransaction) ? contextTransaction.GetHashCode() : 0)}#, currentSystemTransaction={((null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0)}#."); + SqlClientEventSource.Log.Trace(" {0}#, contextTransactionId=0x{1}, contextTransaction={2}#, currentSystemTransaction={3}#.", ObjectID, contextTransactionId, (null != contextTransaction) ? contextTransaction.GetHashCode() : 0, (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0); } if (SqlInternalTransaction.NullTransactionId != contextTransactionId) @@ -309,7 +309,7 @@ internal void AutomaticEnlistment() if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, using context transaction with transactionId=0x{contextTransactionId}"); + SqlClientEventSource.Log.Trace(" {0}#, using context transaction with transactionId=0x{1}", ObjectID, contextTransactionId); } _currentTransaction = new SqlInternalTransaction(this, TransactionType.Context, null, contextTransactionId); ContextTransaction = contextTransaction; @@ -320,14 +320,14 @@ internal void AutomaticEnlistment() if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, no transaction."); + SqlClientEventSource.Log.Trace(" {0}#, no transaction.", ObjectID); } } else { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, using current System.Transaction."); + SqlClientEventSource.Log.Trace(" {0}#, using current System.Transaction.", ObjectID); } base.Enlist(currentSystemTransaction); } @@ -343,7 +343,7 @@ override protected void InternalDeactivate() { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Deactivating."); + SqlClientEventSource.Log.Trace(" {0}#, Deactivating.", ObjectID); } // When we put this to bed, we should not hold on to the transaction @@ -376,7 +376,7 @@ override internal void DelegatedTransactionEnded() if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, cleaning up after Delegated Transaction Completion"); + SqlClientEventSource.Log.Trace(" {0}#, cleaning up after Delegated Transaction Completion", ObjectID); } _currentTransaction = null; // clean up our current transaction too @@ -386,7 +386,7 @@ override internal void DisconnectTransaction(SqlInternalTransaction internalTran { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Disconnecting Transaction {internalTransaction.ObjectID}#."); + SqlClientEventSource.Log.Trace(" {0}#, Disconnecting Transaction {1}#.", ObjectID, internalTransaction.ObjectID); } // VSTS 215465/15029: allow _currentTransaction to be null - it can be cleared before by server's callback @@ -415,8 +415,8 @@ override internal void ExecuteTransaction( if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, transactionRequest={transactionRequest.ToString()}, " + - $"transactionName='{transactionNameValue}', isolationLevel={iso.ToString()}, internalTransaction=#{((null != internalTransaction) ? internalTransaction.ObjectID : 0)} transactionId=0x{((null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId)}."); + SqlClientEventSource.Log.Trace(" {0}#, transactionRequest={1}, " + + "transactionName='{2}', isolationLevel={3}, internalTransaction=#{4} transactionId=0x{5}.", ObjectID, transactionRequest.ToString(), transactionNameValue, iso.ToString(), (null != internalTransaction) ? internalTransaction.ObjectID : 0, (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); } switch (transactionRequest) @@ -476,11 +476,11 @@ override protected byte[] GetDTCAddress() { if (null != whereAbouts) { - SqlClientEventSource.Log.TraceBin($" whereAbouts", whereAbouts, (ushort)whereAbouts.Length); + SqlClientEventSource.Log.TraceBin(" whereAbouts", whereAbouts, (ushort)whereAbouts.Length); } else { - SqlClientEventSource.Log.Trace($" whereAbouts=null"); + SqlClientEventSource.Log.Trace(" whereAbouts=null"); } } return whereAbouts; @@ -508,7 +508,7 @@ private void OnOutOfScope(object s, EventArgs e) // the context may appear to have the connection in use. if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# context is out of scope"); + SqlClientEventSource.Log.Trace(" {0}# context is out of scope", ObjectID); } // TODO: This is suspect to me -- if I go out of scope, who will commit the transaction? @@ -541,11 +541,11 @@ override protected void PropagateTransactionCookie(byte[] transactionCookie) { if (null != transactionCookie) { - SqlClientEventSource.Log.TraceBin($" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); + SqlClientEventSource.Log.TraceBin(" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); } else { - SqlClientEventSource.Log.Trace($" null"); + SqlClientEventSource.Log.Trace(" null"); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs index bb5d029a3b..63d13fbfb3 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs @@ -518,7 +518,7 @@ internal SqlInternalConnectionTds( } if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, constructed new TDS internal connection"); + SqlClientEventSource.Log.Trace(" {0}#, constructed new TDS internal connection", ObjectID); } } @@ -776,7 +776,7 @@ override public void Dispose() { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# disposing"); + SqlClientEventSource.Log.Trace(" {0}# disposing", ObjectID); } try @@ -1371,7 +1371,7 @@ private void CompleteLogin(bool enlistOK) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Server did not acknowledge the federated authentication request"); + SqlClientEventSource.Log.Trace(" {0}#, Server did not acknowledge the federated authentication request", ObjectID); } throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged); @@ -1380,7 +1380,7 @@ private void CompleteLogin(bool enlistOK) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Server never sent the requested federated authentication info"); + SqlClientEventSource.Log.Trace(" {0}#, Server never sent the requested federated authentication info", ObjectID); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoNotReceived); } @@ -1422,7 +1422,7 @@ private void CompleteLogin(bool enlistOK) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Post-Login Phase: Server connection obtained."); + SqlClientEventSource.Log.Trace(" Post-Login Phase: Server connection obtained."); } // for non-pooled connections, enlist in a distributed transaction @@ -1554,7 +1554,7 @@ private void LoginFailure() { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#"); + SqlClientEventSource.Log.Trace(" {0}#", ObjectID); } // If the parser was allocated and we failed, then we must have failed on @@ -1683,7 +1683,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, host={serverInfo.UserServerName}"); + SqlClientEventSource.Log.Trace(" {0}#, host={1}", ObjectID, serverInfo.UserServerName); } int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. @@ -1792,7 +1792,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Routed to {serverInfo.ExtendedServerName}"); + SqlClientEventSource.Log.Trace(" Routed to {0}", serverInfo.ExtendedServerName); } if (routingAttempts > _maxNumberOfRedirectRoute) @@ -1884,7 +1884,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt // then update sleep interval for next iteration (max 1 second interval) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]"); + SqlClientEventSource.Log.Trace(" {0}#, sleeping {1}[milisec]", ObjectID, sleepInterval); } Thread.Sleep(sleepInterval); @@ -1970,7 +1970,7 @@ TimeoutTimer timeout if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, useFailover={useFailoverHost}[bool], primary={primaryServerInfo.UserServerName}, failover={failoverHost}"); + SqlClientEventSource.Log.Trace(" {0}#, useFailover={1}[bool], primary={2}, failover={failoverHost}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName); } int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. @@ -2041,7 +2041,7 @@ TimeoutTimer timeout { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, new failover partner={ServerProvidedFailOverPartner}"); + SqlClientEventSource.Log.Trace(" {0}#, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); } failoverServerInfo.SetDerivedNames(protocol, ServerProvidedFailOverPartner); } @@ -2077,7 +2077,7 @@ TimeoutTimer timeout if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Routed to {_routingInfo.ServerName}"); + SqlClientEventSource.Log.Trace(" Routed to {0}", _routingInfo.ServerName); } if (_parser != null) @@ -2149,7 +2149,7 @@ TimeoutTimer timeout { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, sleeping {sleepInterval}[milisec]"); + SqlClientEventSource.Log.Trace(" {0}#, sleeping {1}[milisec]", ObjectID, sleepInterval); } Thread.Sleep(sleepInterval); @@ -2228,7 +2228,7 @@ private void AttemptOneLogin(ServerInfo serverInfo, string newPassword, SecureSt { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, timout={timeout.MillisecondsRemaining}[msec], server={serverInfo.ExtendedServerName}"); + SqlClientEventSource.Log.Trace(" {0}#, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); } _routingInfo = null; // forget routing information @@ -2384,7 +2384,7 @@ internal void BreakConnection() if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Breaking connection."); + SqlClientEventSource.Log.Trace(" {0}#, Breaking connection.", ObjectID); } DoomThisConnection(); // Mark connection as unusable, so it will be destroyed if (null != connection) @@ -2479,7 +2479,7 @@ internal void OnEnvChange(SqlEnvChange rec) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Received routing info"); + SqlClientEventSource.Log.Trace(" {0}#, Received routing info", ObjectID); } if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0) @@ -2528,7 +2528,7 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Generating federated authentication token"); + SqlClientEventSource.Log.Trace(" {0}#, Generating federated authentication token", ObjectID); } DbConnectionPoolAuthenticationContext dbConnectionPoolAuthenticationContext = null; @@ -2563,9 +2563,9 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, " + - $"The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + - $"The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. Current Time is {DateTime.UtcNow.ToLongTimeString()}."); + SqlClientEventSource.Log.Trace(" {0}#, " + + "The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + + "The expiration time is {1}. Current Time is {DateTime.UtcNow.ToLongTimeString()}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()); } attemptRefreshTokenUnLocked = true; @@ -2589,9 +2589,9 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, " + - $"The authentication context needs a refresh.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. " + - $"Current Time is {DateTime.UtcNow.ToLongTimeString()}."); + SqlClientEventSource.Log.Trace(" {0}#, " + + "The authentication context needs a refresh.The expiration time is {1}. " + + "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); } // Call the function which tries to acquire a lock over the authentication context before trying to update. @@ -2608,14 +2608,14 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" %d#, The attempt to get a new access token succeeded under the locked mode."); + SqlClientEventSource.Log.Trace(" %d#, The attempt to get a new access token succeeded under the locked mode."); } } } if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token."); + SqlClientEventSource.Log.Trace(" {0}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); } } } @@ -2678,9 +2678,9 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, " + - $"Acquired the lock to update the authentication context.The expiration time is {dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()}. " + - $"Current Time is {DateTime.UtcNow.ToLongTimeString()}."); + SqlClientEventSource.Log.Trace(" {0}#, " + + "Acquired the lock to update the authentication context.The expiration time is {1}. " + + "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); } authenticationContextLocked = true; @@ -2689,7 +2689,7 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Refreshing the context is already in progress by another thread."); + SqlClientEventSource.Log.Trace(" {}#, Refreshing the context is already in progress by another thread.", ObjectID); } } @@ -2850,7 +2850,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {msalException.ErrorCode}#"); + SqlClientEventSource.Log.Trace(" {0}#", msalException.ErrorCode); } // Error[0] @@ -2872,8 +2872,8 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, sleeping {sleepInterval}[Milliseconds]"); - SqlClientEventSource.Log.Trace($" {ObjectID}#, remaining {_timeout.MillisecondsRemaining}[Milliseconds]"); + SqlClientEventSource.Log.Trace(" {0}#, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); + SqlClientEventSource.Log.Trace(" {0}#, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); } Thread.Sleep(sleepInterval); @@ -2893,7 +2893,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Finished generating federated authentication token."); + SqlClientEventSource.Log.Trace(" {0}#, Finished generating federated authentication token.", ObjectID); } return fedAuthToken; @@ -2960,14 +2960,14 @@ internal void OnFeatureExtAck(int featureId, byte[] data) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for federated authentication"); + SqlClientEventSource.Log.Trace(" {0}#, Received feature extension acknowledgement for federated authentication", ObjectID); } if (!_federatedAuthenticationRequested) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Did not request federated authentication"); + SqlClientEventSource.Log.Trace(" {0}#, Did not request federated authentication", ObjectID); } throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); @@ -2984,8 +2984,8 @@ internal void OnFeatureExtAck(int featureId, byte[] data) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, " + - $"Federated authentication feature extension ack for MSAL and Security Token includes extra data"); + SqlClientEventSource.Log.Trace(" {0}#, " + + "Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); } throw SQL.ParsingError(ParsingErrorState.FedAuthFeatureAckContainsExtraData); } @@ -2995,7 +2995,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) Debug.Fail("Unknown _fedAuthLibrary type"); if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Attempting to use unknown federated authentication library"); + SqlClientEventSource.Log.Trace(" {0}#, Attempting to use unknown federated authentication library", ObjectID); } throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType); @@ -3018,11 +3018,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts."); + SqlClientEventSource.Log.Trace(" {0}#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); } else { - SqlClientEventSource.Log.Trace($" {ObjectID}#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value."); + SqlClientEventSource.Log.Trace(" {0}#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); } } #endif @@ -3034,14 +3034,14 @@ internal void OnFeatureExtAck(int featureId, byte[] data) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for TCE"); + SqlClientEventSource.Log.Trace(" {0}#, Received feature extension acknowledgement for TCE", ObjectID); } if (data.Length < 1) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Unknown version number for TCE"); + SqlClientEventSource.Log.Trace(" {0}#, Unknown version number for TCE", ObjectID); } throw SQL.ParsingError(ParsingErrorState.TceUnknownVersion); @@ -3052,7 +3052,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Invalid version number for TCE"); + SqlClientEventSource.Log.Trace(" {0}#, Invalid version number for TCE", ObjectID); } throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidVersion, supportedTceVersion); } @@ -3074,14 +3074,14 @@ internal void OnFeatureExtAck(int featureId, byte[] data) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for GlobalTransactions"); + SqlClientEventSource.Log.Trace(" {0}#, Received feature extension acknowledgement for GlobalTransactions", ObjectID); } if (data.Length < 1) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Unknown version number for GlobalTransactions"); + SqlClientEventSource.Log.Trace(" {0}#, Unknown version number for GlobalTransactions", ObjectID); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); @@ -3099,14 +3099,14 @@ internal void OnFeatureExtAck(int featureId, byte[] data) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for AzureSQLSupport"); + SqlClientEventSource.Log.Trace(" {0}#, Received feature extension acknowledgement for AzureSQLSupport", ObjectID); } if (data.Length < 1) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Unknown token for AzureSQLSupport"); + SqlClientEventSource.Log.Trace(" {0}#, Unknown token for AzureSQLSupport", ObjectID); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); @@ -3117,7 +3117,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // Bit 0 for RO/FP support if ((data[0] & 1) == 1 && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, FailoverPartner enabled with Readonly intent for AzureSQL DB"); + SqlClientEventSource.Log.Trace(" {0}#, FailoverPartner enabled with Readonly intent for AzureSQL DB", ObjectID); } break; } @@ -3126,14 +3126,14 @@ internal void OnFeatureExtAck(int featureId, byte[] data) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for DATACLASSIFICATION"); + SqlClientEventSource.Log.Trace(" {0}#, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); } if (data.Length < 1) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION"); + SqlClientEventSource.Log.Trace(" {0}#, Unknown token for DATACLASSIFICATION", ObjectID); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); @@ -3143,7 +3143,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Invalid version number for DATACLASSIFICATION"); + SqlClientEventSource.Log.Trace(" {0}#, Invalid version number for DATACLASSIFICATION", ObjectID); } throw SQL.ParsingErrorValue(ParsingErrorState.DataClassificationInvalidVersion, supportedDataClassificationVersion); } @@ -3152,7 +3152,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Unknown token for DATACLASSIFICATION"); + SqlClientEventSource.Log.Trace(" {0}#, Unknown token for DATACLASSIFICATION", ObjectID); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } @@ -3165,14 +3165,14 @@ internal void OnFeatureExtAck(int featureId, byte[] data) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Received feature extension acknowledgement for UTF8 support"); + SqlClientEventSource.Log.Trace(" {0}#, Received feature extension acknowledgement for UTF8 support", ObjectID); } if (data.Length < 1) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Unknown value for UTF8 support"); + SqlClientEventSource.Log.Trace(" {0}#, Unknown value for UTF8 support", ObjectID); } throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs index eb5747babb..c8addbdbfe 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -144,11 +144,15 @@ override public void Commit() SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -275,7 +279,7 @@ override public void Rollback() if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { // Put something in the trace in case a customer has an issue - SqlClientEventSource.Log.Trace($" {ObjectID}# partial zombie no rollback required"); + SqlClientEventSource.Log.Trace(" {0}# partial zombie no rollback required", ObjectID); } _internalTransaction = null; // yukon zombification @@ -287,11 +291,15 @@ override public void Rollback() SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace($" ObjectID{ObjectID}#, ActivityID {SqlClientEventSource.Log.Guid}"); + { + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -357,8 +365,10 @@ public void Rollback(string transactionName) SqlStatistics statistics = null; long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}# transactionName='{transactionName}'"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}# transactionName='{1}'", ObjectID, transactionName); + } TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -421,10 +431,12 @@ public void Save(string savePointName) ZombieCheck(); SqlStatistics statistics = null; - + long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}# savePointName='{savePointName}'"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}# savePointName='{1}'", ObjectID, savePointName); + } TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -492,7 +504,7 @@ internal void Zombie() { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# yukon deferred zombie"); + SqlClientEventSource.Log.Trace(" {0}# yukon deferred zombie", ObjectID); } } else diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index f32ae77d9e..cd3b2f7f45 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -505,7 +505,7 @@ internal void Connect(ServerInfo serverInfo, if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication"); + SqlClientEventSource.Log.Trace(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication"); } } else @@ -515,28 +515,28 @@ internal void Connect(ServerInfo serverInfo, { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Active Directory Password authentication"); + SqlClientEventSource.Log.Trace(" Active Directory Password authentication"); } } else if (authType == SqlAuthenticationMethod.SqlPassword) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" SQL Password authentication"); + SqlClientEventSource.Log.Trace(" SQL Password authentication"); } } else if (authType == SqlAuthenticationMethod.ActiveDirectoryInteractive) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Active Directory Interactive authentication"); + SqlClientEventSource.Log.Trace(" Active Directory Interactive authentication"); } } else { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" SQL authentication"); + SqlClientEventSource.Log.Trace(" SQL authentication"); } } } @@ -577,7 +577,7 @@ internal void Connect(ServerInfo serverInfo, if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Login failure"); + SqlClientEventSource.Log.Trace(" Login failure"); } ThrowExceptionAndWarning(_physicalStateObj); @@ -610,7 +610,7 @@ internal void Connect(ServerInfo serverInfo, if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Sending prelogin handshake"); + SqlClientEventSource.Log.Trace(" Sending prelogin handshake"); } // UNDONE - send "" for instance now, need to fix later @@ -623,7 +623,7 @@ internal void Connect(ServerInfo serverInfo, if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Consuming prelogin handshake"); + SqlClientEventSource.Log.Trace(" Consuming prelogin handshake"); } PreLoginHandshakeStatus status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, @@ -633,7 +633,7 @@ internal void Connect(ServerInfo serverInfo, { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Prelogin handshake unsuccessful. Reattempting prelogin handshake"); + SqlClientEventSource.Log.Trace(" Prelogin handshake unsuccessful. Reattempting prelogin handshake"); } _physicalStateObj.Dispose(); // Close previous connection @@ -647,7 +647,7 @@ internal void Connect(ServerInfo serverInfo, if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Login failure"); + SqlClientEventSource.Log.Trace(" Login failure"); } ThrowExceptionAndWarning(_physicalStateObj); } @@ -657,8 +657,9 @@ internal void Connect(ServerInfo serverInfo, if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Sending prelogin handshake"); + SqlClientEventSource.Log.Trace(" Sending prelogin handshake"); } + SendPreLoginHandshake(instanceName, encrypt, !string.IsNullOrEmpty(certificate), useOriginalAddressInfo); status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, out marsCapable, out _connHandler._fedAuthRequired); @@ -669,7 +670,7 @@ internal void Connect(ServerInfo serverInfo, { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Prelogin handshake unsuccessful. Login failure"); + SqlClientEventSource.Log.Trace(" Prelogin handshake unsuccessful. Login failure"); } throw SQL.InstanceFailure(); } @@ -677,7 +678,7 @@ internal void Connect(ServerInfo serverInfo, if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Prelogin handshake successful"); + SqlClientEventSource.Log.Trace(" Prelogin handshake successful"); } if (_fMARS && marsCapable) @@ -773,7 +774,7 @@ internal TdsParserStateObject CreateSession() if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# created session {session.ObjectID}"); + SqlClientEventSource.Log.Trace(" {0}# created session {1}", ObjectID, session.ObjectID); } return session; @@ -792,7 +793,7 @@ internal TdsParserStateObject GetSession(object owner) Debug.Assert(!session._pendingData, "pending data on a pooled MARS session"); if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# getting session {session.ObjectID} from pool"); + SqlClientEventSource.Log.Trace(" {0}# getting session {1} from pool", ObjectID, session.ObjectID); } } else @@ -801,7 +802,7 @@ internal TdsParserStateObject GetSession(object owner) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# getting physical session {session.ObjectID}"); + SqlClientEventSource.Log.Trace(" {0}# getting physical session {1}", ObjectID, session.ObjectID); } } Debug.Assert(session._outputPacketNumber == 1, "The packet number is expected to be 1"); @@ -1019,7 +1020,7 @@ private void SendPreLoginHandshake(byte[] instanceName, bool encrypt, bool clien if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" ClientConnectionID {_connHandler._clientConnectionId.ToString()}, ActivityID {actId.ToString()}"); + SqlClientEventSource.Log.Trace(" ClientConnectionID {0}, ActivityID {1}", _connHandler._clientConnectionId.ToString(), actId.ToString()); } break; @@ -1333,8 +1334,8 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, " + - $"Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {(int)payload[payloadOffset]}."); + SqlClientEventSource.Log.Trace(" {0}#, " + + "Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {1}.", ObjectID, (int)payload[payloadOffset]); } throw SQL.ParsingErrorValue(ParsingErrorState.FedAuthRequiredPreLoginResponseInvalidValue, (int)payload[payloadOffset]); @@ -1378,9 +1379,9 @@ internal void Deactivate(bool connectionIsDoomed) // Called when the connection that owns us is deactivated. if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# deactivating"); + SqlClientEventSource.Log.Trace(" {0}# deactivating", ObjectID); - SqlClientEventSource.Log.Trace($" {ObjectID}#, {TraceString()}"); + SqlClientEventSource.Log.Trace(" {0}#, {1}", ObjectID, TraceString()); } if (MARSOn) @@ -1539,7 +1540,7 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {ObjectID}#"); + SqlClientEventSource.Log.Trace(" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {0}#", ObjectID); } } Debug.Assert(_connHandler != null, "TdsParser::ThrowExceptionAndWarning called with null connectionHandler!"); @@ -2263,7 +2264,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Potential multi-threaded misuse of connection, unexpected TDS token found {ObjectID}#"); + SqlClientEventSource.Log.Trace(" Potential multi-threaded misuse of connection, unexpected TDS token found {0}#", ObjectID); } throw SQL.ParsingErrorToken(ParsingErrorState.InvalidTdsTokenReceived, token); // MDAC 82443 } @@ -2588,8 +2589,9 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Received login acknowledgement token"); + SqlClientEventSource.Log.Trace(" Received login acknowledgement token"); } + SqlLoginAck ack; if (!TryProcessLoginAck(stateObj, out ack)) { @@ -2614,7 +2616,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Received federated authentication info token"); + SqlClientEventSource.Log.Trace(" Received federated authentication info token"); } if (!TryProcessFedAuthInfo(stateObj, tokenLength, out info)) @@ -4030,7 +4032,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, // Skip reading token length, since it has already been read in caller if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" FEDAUTHINFO token stream length = {tokenLen}"); + SqlClientEventSource.Log.Trace(" FEDAUTHINFO token stream length = {0}", tokenLen); } if (tokenLen < sizeof(uint)) @@ -4038,7 +4040,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, // the token must at least contain a DWORD indicating the number of info IDs if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); + SqlClientEventSource.Log.Trace(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); } throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen); } @@ -4049,7 +4051,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream."); + SqlClientEventSource.Log.Trace(" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream."); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadCountOfInfoIds); } @@ -4057,7 +4059,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" CountOfInfoIDs = {optionsCount.ToString(CultureInfo.InvariantCulture)}"); + SqlClientEventSource.Log.Trace(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); } if (tokenLen > 0) @@ -4069,14 +4071,14 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Read rest of FEDAUTHINFO token stream: {BitConverter.ToString(tokenData, 0, totalRead)}"); + SqlClientEventSource.Log.Trace(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); } if (!successfulRead || totalRead != tokenLen) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Failed to read FEDAUTHINFO token stream. Attempted to read {tokenLen} bytes, actually read {totalRead}"); + SqlClientEventSource.Log.Trace(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}", tokenLen, totalRead); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadTokenStream); } @@ -4099,7 +4101,10 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, uint dataLen = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 1))); uint dataOffset = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 5))); - SqlClientEventSource.Log.Trace($" FedAuthInfoOpt: ID={id}, DataLen={dataLen.ToString(CultureInfo.InvariantCulture)}, Offset={dataOffset.ToString(CultureInfo.InvariantCulture)}\n"); + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + SqlClientEventSource.Log.Trace(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture)); + } // offset is measured from optCount, so subtract to make offset measured // from the beginning of tokenData @@ -4113,7 +4118,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" FedAuthInfoDataOffset points to an invalid location."); + SqlClientEventSource.Log.Trace(" FedAuthInfoDataOffset points to an invalid location."); } throw SQL.ParsingErrorOffset(ParsingErrorState.FedAuthInfoInvalidOffset, unchecked((int)dataOffset)); } @@ -4128,7 +4133,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Failed to read FedAuthInfoData."); + SqlClientEventSource.Log.Trace(" Failed to read FedAuthInfoData."); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadData, e); } @@ -4136,14 +4141,14 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" FedAuthInfoData is not in unicode format."); + SqlClientEventSource.Log.Trace(" FedAuthInfoData is not in unicode format."); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e); } if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" FedAuthInfoData: {data}"); + SqlClientEventSource.Log.Trace(" FedAuthInfoData: {0}", data); } // store data in tempFedAuthInfo @@ -4158,7 +4163,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, default: if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Ignoring unknown federated authentication info option: {id}"); + SqlClientEventSource.Log.Trace(" Ignoring unknown federated authentication info option: {0}", id); } break; } @@ -4168,14 +4173,14 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" FEDAUTHINFO token stream is not long enough to contain the data it claims to."); + SqlClientEventSource.Log.Trace(" FEDAUTHINFO token stream is not long enough to contain the data it claims to."); } throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForData, tokenLen); } if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Processed FEDAUTHINFO token stream: {tempFedAuthInfo.ToString()}"); + SqlClientEventSource.Log.Trace(" Processed FEDAUTHINFO token stream: {0}", tempFedAuthInfo.ToString()); } if (string.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || string.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) @@ -4183,7 +4188,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, // We should be receiving both stsurl and spn if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" FEDAUTHINFO token stream does not contain both STSURL and SPN."); + SqlClientEventSource.Log.Trace(" FEDAUTHINFO token stream does not contain both STSURL and SPN."); } throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDoesNotContainStsurlAndSpn); } @@ -4614,7 +4619,7 @@ internal bool TryProcessTceCryptoMetadata(TdsParserStateObject stateObj, { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Incorrect ordinal received {index}, max tab size: {cipherTable.Value.Size}"); + SqlClientEventSource.Log.Trace(" Incorrect ordinal received {0}, max tab size: {1}", index, cipherTable.Value.Size); } throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidOrdinalIntoCipherInfoTable, index); } @@ -8885,7 +8890,7 @@ internal void TdsLogin(SqlLogin rec, if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, TDS Login7 flags = {log7Flags}:"); + SqlClientEventSource.Log.Trace(" {0}#, TDS Login7 flags = {1}:", ObjectID, log7Flags); } WriteInt(0, _physicalStateObj); // ClientTimeZone is not used @@ -9047,7 +9052,7 @@ internal void TdsLogin(SqlLogin rec, { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Sending federated authentication feature request"); + SqlClientEventSource.Log.Trace(" Sending federated authentication feature request"); } Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null."); WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true); @@ -9124,7 +9129,7 @@ internal void SendFedAuthToken(SqlFedAuthToken fedAuthToken) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Sending federated authentication token"); + SqlClientEventSource.Log.Trace(" Sending federated authentication token"); } _physicalStateObj._outputMessageType = TdsEnums.MT_FEDAUTH; @@ -9519,7 +9524,7 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Exception caught on ExecuteXXX: '{e.ToString()}'"); + SqlClientEventSource.Log.Trace(" Exception caught on ExecuteXXX: '{0}'", e.ToString()); } if (stateObj.HasOpenResult) @@ -9556,7 +9561,7 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Exception rethrown."); + SqlClientEventSource.Log.Trace(" Exception rethrown."); } } @@ -9615,7 +9620,7 @@ internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationReques { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#"); + SqlClientEventSource.Log.Trace(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}#", ObjectID); } } stateObj.SniContext = SniContext.Snix_Execute; @@ -9747,7 +9752,7 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Potential multi-threaded misuse of connection, non-MARs connection with an open result {ObjectID}#"); + SqlClientEventSource.Log.Trace(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}#", ObjectID); } } stateObj.SniContext = SniContext.Snix_Execute; @@ -10615,9 +10620,9 @@ private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefa if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, Sending parameter '{param.ParameterName}', default flag={sendDefaultValue}, metadata:{metaData.TraceString(3)}"); + SqlClientEventSource.Log.Trace(" {0}#, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); } - + // // Write parameter metadata // @@ -11672,7 +11677,7 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio Debug.Assert(-1 <= timeout, "Timeout"); - SqlClientEventSource.Log.NotificationsTrace($" NotificationRequest: userData: '{notificationRequest.UserData}', options: '{notificationRequest.Options}', timeout: '{notificationRequest.Timeout}'\n"); + SqlClientEventSource.Log.NotificationsTrace(" NotificationRequest: userData: '{0}', options: '{1}', timeout: '{2}'", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj); // Query notifications Type @@ -11701,7 +11706,7 @@ private void WriteTraceHeaderData(TdsParserStateObject stateObj) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" ActivityID {actId.ToString()}"); + SqlClientEventSource.Log.Trace(" ActivityID {0}", actId.ToString()); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index c09d454039..9efc9af57c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -39,7 +39,7 @@ internal TdsParserSessionPool(TdsParser parser) if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# created session pool for parser {parser.ObjectID}"); + SqlClientEventSource.Log.Trace(" {0}# created session pool for parser {1}", ObjectID, parser.ObjectID); } } @@ -66,8 +66,10 @@ internal void Deactivate() // sessions that are past what we want to keep around. long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}# deactivating cachedCount={_cachedCount}\n"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}# deactivating cachedCount={1}", ObjectID, _cachedCount); + } try { @@ -90,7 +92,7 @@ internal void Deactivate() if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# reclaiming session {session.ObjectID}"); + SqlClientEventSource.Log.Trace(" {0}# reclaiming session {1}", ObjectID, session.ObjectID); } PutSession(session); @@ -128,7 +130,7 @@ internal void Dispose() { if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# disposing cachedCount={_cachedCount}"); + SqlClientEventSource.Log.Trace(" {0}# disposing cachedCount={1}", ObjectID, _cachedCount); } lock (_cache) @@ -192,7 +194,7 @@ internal TdsParserStateObject GetSession(object owner) if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# adding session {session.ObjectID} to pool"); + SqlClientEventSource.Log.Trace(" {0}# adding session {1} to pool", ObjectID, session.ObjectID); } _cache.Add(session); @@ -204,7 +206,7 @@ internal TdsParserStateObject GetSession(object owner) if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# using session {session.ObjectID}"); + SqlClientEventSource.Log.Trace(" {0}# using session {1}", ObjectID, session.ObjectID); } return session; @@ -230,7 +232,7 @@ internal void PutSession(TdsParserStateObject session) // Session is good to re-use and our cache has space if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# keeping session {session.ObjectID} cachedCount={_cachedCount}"); + SqlClientEventSource.Log.Trace(" {0}# keeping session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); } Debug.Assert(!session._pendingData, "pending data on a pooled session?"); @@ -243,7 +245,7 @@ internal void PutSession(TdsParserStateObject session) // Either the session is bad, or we have no cache space - so dispose the session and remove it if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace($" {ObjectID}# disposing session {session.ObjectID} cachedCount={_cachedCount}"); + SqlClientEventSource.Log.Trace(" {0}# disposing session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); } bool removed = _cache.Remove(session); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index a4dd1f9a74..4efedb246a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -562,9 +562,9 @@ internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {stateObj.ObjectID}#, NBCROW bitmap received, column count = {columnsCount}"); + SqlClientEventSource.Log.Trace(" {0}#, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount); + SqlClientEventSource.Log.TraceBin(" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); } - SqlClientEventSource.Log.TraceBin($" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); return true; } @@ -920,14 +920,14 @@ internal int DecrementPendingCallbacks(bool release) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, after decrementing _pendingCallbacks: { _pendingCallbacks}"); + SqlClientEventSource.Log.Trace(" {0}#, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); } if ((0 == remaining || release) && _gcHandle.IsAllocated) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, FREEING HANDLE!"); + SqlClientEventSource.Log.Trace(" {0}#, FREEING HANDLE!", ObjectID); } _gcHandle.Free(); } @@ -1039,7 +1039,7 @@ internal int IncrementPendingCallbacks() if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, after incrementing _pendingCallbacks: {_pendingCallbacks}"); + SqlClientEventSource.Log.Trace(" {0}#, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); } Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}"); @@ -2176,7 +2176,7 @@ internal bool TryReadNetworkPacket() #endif if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Async packet replay"); + SqlClientEventSource.Log.Trace(" Async packet replay"); } return true; } @@ -2601,7 +2601,7 @@ internal bool IsConnectionAlive(bool throwOnException) // Connection is dead if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" received error {(int)error} on idle connection"); + SqlClientEventSource.Log.Trace(" received error {0} on idle connection", (int)error); } isAlive = false; if (throwOnException) @@ -2820,7 +2820,7 @@ public void ProcessSniPacket(IntPtr packet, UInt32 error) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.TraceBin($" Packet read", _inBuff, (UInt16)_inBytesRead); + SqlClientEventSource.Log.TraceBin(" Packet read", _inBuff, (UInt16)_inBytesRead); } AssertValidState(); @@ -2981,7 +2981,7 @@ public void WriteAsyncCallback(IntPtr key, IntPtr packet, UInt32 sniError) { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" write async returned error code {(int)sniError}"); + SqlClientEventSource.Log.Trace(" write async returned error code {0}", (int)sniError); } try @@ -3453,7 +3453,7 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" write async returned error code {(int)error}"); + SqlClientEventSource.Log.Trace(" write async returned error code {0}", (int)error); } AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(); @@ -3493,7 +3493,7 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" write async returned error code {(int)sniError}"); + SqlClientEventSource.Log.Trace(" write async returned error code {0}", (int)sniError); } AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(callerHasConnectionLock); @@ -3557,7 +3557,7 @@ internal void SendAttention(bool mustTakeWriteLock = false) if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Send Attention ASync."); + SqlClientEventSource.Log.Trace(" Send Attention ASync."); } } finally @@ -3581,11 +3581,11 @@ internal void SendAttention(bool mustTakeWriteLock = false) _attentionSending = false; } - SqlClientEventSource.Log.TraceBin($" Packet sent", _outBuff, (ushort)_outBytesUsed); + SqlClientEventSource.Log.TraceBin(" Packet sent", _outBuff, (ushort)_outBytesUsed); if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" Attention sent to the server."); + SqlClientEventSource.Log.Trace(" Attention sent to the server."); } AssertValidState(); @@ -3770,7 +3770,7 @@ private void SniWriteStatisticsAndTracing() _traceChangePasswordOffset = 0; _traceChangePasswordLength = 0; } - SqlClientEventSource.Log.TraceBin($" Packet sent", _outBuff, (UInt16)_outBytesUsed); + SqlClientEventSource.Log.TraceBin(" Packet sent", _outBuff, (UInt16)_outBytesUsed); } [Conditional("DEBUG")] diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs index 59fecfea32..28909a4981 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs @@ -54,7 +54,9 @@ internal SqlInternalTransaction(SqlInternalConnection innerConnection, Transacti internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction, long transactionId) { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Created for connection {innerConnection.ObjectID}#, outer transaction {((null != outerTransaction) ? outerTransaction.ObjectID : -1)}#, Type {(int)type}"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Created for connection {1}#, outer transaction {2}#, Type {3}", ObjectID, innerConnection.ObjectID, (null != outerTransaction) ? outerTransaction.ObjectID : -1, (int)type); + } _innerConnection = innerConnection; _transactionType = type; @@ -271,7 +273,9 @@ internal void CloseFromConnection() Debug.Assert(innerConnection != null, "How can we be here if the connection is null?"); if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Closing"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Closing", ObjectID); + } bool processFinallyBlock = true; try @@ -300,8 +304,10 @@ internal void CloseFromConnection() internal void Commit() { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + } if (_innerConnection.IsLockedForBulkCopy) { @@ -376,7 +382,9 @@ internal void Dispose() private /*protected override*/ void Dispose(bool disposing) { if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - SqlClientEventSource.Log.PoolerTrace($" {ObjectID}#, Disposing"); + { + SqlClientEventSource.Log.PoolerTrace(" {0}#, Disposing", ObjectID); + } if (disposing) { @@ -432,7 +440,7 @@ internal void InitParent(SqlTransaction transaction) internal void Rollback() { - var scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + var scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { @@ -479,7 +487,11 @@ internal void Rollback() internal void Rollback(string transactionName) { - var scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, transactionName='{transactionName}'"); + long scopeID = 0; + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#, transactionName='{transactionName}'", ObjectID); + } if (_innerConnection.IsLockedForBulkCopy) { @@ -528,7 +540,11 @@ internal void Rollback(string transactionName) internal void Save(string savePointName) { - var scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#, savePointName='{savePointName}'"); + long scopeID = 0; + if (SqlClientEventSource.Log.IsScopeEnabled()) + { + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#, savePointName='{savePointName}'", ObjectID); + } _innerConnection.ValidateConnectionForExecute(null); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs index ea6fb6726b..7a48f59874 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs @@ -66,9 +66,9 @@ Int64 allocationSize ) { long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) + if (SqlClientEventSource.Log.IsScopeEnabled()) { - scopeID = SqlClientEventSource.Log.ScopeEnter($" { ObjectID}# access={(int)access} options={(int)options} path='{path}'"); + scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}# access={1} options={2} path='{3}'", ObjectID, (int)access, (int)options, path); } try @@ -720,8 +720,8 @@ Int64 allocationSize { if (SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace($" {ObjectID}#, desiredAccess=0x{(int)nDesiredAccess}, allocationSize={allocationSize}, " + - $"fileAttributes=0x%{0}, shareAccess=0x{(int)shareAccess}, dwCreateDisposition=0x{dwCreateDisposition}, createOptions=0x{ dwCreateOptions}"); + SqlClientEventSource.Log.Trace(" {0}#, desiredAccess=0x{1}, allocationSize={2}, " + + "fileAttributes=0x{3}, shareAccess=0x{4}, dwCreateDisposition=0x{5}, createOptions=0x{ dwCreateOptions}", ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition); } retval = UnsafeNativeMethods.NtCreateFile(out hFile, nDesiredAccess, From 9d1167751059b4d6b526fa3a04ac97d575c702e3 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 11 Feb 2020 15:07:44 -0800 Subject: [PATCH 24/46] Fixing test issues --- ...ClientEventSourceTest.cs => EventSourceTest.cs} | 14 +++++++------- ...osoft.Data.SqlClient.ManualTesting.Tests.csproj | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) rename src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/{SqlClientEventSourceTest.cs => EventSourceTest.cs} (85%) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/SqlClientEventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs similarity index 85% rename from src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/SqlClientEventSourceTest.cs rename to src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs index 839f49367a..93a49e7f8b 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/SqlClientEventSourceTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs @@ -4,22 +4,19 @@ using System.Collections.Generic; using System.Diagnostics.Tracing; -using Microsoft.Data.SqlClient.ManualTesting.Tests; using Xunit; -namespace Microsoft.Data.SqlClient.Tests +namespace Microsoft.Data.SqlClient.ManualTesting.Tests.EventSource { [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "Not Implemented")] - public class SqlClientEventSourceTest + public class EventSourceTest { [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void IsTraceEnabled() { - string connString = DataTestUtility.TCPConnectionString; using (var listener = new SampleEventListener()) { - listener.EnableEvents(SqlClientEventSource.Log, EventLevel.Informational, SqlClientEventSource.Keywords.Trace); - using (SqlConnection connection = new SqlConnection(connString)) + using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand("SELECT * From [Customers]", connection)) @@ -27,19 +24,22 @@ public void IsTraceEnabled() command.ExecuteNonQuery(); } } + //Check if all the events are from Trace foreach (var item in listener.eventsNames) { Assert.Contains("Trace", item); } - +#if net46 //Check if we can disable the events listener.DisableEvents(SqlClientEventSource.Log); + Assert.False(SqlClientEventSource.Log.IsEnabled()); //Check if we are able to enable events again listener.EnableEvents(SqlClientEventSource.Log, EventLevel.Informational); Assert.True(SqlClientEventSource.Log.IsEnabled()); +#endif } } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj index 210bd28e25..ca06a8cac6 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj @@ -56,7 +56,7 @@ - + From 6397d77b1d1d42f00e8425e191b29146221e11a9 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 11 Feb 2020 15:51:26 -0800 Subject: [PATCH 25/46] more fixes --- .../netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index a6e28d491e..021c970825 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -1036,7 +1036,9 @@ override public void Prepare() } if (SqlClientEventSource.Log.IsCorrelationEnabled()) + { SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + } statistics = SqlStatistics.StartTimer(Statistics); @@ -1470,7 +1472,7 @@ override public int ExecuteNonQuery() scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); } - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + if (SqlClientEventSource.Log.IsCorrelationEnabled()) { SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); } @@ -2032,6 +2034,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st RunExecuteNonQuerySmi(sendToPipe); } + //Always Encrypted generally operates only on parameterized queries. However enclave based Always encrypted also supports unparameterized queries //We skip this block for enclave based always encrypted so that we can make a call to SQL Server to get the encryption information else if (!ShouldUseEnclaveBasedWorkflow && !BatchRPCMode && (System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters))) @@ -2055,9 +2058,9 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st task = RunExecuteNonQueryTds(methodName, async, timeout, asyncWrite); } else - { // otherwise, use a full-fledged execute that can handle params and stored procs + { + // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); - if (SqlClientEventSource.Log.IsTraceEnabled()) { SqlClientEventSource.Log.Trace(" {0}#, Command executed as RPC.", ObjectID); @@ -2466,7 +2469,6 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) new public SqlDataReader ExecuteReader() { SqlStatistics statistics = null; - long scopeID = 0; if (SqlClientEventSource.Log.IsScopeEnabled()) { From 4cf1a081c1d035755d92b509ab1e1b115f1b97d6 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 11 Feb 2020 16:25:54 -0800 Subject: [PATCH 26/46] EventSource --- .../netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index 021c970825..b36a4816ec 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -2543,7 +2543,6 @@ internal SqlDataReader ExecuteReader(CommandBehavior behavior, string method) // Reset _pendingCancel upon entry into any Execute - used to synchronize state // between entry into Execute* API and the thread obtaining the stateObject. _pendingCancel = false; - SqlStatistics statistics = null; TdsParser bestEffortCleanupTarget = null; From 388bba6d47d1b773d149c6de4e4a6e01e8eb5938 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Thu, 13 Feb 2020 11:22:38 -0800 Subject: [PATCH 27/46] ActivityCorrelator added. --- .../SqlClientEventSource.xml | 53 ------------------- .../src/Microsoft/Data/Common/AdapterUtil.cs | 2 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 4 +- .../Data/SqlClient/SqlClientEventSource.cs | 47 ++++++++-------- .../Microsoft/Data/SqlClient/SqlCommand.cs | 42 +++++++-------- .../Microsoft/Data/SqlClient/SqlConnection.cs | 14 ++--- .../Data/SqlClient/SqlDataAdapter.cs | 2 +- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 2 +- .../Data/SqlClient/SqlTransaction.cs | 4 +- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 7 +-- 10 files changed, 60 insertions(+), 117 deletions(-) delete mode 100644 doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml deleted file mode 100644 index d802e648e4..0000000000 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - This class implements class and provides ability to create events for event tracing for Windows(ETW). - - - - This is the singleton instance of the class. - - - - This class provides supported Keywords from an EventSource consumer point of view, but these definitions are not needed outside this class. - - - Enabling this event turns on the 'Trace' events for listening implementation. - - 1 - - Enabling this event turns on the 'Scope' events for listening implementation. - 2 - - - Enabling this event turns on the 'NotificationTrace' events for listening implementation. - 4 - - - Enabling this event turns on the 'Pooling' events for listening implementation. - 8 - - - Enabling this event turns on the 'Correlation' events for listening implementation. - 16 - - - Enabling this event turns on the 'NotificationScope' events for listening implementation. - 32 - - - Enabling this event turns on the 'PoolerScope' events for listening implementation. - 64 - - - Enabling this event turns on 'PoolerTrace' events for listening implementation. - 128 - - - Enabling this event turns on 'Advanced' events for listening implementation. - 512 - - - - diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index 2dba4ec6f6..0ae2035649 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -102,7 +102,7 @@ static private void TraceException( Debug.Assert(null != e, "TraceException: null Exception"); if (null != e && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace(trace,e.ToString()); // will include callstack if permission is available + SqlClientEventSource.Log.Trace(trace, e.ToString()); // will include callstack if permission is available } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index 2bcedd8b88..95b1f8d2f1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs @@ -602,7 +602,7 @@ private Task CreateAndExecuteInitialQueryAsync(out Bulk if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID %ls", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); @@ -895,7 +895,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i private Task SubmitUpdateBulkCommand(string TDSCommand) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index aba11927f3..5cb18b9ee1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -8,12 +8,10 @@ namespace Microsoft.Data.SqlClient { - /// [EventSource(Name = "Microsoft.Data.SqlClient.EventSource")] - public class SqlClientEventSource : EventSource + internal class SqlClientEventSource : EventSource { - /// - public static readonly SqlClientEventSource Log = new SqlClientEventSource(); + internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); private static long s_nextScopeId = 0; private static long s_nextNotificationScopeId = 0; @@ -27,36 +25,28 @@ public class SqlClientEventSource : EventSource private const int PoolerScopeEnterId = 8; private const int PoolerTraceId = 9; + //if we add more keywords they need to be a power of 2. + //Keyword class needs to be nested inside this class otherwise nothing will be logged as the SqlClientEventSource wont have contorol over that. #region Keywords - /// - public class Keywords + internal class Keywords { - /// - public const EventKeywords Trace = (EventKeywords)1; + internal const EventKeywords Trace = (EventKeywords)1; - /// - public const EventKeywords Scope = (EventKeywords)2; + internal const EventKeywords Scope = (EventKeywords)2; - /// - public const EventKeywords NotificationTrace = (EventKeywords)4; + internal const EventKeywords NotificationTrace = (EventKeywords)4; - /// - public const EventKeywords Pooling = (EventKeywords)8; + internal const EventKeywords Pooling = (EventKeywords)8; - /// - public const EventKeywords Correlation = (EventKeywords)16; + internal const EventKeywords Correlation = (EventKeywords)16; - /// - public const EventKeywords NotificationScope = (EventKeywords)32; + internal const EventKeywords NotificationScope = (EventKeywords)32; - /// - public const EventKeywords PoolerScope = (EventKeywords)64; + internal const EventKeywords PoolerScope = (EventKeywords)64; - /// - public const EventKeywords PoolerTrace = (EventKeywords)128; + internal const EventKeywords PoolerTrace = (EventKeywords)128; - /// - public const EventKeywords Advanced = (EventKeywords)512; + internal const EventKeywords Advanced = (EventKeywords)512; } #endregion @@ -169,7 +159,6 @@ internal long ScopeEnter(string message, T0 args0, T1 args1, T2 } [NonEvent] - internal long PoolerScopeEnter(string message, T0 args0) { return PoolerScopeEnter(string.Format(message, args0)); @@ -235,6 +224,12 @@ internal void CorrelationTrace(string message, T0 args0, T1 args1) CorrelationTrace(string.Format(message, args0, args1)); } + [NonEvent] + internal void CorrelationTrace(string message, T0 args0, T1 args1, T2 args2) + { + CorrelationTrace(string.Format(message, args0, args1, args2)); + } + [NonEvent] internal void NotificationsTrace(string message, T0 args0) { @@ -274,7 +269,7 @@ internal long ScopeEnter(string message) if (SqlClientEventSource.Log.IsEnabled()) { scopeId = Interlocked.Increment(ref s_nextScopeId); - WriteEvent(EnterScopeId, scopeId, message); + WriteEvent(EnterScopeId, message); } return scopeId; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index b36a4816ec..24b07f975f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -1037,7 +1037,7 @@ override public void Prepare() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } statistics = SqlStatistics.StartTimer(Statistics); @@ -1225,7 +1225,7 @@ override public void Cancel() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } SqlStatistics statistics = null; @@ -1397,7 +1397,7 @@ override public object ExecuteScalar() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } bool success = false; @@ -1474,7 +1474,7 @@ override public int ExecuteNonQuery() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } bool success = false; @@ -1546,7 +1546,7 @@ public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObj { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } SqlConnection.ExecutePermission.Demand(); @@ -1776,7 +1776,7 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } } } @@ -1797,7 +1797,7 @@ private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); @@ -2058,7 +2058,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st task = RunExecuteNonQueryTds(methodName, async, timeout, asyncWrite); } else - { + { // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); if (SqlClientEventSource.Log.IsTraceEnabled()) @@ -2126,7 +2126,7 @@ public XmlReader ExecuteXmlReader() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } bool success = false; @@ -2170,7 +2170,7 @@ public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateOb { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } SqlConnection.ExecutePermission.Demand(); @@ -2327,7 +2327,7 @@ public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } } } @@ -2336,7 +2336,7 @@ private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); @@ -2459,7 +2459,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } return ExecuteReader(behavior, ADP.ExecuteReader); @@ -2477,7 +2477,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } try @@ -2503,7 +2503,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{ObjectID}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); } try @@ -2529,7 +2529,7 @@ public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObjec { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); } SqlConnection.ExecutePermission.Demand(); @@ -2614,7 +2614,7 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } } } @@ -2623,7 +2623,7 @@ private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); @@ -3028,7 +3028,7 @@ public override Task ExecuteNonQueryAsync(CancellationToken cancellationTok { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } SqlConnection.ExecutePermission.Demand(); @@ -3117,7 +3117,7 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); } SqlConnection.ExecutePermission.Demand(); @@ -3255,7 +3255,7 @@ public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } SqlConnection.ExecutePermission.Demand(); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index 8277c81cb8..68086117e0 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -1177,7 +1177,7 @@ override public void ChangeDatabase(string database) if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, EventSource.GetGuid(typeof(SqlClientEventSource))); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } TdsParser bestEffortCleanupTarget = null; @@ -1280,7 +1280,7 @@ override public void Close() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, EventSource.GetGuid(typeof(SqlClientEventSource))); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } try @@ -1422,12 +1422,12 @@ override public void Open() long scopeID = 0; if (SqlClientEventSource.Log.IsScopeEnabled()) { - scopeID = SqlClientEventSource.Log.ScopeEnter(" ObjectID: {0}, ActivityID {1}", ObjectID); + scopeID = SqlClientEventSource.Log.ScopeEnter(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, EventSource.GetGuid(typeof(SqlClientEventSource))); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } try @@ -1710,7 +1710,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, EventSource.GetGuid(typeof(SqlClientEventSource))); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } try @@ -2510,7 +2510,7 @@ public static void ChangePassword(string connectionString, string newPassword) if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ActivityID {0}", EventSource.GetGuid(typeof(SqlClientEventSource))); + SqlClientEventSource.Log.CorrelationTrace(" ActivityID {0}", ActivityCorrelator.Current.ToString()); } try @@ -2566,7 +2566,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ActivityID {0}", EventSource.GetGuid(typeof(SqlClientEventSource))); + SqlClientEventSource.Log.CorrelationTrace(" ActivityID {0}", ActivityCorrelator.Current.ToString()); } try diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index bb2eb5ac3b..02fea66625 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -255,7 +255,7 @@ override protected int ExecuteBatch() Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); return _commandSet.ExecuteNonQuery(); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs index e64f15c448..22d9a8d12c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -4493,7 +4493,7 @@ private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateO { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID '{1}'", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID '{1}'", ObjectID, ActivityCorrelator.Current.ToString()); } Task executeTask = parser.TdsExecuteSQLBatch(_resetOptionsString, (_command != null) ? _command.CommandTimeout : 0, null, stateObj, sync: true); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs index c8addbdbfe..987b3eb0d3 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -151,7 +151,7 @@ override public void Commit() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } TdsParser bestEffortCleanupTarget = null; @@ -298,7 +298,7 @@ override public void Rollback() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } TdsParser bestEffortCleanupTarget = null; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index cd3b2f7f45..406ca3582f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -2140,7 +2140,6 @@ internal bool RunReliably(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDat } } - internal bool Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) { bool syncOverAsync = stateObj._syncOverAsync; @@ -2951,6 +2950,7 @@ private bool TryProcessEnvChange(int tokenLength, TdsParserStateObject stateObj, // Changing packet size does not support retry, should not pend" throw SQL.SynchronousCallMayNotPend(); } + // Only set on physical state object - this should only occur on LoginAck prior // to MARS initialization! Int32 packetSize = Int32.Parse(env.newValue, NumberStyles.Integer, CultureInfo.InvariantCulture); @@ -3275,7 +3275,6 @@ private bool TryProcessDone(SqlCommand cmd, SqlDataReader reader, ref RunBehavio // status // command // rowcount (valid only if DONE_COUNT bit is set) - if (!stateObj.TryReadUInt16(out status)) { return false; @@ -3300,6 +3299,7 @@ private bool TryProcessDone(SqlCommand cmd, SqlDataReader reader, ref RunBehavio { return false; } + // If we haven't yet completed processing login token stream yet, we may be talking to a Yukon server // In that case we still have to read another 4 bytes // But don't try to read beyond the TDS stream in this case, because it generates errors if login failed. @@ -3347,6 +3347,7 @@ private bool TryProcessDone(SqlCommand cmd, SqlDataReader reader, ref RunBehavio cmd.InternalRecordsAffected = count; } } + // Skip the bogus DONE counts sent by the server if (stateObj._receivedColMetaData || (curCmd != TdsEnums.SELECT)) { @@ -3922,7 +3923,6 @@ private bool TryProcessLoginAck(TdsParserStateObject stateObj, out SqlLoginAck s // 0x71000001 -> Shiloh SP1 // 0x72xx0002 -> Yukon RTM // information provided by S. Ashwin - switch (majorMinor) { case TdsEnums.SPHINXORSHILOH_MAJOR << 24 | TdsEnums.DEFAULT_MINOR: // Sphinx & Shiloh RTM @@ -4280,6 +4280,7 @@ internal bool TryProcessError(byte token, TdsParserStateObject stateObj, out Sql return false; } line = shortLine; + // If we haven't yet completed processing login token stream yet, we may be talking to a Yukon server // In that case we still have to read another 2 bytes if (_state == TdsParserState.OpenNotLoggedIn) From 96614db22e2cfedc2fe79cb0996565cba1d93444 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Thu, 13 Feb 2020 11:22:38 -0800 Subject: [PATCH 28/46] ActivityCorrelator added. --- .../SqlClientEventSource_EventLogger.cs | 2 +- .../SqlClientEventSource.xml | 53 ------------------- .../src/Microsoft/Data/Common/AdapterUtil.cs | 2 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 4 +- .../Data/SqlClient/SqlClientEventSource.cs | 47 ++++++++-------- .../Microsoft/Data/SqlClient/SqlCommand.cs | 42 +++++++-------- .../Microsoft/Data/SqlClient/SqlConnection.cs | 14 ++--- .../Data/SqlClient/SqlDataAdapter.cs | 2 +- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 2 +- .../Data/SqlClient/SqlTransaction.cs | 4 +- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 7 +-- 11 files changed, 61 insertions(+), 118 deletions(-) delete mode 100644 doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml diff --git a/doc/samples/SqlClientEventSource_EventLogger.cs b/doc/samples/SqlClientEventSource_EventLogger.cs index 429df7cc62..39b8a0213d 100644 --- a/doc/samples/SqlClientEventSource_EventLogger.cs +++ b/doc/samples/SqlClientEventSource_EventLogger.cs @@ -28,7 +28,7 @@ static void Main(string[] args) } } -public class SampleEventListener : EventListenr +public class SampleEventListener : EventListener { static TextWriter Out = Console.Out; diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml deleted file mode 100644 index d802e648e4..0000000000 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlClientEventSource.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - This class implements class and provides ability to create events for event tracing for Windows(ETW). - - - - This is the singleton instance of the class. - - - - This class provides supported Keywords from an EventSource consumer point of view, but these definitions are not needed outside this class. - - - Enabling this event turns on the 'Trace' events for listening implementation. - - 1 - - Enabling this event turns on the 'Scope' events for listening implementation. - 2 - - - Enabling this event turns on the 'NotificationTrace' events for listening implementation. - 4 - - - Enabling this event turns on the 'Pooling' events for listening implementation. - 8 - - - Enabling this event turns on the 'Correlation' events for listening implementation. - 16 - - - Enabling this event turns on the 'NotificationScope' events for listening implementation. - 32 - - - Enabling this event turns on the 'PoolerScope' events for listening implementation. - 64 - - - Enabling this event turns on 'PoolerTrace' events for listening implementation. - 128 - - - Enabling this event turns on 'Advanced' events for listening implementation. - 512 - - - - diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index 2dba4ec6f6..0ae2035649 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -102,7 +102,7 @@ static private void TraceException( Debug.Assert(null != e, "TraceException: null Exception"); if (null != e && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace(trace,e.ToString()); // will include callstack if permission is available + SqlClientEventSource.Log.Trace(trace, e.ToString()); // will include callstack if permission is available } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index 2bcedd8b88..95b1f8d2f1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs @@ -602,7 +602,7 @@ private Task CreateAndExecuteInitialQueryAsync(out Bulk if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID %ls", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); @@ -895,7 +895,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i private Task SubmitUpdateBulkCommand(string TDSCommand) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index aba11927f3..5cb18b9ee1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -8,12 +8,10 @@ namespace Microsoft.Data.SqlClient { - /// [EventSource(Name = "Microsoft.Data.SqlClient.EventSource")] - public class SqlClientEventSource : EventSource + internal class SqlClientEventSource : EventSource { - /// - public static readonly SqlClientEventSource Log = new SqlClientEventSource(); + internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); private static long s_nextScopeId = 0; private static long s_nextNotificationScopeId = 0; @@ -27,36 +25,28 @@ public class SqlClientEventSource : EventSource private const int PoolerScopeEnterId = 8; private const int PoolerTraceId = 9; + //if we add more keywords they need to be a power of 2. + //Keyword class needs to be nested inside this class otherwise nothing will be logged as the SqlClientEventSource wont have contorol over that. #region Keywords - /// - public class Keywords + internal class Keywords { - /// - public const EventKeywords Trace = (EventKeywords)1; + internal const EventKeywords Trace = (EventKeywords)1; - /// - public const EventKeywords Scope = (EventKeywords)2; + internal const EventKeywords Scope = (EventKeywords)2; - /// - public const EventKeywords NotificationTrace = (EventKeywords)4; + internal const EventKeywords NotificationTrace = (EventKeywords)4; - /// - public const EventKeywords Pooling = (EventKeywords)8; + internal const EventKeywords Pooling = (EventKeywords)8; - /// - public const EventKeywords Correlation = (EventKeywords)16; + internal const EventKeywords Correlation = (EventKeywords)16; - /// - public const EventKeywords NotificationScope = (EventKeywords)32; + internal const EventKeywords NotificationScope = (EventKeywords)32; - /// - public const EventKeywords PoolerScope = (EventKeywords)64; + internal const EventKeywords PoolerScope = (EventKeywords)64; - /// - public const EventKeywords PoolerTrace = (EventKeywords)128; + internal const EventKeywords PoolerTrace = (EventKeywords)128; - /// - public const EventKeywords Advanced = (EventKeywords)512; + internal const EventKeywords Advanced = (EventKeywords)512; } #endregion @@ -169,7 +159,6 @@ internal long ScopeEnter(string message, T0 args0, T1 args1, T2 } [NonEvent] - internal long PoolerScopeEnter(string message, T0 args0) { return PoolerScopeEnter(string.Format(message, args0)); @@ -235,6 +224,12 @@ internal void CorrelationTrace(string message, T0 args0, T1 args1) CorrelationTrace(string.Format(message, args0, args1)); } + [NonEvent] + internal void CorrelationTrace(string message, T0 args0, T1 args1, T2 args2) + { + CorrelationTrace(string.Format(message, args0, args1, args2)); + } + [NonEvent] internal void NotificationsTrace(string message, T0 args0) { @@ -274,7 +269,7 @@ internal long ScopeEnter(string message) if (SqlClientEventSource.Log.IsEnabled()) { scopeId = Interlocked.Increment(ref s_nextScopeId); - WriteEvent(EnterScopeId, scopeId, message); + WriteEvent(EnterScopeId, message); } return scopeId; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index b36a4816ec..24b07f975f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -1037,7 +1037,7 @@ override public void Prepare() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } statistics = SqlStatistics.StartTimer(Statistics); @@ -1225,7 +1225,7 @@ override public void Cancel() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } SqlStatistics statistics = null; @@ -1397,7 +1397,7 @@ override public object ExecuteScalar() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } bool success = false; @@ -1474,7 +1474,7 @@ override public int ExecuteNonQuery() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } bool success = false; @@ -1546,7 +1546,7 @@ public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObj { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } SqlConnection.ExecutePermission.Demand(); @@ -1776,7 +1776,7 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } } } @@ -1797,7 +1797,7 @@ private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); @@ -2058,7 +2058,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st task = RunExecuteNonQueryTds(methodName, async, timeout, asyncWrite); } else - { + { // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); if (SqlClientEventSource.Log.IsTraceEnabled()) @@ -2126,7 +2126,7 @@ public XmlReader ExecuteXmlReader() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } bool success = false; @@ -2170,7 +2170,7 @@ public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateOb { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } SqlConnection.ExecutePermission.Demand(); @@ -2327,7 +2327,7 @@ public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } } } @@ -2336,7 +2336,7 @@ private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); @@ -2459,7 +2459,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } return ExecuteReader(behavior, ADP.ExecuteReader); @@ -2477,7 +2477,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } try @@ -2503,7 +2503,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{ObjectID}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); } try @@ -2529,7 +2529,7 @@ public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObjec { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); } SqlConnection.ExecutePermission.Demand(); @@ -2614,7 +2614,7 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } } } @@ -2623,7 +2623,7 @@ private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); @@ -3028,7 +3028,7 @@ public override Task ExecuteNonQueryAsync(CancellationToken cancellationTok { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } SqlConnection.ExecutePermission.Demand(); @@ -3117,7 +3117,7 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); } SqlConnection.ExecutePermission.Demand(); @@ -3255,7 +3255,7 @@ public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } SqlConnection.ExecutePermission.Demand(); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index 8277c81cb8..68086117e0 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -1177,7 +1177,7 @@ override public void ChangeDatabase(string database) if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, EventSource.GetGuid(typeof(SqlClientEventSource))); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } TdsParser bestEffortCleanupTarget = null; @@ -1280,7 +1280,7 @@ override public void Close() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, EventSource.GetGuid(typeof(SqlClientEventSource))); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } try @@ -1422,12 +1422,12 @@ override public void Open() long scopeID = 0; if (SqlClientEventSource.Log.IsScopeEnabled()) { - scopeID = SqlClientEventSource.Log.ScopeEnter(" ObjectID: {0}, ActivityID {1}", ObjectID); + scopeID = SqlClientEventSource.Log.ScopeEnter(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, EventSource.GetGuid(typeof(SqlClientEventSource))); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } try @@ -1710,7 +1710,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, EventSource.GetGuid(typeof(SqlClientEventSource))); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } try @@ -2510,7 +2510,7 @@ public static void ChangePassword(string connectionString, string newPassword) if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ActivityID {0}", EventSource.GetGuid(typeof(SqlClientEventSource))); + SqlClientEventSource.Log.CorrelationTrace(" ActivityID {0}", ActivityCorrelator.Current.ToString()); } try @@ -2566,7 +2566,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ActivityID {0}", EventSource.GetGuid(typeof(SqlClientEventSource))); + SqlClientEventSource.Log.CorrelationTrace(" ActivityID {0}", ActivityCorrelator.Current.ToString()); } try diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index bb2eb5ac3b..02fea66625 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -255,7 +255,7 @@ override protected int ExecuteBatch() Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); return _commandSet.ExecuteNonQuery(); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs index e64f15c448..22d9a8d12c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -4493,7 +4493,7 @@ private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateO { if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID '{1}'", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID '{1}'", ObjectID, ActivityCorrelator.Current.ToString()); } Task executeTask = parser.TdsExecuteSQLBatch(_resetOptionsString, (_command != null) ? _command.CommandTimeout : 0, null, stateObj, sync: true); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs index c8addbdbfe..987b3eb0d3 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -151,7 +151,7 @@ override public void Commit() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } TdsParser bestEffortCleanupTarget = null; @@ -298,7 +298,7 @@ override public void Rollback() if (SqlClientEventSource.Log.IsCorrelationEnabled()) { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID); + SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } TdsParser bestEffortCleanupTarget = null; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index cd3b2f7f45..406ca3582f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -2140,7 +2140,6 @@ internal bool RunReliably(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDat } } - internal bool Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) { bool syncOverAsync = stateObj._syncOverAsync; @@ -2951,6 +2950,7 @@ private bool TryProcessEnvChange(int tokenLength, TdsParserStateObject stateObj, // Changing packet size does not support retry, should not pend" throw SQL.SynchronousCallMayNotPend(); } + // Only set on physical state object - this should only occur on LoginAck prior // to MARS initialization! Int32 packetSize = Int32.Parse(env.newValue, NumberStyles.Integer, CultureInfo.InvariantCulture); @@ -3275,7 +3275,6 @@ private bool TryProcessDone(SqlCommand cmd, SqlDataReader reader, ref RunBehavio // status // command // rowcount (valid only if DONE_COUNT bit is set) - if (!stateObj.TryReadUInt16(out status)) { return false; @@ -3300,6 +3299,7 @@ private bool TryProcessDone(SqlCommand cmd, SqlDataReader reader, ref RunBehavio { return false; } + // If we haven't yet completed processing login token stream yet, we may be talking to a Yukon server // In that case we still have to read another 4 bytes // But don't try to read beyond the TDS stream in this case, because it generates errors if login failed. @@ -3347,6 +3347,7 @@ private bool TryProcessDone(SqlCommand cmd, SqlDataReader reader, ref RunBehavio cmd.InternalRecordsAffected = count; } } + // Skip the bogus DONE counts sent by the server if (stateObj._receivedColMetaData || (curCmd != TdsEnums.SELECT)) { @@ -3922,7 +3923,6 @@ private bool TryProcessLoginAck(TdsParserStateObject stateObj, out SqlLoginAck s // 0x71000001 -> Shiloh SP1 // 0x72xx0002 -> Yukon RTM // information provided by S. Ashwin - switch (majorMinor) { case TdsEnums.SPHINXORSHILOH_MAJOR << 24 | TdsEnums.DEFAULT_MINOR: // Sphinx & Shiloh RTM @@ -4280,6 +4280,7 @@ internal bool TryProcessError(byte token, TdsParserStateObject stateObj, out Sql return false; } line = shortLine; + // If we haven't yet completed processing login token stream yet, we may be talking to a Yukon server // In that case we still have to read another 2 bytes if (_state == TdsParserState.OpenNotLoggedIn) From f0c1c0a4730417d3dfc6e39262387fee0c9612a3 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Thu, 13 Feb 2020 15:01:59 -0800 Subject: [PATCH 29/46] fixing AdvanceTraceOn issues --- .../Data/Common/DbConnectionOptions.cs | 9 +++--- .../Microsoft/Data/SqlClient/SqlCommand.cs | 12 ++++---- .../Data/SqlClient/SqlDataReaderSmi.cs | 4 --- .../Data/SqlClient/SqlInternalConnection.cs | 12 ++------ .../SqlClient/SqlInternalConnectionSmi.cs | 4 +-- .../SqlClient/SqlInternalConnectionTds.cs | 20 ++++++------- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 28 ++++++++++--------- .../Data/SqlClient/TdsParserStateObject.cs | 12 +++++--- .../Microsoft/Data/SqlTypes/SqlFileStream.cs | 2 +- 9 files changed, 46 insertions(+), 57 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs index 527d39be7e..6d73e0a9c3 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs @@ -627,12 +627,11 @@ internal string ExpandKeyword(string keyword, string replacementValue) [System.Diagnostics.Conditional("DEBUG")] private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hashtable synonyms) { - Debug.Assert(keyname == keyname.ToLower(CultureInfo.InvariantCulture), "missing ToLower"); - - string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); - - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { + Debug.Assert(keyname == keyname.ToLower(CultureInfo.InvariantCulture), "missing ToLower"); + string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); + if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) { // don't trace passwords ever! if (null != keyvalue) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index 24b07f975f..cdb1b3f945 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -372,13 +372,13 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}# metaData.Length={1}.", _command.ObjectID, (null != metaData) ? metaData.Length : -1); - } - if (null != metaData && SqlClientEventSource.Log.IsTraceEnabled()) - { - for (int i = 0; i < metaData.Length; i++) + if (null != metaData) { - SqlClientEventSource.Log.Trace(" {0}#, metaData[{1}] is {2}{3}", _command.ObjectID, i, metaData[i].GetType().ToString(), metaData[i].TraceString()); + for (int i = 0; i < metaData.Length; i++) + { + SqlClientEventSource.Log.Trace(" {0}#, metaData[{1}] is {2}{3}", _command.ObjectID, i, metaData[i].GetType().ToString(), metaData[i].TraceString()); + } } } @@ -3808,7 +3808,6 @@ private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, b bool processFinallyBlock = true; try { - Task reconnectTask = _activeConnection.ValidateAndReconnect(null, timeout); if (reconnectTask != null) @@ -3863,7 +3862,6 @@ private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, b // no parameters are sent over // no data reader is returned // use this overload for "batch SQL" tds token type - if (SqlClientEventSource.Log.IsTraceEnabled()) { SqlClientEventSource.Log.Trace(" {0}#, Command executed as SQLBATCH.", ObjectID); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs index 3526f05887..df922d3470 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs @@ -28,8 +28,6 @@ namespace Microsoft.Data.SqlClient // This is accomplished by having no public override constructors. internal sealed class SqlDataReaderSmi : SqlDataReader { - - // // IDBRecord properties // @@ -1343,8 +1341,6 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, md.Length={1} nextEventIsRow={2}.", reader.ObjectID, mdLength, nextEventIsRow); - - if (null != md) { for (int i = 0; i < md.Length; i++) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index aa578c9394..6facbfa35a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -590,26 +590,18 @@ private void EnlistNonNull(SysTx.Transaction tx) // send cookie to server to finish enlistment PropagateTransactionCookie(cookie); - _isEnlistedInTransaction = true; - long transactionId = SqlInternalTransaction.NullTransactionId; - int transactionObjectID = 0; - if (null != CurrentTransaction) - { - transactionId = CurrentTransaction.TransactionId; - transactionObjectID = CurrentTransaction.ObjectID; - } - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { + long transactionId = null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId; + int transactionObjectID = null != CurrentTransaction ? CurrentTransaction.ObjectID : 0; SqlClientEventSource.Log.Trace(" {0}#, enlisted with transaction {1}# with transactionId=0x{2}", ObjectID, transactionObjectID, transactionId); } } EnlistedTransaction = tx; // Tell the base class about our enlistment - // If we're on a Yukon or newer server, and we we delegate the // transaction successfully, we will have done a begin transaction, // which produces a transaction id that we should execute all requests diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs index 1a49a86695..b97dc0057f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs @@ -411,12 +411,10 @@ override internal void ExecuteTransaction( SqlInternalTransaction internalTransaction, bool isDelegateControlRequest) { - var transactionNameValue = (null != transactionName) ? transactionName : "null"; - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, transactionRequest={1}, " + - "transactionName='{2}', isolationLevel={3}, internalTransaction=#{4} transactionId=0x{5}.", ObjectID, transactionRequest.ToString(), transactionNameValue, iso.ToString(), (null != internalTransaction) ? internalTransaction.ObjectID : 0, (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); + "transactionName='{2}', isolationLevel={3}, internalTransaction=#{4} transactionId=0x{5}.", ObjectID, transactionRequest.ToString(), transactionName ?? "null", iso.ToString(), (null != internalTransaction) ? internalTransaction.ObjectID : 0, (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); } switch (transactionRequest) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs index 63d13fbfb3..00fc01bbd3 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs @@ -516,7 +516,7 @@ internal SqlInternalConnectionTds( ThreadHasParserLockForClose = false; _parserLock.Release(); } - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, constructed new TDS internal connection", ObjectID); } @@ -774,7 +774,7 @@ override protected void ChangeDatabaseInternal(string database) override public void Dispose() { - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}# disposing", ObjectID); } @@ -1420,7 +1420,7 @@ private void CompleteLogin(bool enlistOK) _fConnectionOpen = true; // mark connection as open - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" Post-Login Phase: Server connection obtained."); } @@ -1681,7 +1681,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt int routingAttempts = 0; ServerInfo originalServerInfo = serverInfo; // serverInfo may end up pointing to new object due to routing, original object is used to set CurrentDatasource - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, host={1}", ObjectID, serverInfo.UserServerName); } @@ -1882,7 +1882,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt // Sleep for a bit to prevent clogging the network with requests, // then update sleep interval for next iteration (max 1 second interval) - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, sleeping {1}[milisec]", ObjectID, sleepInterval); } @@ -1968,7 +1968,7 @@ TimeoutTimer timeout Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used"); - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, useFailover={1}[bool], primary={2}, failover={failoverHost}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName); } @@ -2039,7 +2039,7 @@ TimeoutTimer timeout // Primary server may give us a different failover partner than the connection string indicates. Update it if (null != ServerProvidedFailOverPartner && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) { - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); } @@ -2147,7 +2147,7 @@ TimeoutTimer timeout // the network with requests, then update sleep interval for next iteration (max 1 second interval) if (1 == attemptNumber % 2) { - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, sleeping {1}[milisec]", ObjectID, sleepInterval); } @@ -2226,7 +2226,7 @@ private void ResolveExtendedServerName(ServerInfo serverInfo, bool aliasLookup, // Common code path for making one attempt to establish a connection and log in to server. private void AttemptOneLogin(ServerInfo serverInfo, string newPassword, SecureString newSecurePassword, bool ignoreSniOpenTimeout, TimeoutTimer timeout, bool withFailover = false, bool isFirstTransparentAttempt = true, bool disableTnir = false) { - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); } @@ -2870,7 +2870,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) throw exc; } - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); SqlClientEventSource.Log.Trace(" {0}#, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index 406ca3582f..1481862733 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -427,7 +427,7 @@ private bool IncludeTraceHeader { get { - return (_isDenali); + return (_isDenali && SqlClientEventSource.Log.IsEnabled()); } } @@ -608,12 +608,12 @@ internal void Connect(ServerInfo serverInfo, UInt32 result = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId); Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); + // UNDONE - send "" for instance now, need to fix later if (SqlClientEventSource.Log.IsTraceEnabled()) { SqlClientEventSource.Log.Trace(" Sending prelogin handshake"); } - // UNDONE - send "" for instance now, need to fix later SendPreLoginHandshake(instanceName, encrypt, !string.IsNullOrEmpty(certificate), useOriginalAddressInfo); _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake); @@ -772,7 +772,7 @@ internal TdsParserStateObject CreateSession() { TdsParserStateObject session = new TdsParserStateObject(this, (SNIHandle)_pMarsPhysicalConObj.Handle, true); - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}# created session {1}", ObjectID, session.ObjectID); } @@ -791,7 +791,7 @@ internal TdsParserStateObject GetSession(object owner) session = _sessionPool.GetSession(owner); Debug.Assert(!session._pendingData, "pending data on a pooled MARS session"); - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}# getting session {1} from pool", ObjectID, session.ObjectID); } @@ -800,7 +800,7 @@ internal TdsParserStateObject GetSession(object owner) { session = _physicalStateObj; - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}# getting physical session {1}", ObjectID, session.ObjectID); } @@ -1377,10 +1377,12 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod internal void Deactivate(bool connectionIsDoomed) { // Called when the connection that owns us is deactivated. - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}# deactivating", ObjectID); - + } + if (SqlClientEventSource.Log.IsStateDumpEnabled()) + { SqlClientEventSource.Log.Trace(" {0}#, {1}", ObjectID, TraceString()); } @@ -4030,7 +4032,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, SqlFedAuthInfo tempFedAuthInfo = new SqlFedAuthInfo(); // Skip reading token length, since it has already been read in caller - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" FEDAUTHINFO token stream length = {0}", tokenLen); } @@ -4038,7 +4040,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, if (tokenLen < sizeof(uint)) { // the token must at least contain a DWORD indicating the number of info IDs - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); } @@ -4057,7 +4059,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); } @@ -4161,7 +4163,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, tempFedAuthInfo.stsurl = data; break; default: - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" Ignoring unknown federated authentication info option: {0}", id); } @@ -8889,7 +8891,7 @@ internal void TdsLogin(SqlLogin rec, WriteInt(log7Flags, _physicalStateObj); - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, TDS Login7 flags = {1}:", ObjectID, log7Flags); } @@ -10619,7 +10621,7 @@ private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefa var sendDefaultValue = sendDefault ? 1 : 0; - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index 4efedb246a..73b11e1f3d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -918,14 +918,14 @@ internal int DecrementPendingCallbacks(bool release) { int remaining = Interlocked.Decrement(ref _pendingCallbacks); - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); } if ((0 == remaining || release) && _gcHandle.IsAllocated) { - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, FREEING HANDLE!", ObjectID); } @@ -1037,7 +1037,7 @@ internal int IncrementPendingCallbacks() { int remaining = Interlocked.Increment(ref _pendingCallbacks); - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); } @@ -3770,7 +3770,11 @@ private void SniWriteStatisticsAndTracing() _traceChangePasswordOffset = 0; _traceChangePasswordLength = 0; } - SqlClientEventSource.Log.TraceBin(" Packet sent", _outBuff, (UInt16)_outBytesUsed); + + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + SqlClientEventSource.Log.TraceBin(" Packet sent", _outBuff, (ushort)_outBytesUsed); + } } [Conditional("DEBUG")] diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs index 7a48f59874..641ae836f5 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs @@ -718,7 +718,7 @@ Int64 allocationSize UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode); try { - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { SqlClientEventSource.Log.Trace(" {0}#, desiredAccess=0x{1}, allocationSize={2}, " + "fileAttributes=0x{3}, shareAccess=0x{4}, dwCreateDisposition=0x{5}, createOptions=0x{ dwCreateOptions}", ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition); From 11b90fc0a5da60ef43227cee0ef4878c292265b2 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Thu, 13 Feb 2020 15:18:27 -0800 Subject: [PATCH 30/46] StateDump --- .../src/Microsoft/Data/SqlClient/SqlClientEventSource.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 5cb18b9ee1..c986772b69 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -46,7 +46,9 @@ internal class Keywords internal const EventKeywords PoolerTrace = (EventKeywords)128; - internal const EventKeywords Advanced = (EventKeywords)512; + internal const EventKeywords Advanced = (EventKeywords)256; + + internal const EventKeywords StateDump = (EventKeywords)512; } #endregion @@ -77,6 +79,9 @@ internal class Keywords [NonEvent] internal bool IsAdvanceTraceOn() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Advanced); + + [NonEvent] + internal bool IsStateDumpEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.StateDump); #endregion #region overloads From 71fee3dca5cbf520c8d1f657d6c1ba57b47f0c70 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Wed, 19 Feb 2020 09:45:49 -0800 Subject: [PATCH 31/46] Removing if statement from code and placing them inside EventSource --- .../src/Microsoft/Data/Common/AdapterUtil.cs | 2 +- .../Data/Common/DBConnectionString.cs | 10 +- .../Data/Common/DbConnectionOptions.cs | 7 +- .../netfx/src/Microsoft/Data/DataException.cs | 22 +- .../Data/ProviderBase/DbConnectionFactory.cs | 75 +--- .../Data/ProviderBase/DbConnectionInternal.cs | 85 +--- .../Data/ProviderBase/DbConnectionPool.cs | 311 +++----------- .../ProviderBase/DbConnectionPoolGroup.cs | 18 +- .../Data/ProviderBase/SqlConnectionHelper.cs | 47 +-- .../Microsoft/Data/SqlClient/LocalDBAPI.cs | 35 +- .../SqlClient/Server/SmiEventSink_Default.cs | 6 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 23 +- .../Data/SqlClient/SqlClientEventSource.cs | 301 ++++++++++---- .../Data/SqlClient/SqlClientLogger.cs | 10 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 279 +++---------- .../Microsoft/Data/SqlClient/SqlCommandSet.cs | 24 +- .../Microsoft/Data/SqlClient/SqlConnection.cs | 142 ++----- .../Data/SqlClient/SqlConnectionFactory.cs | 6 +- .../SqlConnectionPoolGroupProviderInfo.cs | 11 +- .../Data/SqlClient/SqlDataAdapter.cs | 15 +- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 64 +-- .../Data/SqlClient/SqlDataReaderSmi.cs | 60 +-- .../Data/SqlClient/SqlDelegatedTransaction.cs | 41 +- .../Microsoft/Data/SqlClient/SqlDependency.cs | 320 +++----------- .../Data/SqlClient/SqlDependencyListener.cs | 392 +++--------------- .../Data/SqlClient/SqlDependencyUtils.cs | 178 ++------ .../src/Microsoft/Data/SqlClient/SqlError.cs | 5 +- .../Data/SqlClient/SqlInternalConnection.cs | 50 +-- .../SqlClient/SqlInternalConnectionSmi.cs | 124 ++---- .../SqlClient/SqlInternalConnectionTds.cs | 268 +++--------- .../Data/SqlClient/SqlTransaction.cs | 53 +-- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 274 +++--------- .../Data/SqlClient/TdsParserSessionPool.cs | 51 +-- .../Data/SqlClient/TdsParserStateObject.cs | 81 +--- .../Data/SqlClient/sqlinternaltransaction.cs | 38 +- .../Microsoft/Data/SqlTypes/SqlFileStream.cs | 14 +- 36 files changed, 843 insertions(+), 2599 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index 0ae2035649..6921eb18d2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -102,7 +102,7 @@ static private void TraceException( Debug.Assert(null != e, "TraceException: null Exception"); if (null != e && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace(trace, e.ToString()); // will include callstack if permission is available + SqlClientEventSource.Log.TraceEvent(trace, e.ToString()); // will include callstack if permission is available } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs index f864c563f7..df45de05c9 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs @@ -470,10 +470,7 @@ static private string[] NoDuplicateUnion(string[] a, string[] b) private static string[] ParseRestrictions(string restrictions, Hashtable synonyms) { #if DEBUG - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" Restrictions='{0}'",restrictions); - } + SqlClientEventSource.Log.AdvanceTrace(" Restrictions='{0}'", restrictions); #endif List restrictionValues = new List(); StringBuilder buffer = new StringBuilder(restrictions.Length); @@ -489,10 +486,7 @@ private static string[] ParseRestrictions(string restrictions, Hashtable synonym if (!ADP.IsEmpty(keyname)) { #if DEBUG - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" KeyName='{0}'",keyname); - } + SqlClientEventSource.Log.AdvanceTrace(" KeyName='{0}'", keyname); #endif string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144 if (ADP.IsEmpty(realkeyname)) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs index 6d73e0a9c3..62510f14ab 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs @@ -633,14 +633,15 @@ private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hash string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) - { // don't trace passwords ever! + { + // don't trace passwords ever! if (null != keyvalue) { - SqlClientEventSource.Log.Trace(" KeyName='{0}', KeyValue='{1}'", keyname, keyvalue); + SqlClientEventSource.Log.AdvanceTrace(" KeyName='{0}', KeyValue='{1}'", keyname, keyvalue); } else { - SqlClientEventSource.Log.Trace(" KeyName='{0}'", keyname); + SqlClientEventSource.Log.AdvanceTrace(" KeyName='{0}'", keyname); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs index 6f5fa6007b..82665dd592 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -26,21 +26,17 @@ static private void TraceException( string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e && SqlClientEventSource.Log.IsAdvanceTraceOn()) + if (null != e) { - SqlClientEventSource.Log.Trace(e.Message); - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + SqlClientEventSource.Log.AdvanceTrace(e.Message); + try + { + SqlClientEventSource.Log.AdvanceTrace(", StackTrace='{0}'", Environment.StackTrace); + } + catch (System.Security.SecurityException) { - try - { - SqlClientEventSource.Log.Trace(", StackTrace='{0}'", Environment.StackTrace); - } - catch (System.Security.SecurityException) - { - // if you don't have permission - you don't get the stack trace - SqlClientEventSource.Log.Trace("Permission Denied"); - } + // if you don't have permission - you don't get the stack trace + SqlClientEventSource.Log.AdvanceTrace("Permission Denied"); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index 3d7ddbc0f1..27c589c2ed 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -65,12 +65,7 @@ internal int ObjectID public void ClearAllPools() { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(""); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent("", "API"); try { Dictionary connectionPoolGroups = _connectionPoolGroups; @@ -92,13 +87,7 @@ public void ClearAllPools() public void ClearPool(DbConnection connection) { ADP.CheckArgumentNull(connection, "connection"); - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", GetObjectId(connection)); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", GetObjectId(connection)); try { DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); @@ -117,12 +106,7 @@ public void ClearPool(DbConnectionPoolKey key) { Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, "key.ConnectionString"); - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" connectionString"); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" connectionString", "API"); try { @@ -167,10 +151,7 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakeNonPooledObject(owningConnection, PerformanceCounters); } - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Non-pooled database connection created.", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Non-pooled database connection created.", ObjectID); return newConnection; } @@ -186,12 +167,7 @@ internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbCo PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakePooledConnection(pool); } - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Pooled database connection created.", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Pooled database connection created.", ObjectID); return newConnection; } @@ -386,10 +362,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour // connection creation failed on semaphore waiting or if max pool reached if (connectionPool.IsRunning) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, GetConnection failed because a pool timeout occurred.", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, GetConnection failed because a pool timeout occurred.", ObjectID); // If GetConnection failed while the pool is running, the pool timeout occurred. throw ADP.PooledOpenTimeout(); @@ -408,10 +381,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour if (connection == null) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, GetConnection failed because a pool timeout occurred and all retries were exhausted.", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, GetConnection failed because a pool timeout occurred and all retries were exhausted.", ObjectID); // exhausted all retries or timed out - give up throw ADP.PooledOpenTimeout(); @@ -438,10 +408,7 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti // however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, DisabledPoolGroup={1}#", ObjectID, connectionPoolGroup.ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, DisabledPoolGroup={1}#", ObjectID, connectionPoolGroup.ObjectID); // reusing existing pool option in case user originally used SetConnectionPoolOptions DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions; @@ -571,11 +538,8 @@ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPo private void PruneConnectionPoolGroups(object state) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - // when debugging this method, expect multiple threads at the same time - SqlClientEventSource.Log.Trace(" {0}#", ObjectID); - } + // when debugging this method, expect multiple threads at the same time + SqlClientEventSource.Log.AdvanceTrace(" {0}#", ObjectID); // First, walk the pool release list and attempt to clear each // pool, when the pool is finally empty, we dispose of it. If the @@ -595,12 +559,7 @@ private void PruneConnectionPoolGroups(object state) if (0 == pool.Count) { _poolsToRelease.Remove(pool); - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, ReleasePool={1}#", ObjectID, pool.ObjectID); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}#, ReleasePool={1}#", ObjectID, pool.ObjectID); PerformanceCounters.NumberOfInactiveConnectionPools.Decrement(); } } @@ -625,12 +584,7 @@ private void PruneConnectionPoolGroups(object state) if (0 == poolsLeft) { _poolGroupsToRelease.Remove(poolGroup); - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, ReleasePoolGroup={1}#", ObjectID, poolGroup.ObjectID); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}#, ReleasePoolGroup={1}#", ObjectID, poolGroup.ObjectID); PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Decrement(); } } @@ -696,10 +650,7 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { Debug.Assert(null != poolGroup, "null poolGroup?"); - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, poolGroup={1}#", ObjectID, poolGroup.ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, poolGroup={1}#", ObjectID, poolGroup.ObjectID); lock (_poolGroupsToRelease) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index dc4da33138..e672ed1a26 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -163,11 +163,7 @@ protected internal SysTx.Transaction EnlistedTransaction if (null != value) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Enlisting.", ObjectID, value.GetHashCode()); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Transaction {1}#, Enlisting.", ObjectID, value.GetHashCode()); TransactionOutcomeEnlist(value); } } @@ -392,11 +388,7 @@ internal void ActivateConnection(SysTx.Transaction transaction) { // Internal method called from the connection pooler so we don't expose // the Activate method publicly. - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Activating", ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Activating", ObjectID); #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); Debug.Assert(1 == activateCount, "activated multiple times?"); @@ -467,11 +459,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac //////////////////////////////////////////////////////////////// Debug.Assert(null != owningObject, "null owningObject"); Debug.Assert(null != connectionFactory, "null connectionFactory"); - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}# Closing.", ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}# Closing.", ObjectID); // if an exception occurs after the state change but before the try block // the connection will be stuck in OpenBusy state. The commented out try-catch @@ -576,10 +564,7 @@ internal void DeactivateConnection() { // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Deactivating", ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Deactivating", ObjectID); #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); Debug.Assert(0 == activateCount, "activated multiple times?"); @@ -613,11 +598,7 @@ virtual internal void DelegatedTransactionEnded() // IMPORTANT NOTE: You must have taken a lock on the object before // you call this method to prevent race conditions with Clear and // ReclaimEmancipatedObjects. - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Delegated Transaction Completed.", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Delegated Transaction Completed.", ObjectID); if (1 == _pooledCount) { @@ -680,11 +661,7 @@ public virtual void Dispose() protected internal void DoNotPoolThisConnection() { _cannotBePooled = true; - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Marking pooled object as non-poolable so it will be disposed", ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Marking pooled object as non-poolable so it will be disposed", ObjectID); } /// Ensure that this connection cannot be put back into the pool. @@ -692,11 +669,7 @@ protected internal void DoNotPoolThisConnection() protected internal void DoomThisConnection() { _connectionIsDoomed = true; - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Dooming", ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Dooming", ObjectID); } // Reset connection doomed status so it can be re-connected and pooled. @@ -830,10 +803,7 @@ internal void PrePush(object expectedOwner) } //DbConnection x = (expectedOwner as DbConnection); - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {}#, Preparing to push into pool, owning connection {0}#, pooledCount={1}", ObjectID, _pooledCount); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {}#, Preparing to push into pool, owning connection {0}#, pooledCount={1}", ObjectID, _pooledCount); _pooledCount++; _owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2% @@ -865,10 +835,7 @@ internal void PostPop(object newOwner) _pooledCount--; //DbConnection x = (newOwner as DbConnection); - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Preparing to pop from pool, owning connection {1}#, pooledCount={2}", ObjectID, 0, _pooledCount); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Preparing to pop from pool, owning connection {1}#, pooledCount={2}", ObjectID, 0, _pooledCount); //3 // The following tests are retail assertions of things we can't allow to happen. if (null != Pool) @@ -925,10 +892,7 @@ internal void DetachCurrentTransactionIfEnded() // Detach transaction from connection. internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Transaction Completed. (pooledCount={1})", ObjectID, _pooledCount); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Transaction Completed. (pooledCount={1})", ObjectID, _pooledCount); // potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new // transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should @@ -969,14 +933,9 @@ internal void CleanupConnectionOnTransactionCompletion(SysTx.Transaction transac void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) { SysTx.Transaction transaction = e.Transaction; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); CleanupTransactionOnCompletion(transaction); - CleanupConnectionOnTransactionCompletion(transaction); } @@ -991,27 +950,19 @@ private void TransactionOutcomeEnlist(SysTx.Transaction transaction) internal void SetInStasis() { _isInStasis = true; - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID); PerformanceCounters.NumberOfStasisConnections.Increment(); } private void TerminateStasis(bool returningToPool) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) + if (returningToPool) { - if (returningToPool) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Delegated Transaction has ended, connection is closed. Returning to general pool.", ObjectID); - } - else - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Delegated Transaction has ended, connection is closed/leaked. Disposing.", ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Delegated Transaction has ended, connection is closed. Returning to general pool.", ObjectID); + } + else + { + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Delegated Transaction has ended, connection is closed/leaked. Disposing.", ObjectID); } PerformanceCounters.NumberOfStasisConnections.Decrement(); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index 96ca456a34..f9d35dff1d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -79,14 +79,9 @@ sealed private class TransactedConnectionPool internal TransactedConnectionPool(DbConnectionPool pool) { Debug.Assert(null != pool, "null pool?"); - _pool = pool; _transactedCxns = new Dictionary(); - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Constructed for connection pool {1}#", ObjectID, _pool.ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Constructed for connection pool {1}#", ObjectID, _pool.ObjectID); } internal int ObjectID @@ -143,9 +138,9 @@ internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction) } } - if (null != transactedObject && SqlClientEventSource.Log.IsPoolerTraceEnabled()) + if (null != transactedObject) { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } return transactedObject; } @@ -172,12 +167,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); connections.Add(transactedObject); } } @@ -212,21 +202,13 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); connections.Add(transactedObject); } } else { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Adding List to transacted pool.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Adding List to transacted pool.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); // add the connection/transacted object to the list newConnections.Add(transactedObject); @@ -254,11 +236,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt } } } - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Added.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Added.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } Pool.PerformanceCounters.NumberOfFreeConnections.Increment(); @@ -267,11 +245,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionInternal transactedObject) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); TransactedConnectionList connections; int entry = -1; @@ -305,10 +279,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern // safely remove the list from the transacted pool. if (0 >= connections.Count) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Removing List from transacted pool.", ObjectID, transaction.GetHashCode()); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Transaction {1}#, Removing List from transacted pool.", ObjectID, transaction.GetHashCode()); _transactedCxns.Remove(transaction); // we really need to dispose our connection list; it may have @@ -325,10 +296,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern else { //Debug.Assert ( false, "TransactionCompletedEvent fired before PutTransactedObject put the connection in the transacted pool." ); - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Transacted pool not yet created prior to transaction completing. Connection may be leaked.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Transacted pool not yet created prior to transaction completing. Connection may be leaked.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } } @@ -555,11 +523,7 @@ internal DbConnectionPool( _poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback _state = State.Running; - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Constructed.", ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Constructed.", ObjectID); //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls // StartBackgroundCallbacks after pool is actually in the collection @@ -707,11 +671,7 @@ private void CleanupCallback(Object state) // // With this logic, objects are pruned from the pool if unused for // at least one period but not more than two periods. - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#", ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#", ObjectID); // Destroy free objects that put us above MinPoolSize from old stack. while (Count > MinPoolSize) @@ -785,12 +745,7 @@ private void CleanupCallback(Object state) break; Debug.Assert(obj != null, "null connection is not expected"); - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, ChangeStacks={1}#", ObjectID, obj.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, ChangeStacks={1}#", ObjectID, obj.ObjectID); Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); Debug.Assert(obj.CanBePooled, "pooled object is not poolable"); @@ -805,11 +760,7 @@ private void CleanupCallback(Object state) internal void Clear() { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Clearing.", ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Clearing.", ObjectID); DbConnectionInternal obj; // First, quickly doom everything. @@ -845,11 +796,7 @@ internal void Clear() // Finally, reclaim everything that's emancipated (which, because // it's been doomed, will cause it to be disposed of as well) ReclaimEmancipatedObjects(); - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Cleared.", ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Cleared.", ObjectID); } private Timer CreateCleanupTimer() @@ -939,11 +886,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio } } } - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Added to pool.", ObjectID, newObj.ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Added to pool.", ObjectID, newObj.ObjectID); // Reset the error wait: _errorWait = ERROR_WAIT_DEFAULT; @@ -1004,11 +947,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio private void DeactivateObject(DbConnectionInternal obj) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Deactivating.", ObjectID, obj.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Deactivating.", ObjectID, obj.ObjectID); obj.DeactivateConnection(); // we presume this operation is safe outside of a lock... bool returnToGeneralPool = false; @@ -1148,18 +1087,11 @@ internal void DestroyObject(DbConnectionInternal obj) // again. if (obj.IsTxRootWaitingForTxEnd) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Has Delegated Transaction, waiting to Dispose.", ObjectID, obj.ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Has Delegated Transaction, waiting to Dispose.", ObjectID, obj.ObjectID); } else { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Removing from pool.", ObjectID, obj.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Removing from pool.", ObjectID, obj.ObjectID); bool removed = false; lock (_objectList) { @@ -1170,32 +1102,18 @@ internal void DestroyObject(DbConnectionInternal obj) if (removed) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Removed from pool.", ObjectID, obj.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Removed from pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfPooledConnections.Decrement(); } - obj.Dispose(); - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Disposed.", ObjectID, obj.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Disposed.", ObjectID, obj.ObjectID); PerformanceCounters.HardDisconnectsPerSecond.Increment(); } } private void ErrorCallback(Object state) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Resetting Error handling.", ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Resetting Error handling.", ObjectID); _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); @@ -1369,11 +1287,7 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource {0}#, DbConnectionInternal State != Running.", ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, DbConnectionInternal State != Running.", ObjectID); connection = null; return true; } @@ -1418,11 +1332,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj SysTx.Transaction transaction = null; PerformanceCounters.SoftConnectsPerSecond.Increment(); - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Getting connection.", ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Getting connection.", ObjectID); // If automatic transaction enlistment is required, then we try to // get the connection from the transacted connection pool first. @@ -1475,33 +1385,20 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj switch (waitResult) { case WAIT_TIMEOUT: - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Wait timed out.", ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Wait timed out.", ObjectID); Interlocked.Decrement(ref _waitCount); connection = null; return false; case ERROR_HANDLE: - // Throw the error that PoolCreateRequest stashed. - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Errors are set.", ObjectID); - } + // Throw the error that PoolCreateRequest stashed. + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Errors are set.", ObjectID); Interlocked.Decrement(ref _waitCount); throw TryCloneCachedException(); case CREATION_HANDLE: - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Creating new connection.", ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Creating new connection.", ObjectID); try { obj = UserCreateRequest(owningObject, userOptions); @@ -1554,11 +1451,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj if ((obj != null) && (!obj.IsConnectionAlive())) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, found dead and removed.", ObjectID, obj.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); obj = null; // Setting to null in case creating a new object fails @@ -1569,11 +1462,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj RuntimeHelpers.PrepareConstrainedRegions(); try { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Creating new connection.", ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Creating new connection.", ObjectID); obj = UserCreateRequest(owningObject, userOptions); } finally @@ -1584,11 +1473,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj else { // Timeout waiting for creation semaphore - return null - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Wait timed out.", ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Wait timed out.", ObjectID); connection = null; return false; } @@ -1598,49 +1483,28 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case WAIT_FAILED: Debug.Assert(waitForMultipleObjectsExHR != 0, "WaitForMultipleObjectsEx failed but waitForMultipleObjectsExHR remained 0"); - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Wait failed.", ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Wait failed.", ObjectID); Interlocked.Decrement(ref _waitCount); Marshal.ThrowExceptionForHR(waitForMultipleObjectsExHR); goto default; // if ThrowExceptionForHR didn't throw for some reason - case (WAIT_ABANDONED + SEMAPHORE_HANDLE): - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Semaphore handle abandonded.", ObjectID); - } + case (WAIT_ABANDONED + SEMAPHORE_HANDLE): + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Semaphore handle abandonded.", ObjectID); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(SEMAPHORE_HANDLE, _waitHandles.PoolSemaphore); - case (WAIT_ABANDONED + ERROR_HANDLE): - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Error handle abandonded.", ObjectID); - } + case (WAIT_ABANDONED + ERROR_HANDLE): + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Error handle abandonded.", ObjectID); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(ERROR_HANDLE, _waitHandles.ErrorEvent); - case (WAIT_ABANDONED + CREATION_HANDLE): - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Creation handle abandoned.", ObjectID); - } + case (WAIT_ABANDONED + CREATION_HANDLE): + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Creation handle abandoned.", ObjectID); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(CREATION_HANDLE, _waitHandles.CreationSemaphore); - default: - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, WaitForMultipleObjects={1}", ObjectID, waitResult); - } + default: + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, WaitForMultipleObjects={1}", ObjectID, waitResult); Interlocked.Decrement(ref _waitCount); throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult); } @@ -1705,12 +1569,7 @@ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal o internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) { PerformanceCounters.SoftConnectsPerSecond.Increment(); - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, replacing connection.", ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, replacing connection.", ObjectID); DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); if (newConnection != null) @@ -1752,11 +1611,7 @@ private DbConnectionInternal GetFromGeneralPool() if (null != obj) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Popped from general pool.", ObjectID, obj.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Popped from general pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfFreeConnections.Decrement(); } return (obj); @@ -1773,11 +1628,7 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac if (null != obj) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Popped from transacted pool.", ObjectID, obj.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Popped from transacted pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfFreeConnections.Decrement(); if (obj.IsTransactionRoot) @@ -1788,22 +1639,14 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac } catch { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, found dead and removed.", ObjectID, obj.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); throw; } } else if (!obj.IsConnectionAlive()) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, found dead and removed.", ObjectID, obj.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); obj = null; } @@ -1818,13 +1661,7 @@ private void PoolCreateRequest(object state) { // called by pooler to ensure pool requests are currently being satisfied - // creation mutex has not been obtained - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.PoolerScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.PoolerScopeEnterEvent(" {0}#", ObjectID); try { if (State.Running == _state) @@ -1909,10 +1746,7 @@ private void PoolCreateRequest(object state) else { // trace waitResult and ignore the failure - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, PoolCreateRequest called WaitForSingleObject failed {1}", ObjectID, waitResult); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, PoolCreateRequest called WaitForSingleObject failed {1}", ObjectID, waitResult); } } catch (Exception e) @@ -1926,10 +1760,7 @@ private void PoolCreateRequest(object state) // Now that CreateObject can throw, we need to catch the exception and discard it. // There is no further action we can take beyond tracing. The error will be // thrown to the user the next time they request a connection. - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, PoolCreateRequest called CreateConnection which threw an exception: {1}", ObjectID, e); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, PoolCreateRequest called CreateConnection which threw an exception: {1}", ObjectID, e); } finally { @@ -1962,11 +1793,7 @@ internal void PutNewObject(DbConnectionInternal obj) // causes the following assert to fire, which really mucks up stress // against checked bits. // Debug.Assert(obj.CanBePooled, "non-poolable object in pool"); - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Pushing to general pool.", ObjectID, obj.ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Pushing to general pool.", ObjectID, obj.ObjectID); _stackNew.Push(obj); _waitHandles.PoolSemaphore.Release(1); @@ -2015,11 +1842,7 @@ internal void PutObjectFromTransactedPool(DbConnectionInternal obj) // method, we can safely presume that the caller is the only person // that is using the connection, and that all pre-push logic has been // done and all transactions are ended. - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Transaction has ended.", ObjectID, obj.ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Transaction has ended.", ObjectID, obj.ObjectID); if (_state == State.Running && obj.CanBePooled) { @@ -2044,12 +1867,7 @@ private void QueuePoolCreateRequest() private bool ReclaimEmancipatedObjects() { bool emancipatedObjectFound = false; - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#", ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#", ObjectID); List reclaimedObjects = new List(); int count; @@ -2101,12 +1919,7 @@ private bool ReclaimEmancipatedObjects() for (int i = 0; i < count; ++i) { DbConnectionInternal obj = reclaimedObjects[i]; - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Connection {1}#, Reclaiming.", ObjectID, obj.ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Reclaiming.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfReclaimedConnections.Increment(); emancipatedObjectFound = true; @@ -2119,12 +1932,9 @@ private bool ReclaimEmancipatedObjects() internal void Startup() { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, CleanupWait={1}", ObjectID, _cleanupWait); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, CleanupWait={1}", ObjectID, _cleanupWait); _cleanupTimer = CreateCleanupTimer(); + if (NeedToReplenish) { QueuePoolCreateRequest(); @@ -2133,11 +1943,7 @@ internal void Startup() internal void Shutdown() { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#", ObjectID); - } - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#", ObjectID); _state = State.ShuttingDown; // deactivate timer callbacks @@ -2157,12 +1963,9 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern { Debug.Assert(null != transaction, "null transaction?"); Debug.Assert(null != transactedObject, "null transactedObject?"); - // Note: connection may still be associated with transaction due to Explicit Unbinding requirement. - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Transaction {1}#, Connection {2}#, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); - } + // Note: connection may still be associated with transaction due to Explicit Unbinding requirement. + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); // called by the internal connection when it get's told that the // transaction is completed. We tell the transacted pool to remove diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs index 8511aab5eb..89f6b04ec3 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -273,11 +273,7 @@ private bool MarkPoolGroupAsActive() if (PoolGroupStateIdle == _state) { _state = PoolGroupStateActive; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Active", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Active", ObjectID); } return (PoolGroupStateActive == _state); } @@ -339,20 +335,12 @@ internal bool Prune() if (PoolGroupStateActive == _state) { _state = PoolGroupStateIdle; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Idle", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Idle", ObjectID); } else if (PoolGroupStateIdle == _state) { _state = PoolGroupStateDisabled; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Disabled", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Disabled", ObjectID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs index 2c5197a236..0b0f5b8ef8 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs @@ -87,11 +87,7 @@ internal DbConnectionOptions ConnectionOptions private string ConnectionString_Get() { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions connectionOptions = UserConnectionOptions; return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); @@ -136,11 +132,7 @@ private void ConnectionString_Set(DbConnectionPoolKey key) } string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, '{1}'", ObjectID, cstr); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, '{1}'", ObjectID, cstr); } internal DbConnectionInternal InnerConnection @@ -188,16 +180,13 @@ internal void Abort(Exception e) // NOTE: we put the tracing last, because the ToString() calls (and // the SqlClientEventSource.SqlClientEventSource.Log.Trace, for that matter) have no reliability contract and // will end the reliable try... - if (SqlClientEventSource.Log.IsTraceEnabled()) + if (e is OutOfMemoryException) { - if (e is OutOfMemoryException) - { - SqlClientEventSource.Log.Trace(" {0}#, Aborting operation due to asynchronous exception: {'OutOfMemory'}", ObjectID); - } - else - { - SqlClientEventSource.Log.Trace(" {0}#, Aborting operation due to asynchronous exception: {1}", ObjectID, e.ToString()); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Aborting operation due to asynchronous exception: {'OutOfMemory'}", ObjectID); + } + else + { + SqlClientEventSource.Log.TraceEvent(" {0}#, Aborting operation due to asynchronous exception: {1}", ObjectID, e.ToString()); } } @@ -210,13 +199,7 @@ internal void AddWeakReference(object value, int tag) override protected DbCommand CreateDbCommand() { DbCommand command = null; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); try { DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; @@ -262,11 +245,7 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)); permissionSet.Demand(); - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Connection enlisting in a transaction.", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection enlisting in a transaction.", ObjectID); SysTx.Transaction indigoTransaction = null; if (null != transaction) @@ -291,11 +270,7 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans override public void EnlistTransaction(SysTx.Transaction transaction) { SqlConnection.ExecutePermission.Demand(); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Connection enlisting in a transaction.", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection enlisting in a transaction.", ObjectID); // If we're currently enlisted in a transaction and we were called // on the EnlistTransaction method (Whidbey) we're not allowed to diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs index ddf5925e9a..8a31f2f2df 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs @@ -73,10 +73,7 @@ static IntPtr UserInstanceDLLHandle SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle); if (s_userInstanceDLLHandle != IntPtr.Zero) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" LocalDB - handle obtained"); - } + SqlClientEventSource.Log.TraceEvent(" LocalDB - handle obtained"); } else { @@ -120,12 +117,7 @@ static LocalDBCreateInstanceDelegate LocalDBCreateInstance if (functionAddr == IntPtr.Zero) { int hResult = Marshal.GetLastWin32Error(); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" GetProcAddress for LocalDBCreateInstance error 0x{0}", hResult); - } - + SqlClientEventSource.Log.TraceEvent(" GetProcAddress for LocalDBCreateInstance error 0x{0}", hResult); throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); } s_localDBCreateInstance = (LocalDBCreateInstanceDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBCreateInstanceDelegate)); @@ -167,12 +159,7 @@ static LocalDBFormatMessageDelegate LocalDBFormatMessage { // SNI checks for LocalDBFormatMessage during DLL loading, so it is practically impossibe to get this error. int hResult = Marshal.GetLastWin32Error(); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); - } - + SqlClientEventSource.Log.TraceEvent(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); } s_localDBFormatMessage = (LocalDBFormatMessageDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBFormatMessageDelegate)); @@ -328,10 +315,7 @@ internal static void CreateLocalDBInstance(string instance) } else { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" No system.data.localdb section found in configuration"); - } + SqlClientEventSource.Log.TraceEvent(" No system.data.localdb section found in configuration"); } s_configurableInstances = tempConfigurableInstances; } @@ -358,21 +342,14 @@ internal static void CreateLocalDBInstance(string instance) // LocalDBCreateInstance is thread- and cross-process safe method, it is OK to call from two threads simultaneously int hr = LocalDBCreateInstance(instanceInfo.version, instance, flags: 0); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Starting creation of instance {0} version {1}", instance, instanceInfo.version); - } + SqlClientEventSource.Log.TraceEvent(" Starting creation of instance {0} version {1}", instance, instanceInfo.version); if (hr < 0) { throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_CreateFailed"), instance: instance, localDbError: hr); } - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Finished creation of instance {0}", instance); - } + SqlClientEventSource.Log.TraceEvent(" Finished creation of instance {0}", instance); instanceInfo.created = true; // mark instance as created } // CreateLocalDbInstance } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs index a6f8e8d78e..dd3b6a807b 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs @@ -267,11 +267,7 @@ internal override void MessagePosted(int number, byte state, byte errorClass, st { if (null == _parent) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, number={1} state={2} errorClass={3} server='{4}' message='{5}' procedure='{6}' linenumber={7}.", 0, number, state, errorClass, server ?? "", message ?? "", procedure ?? "", lineNumber); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}#, number={1} state={2} errorClass={3} server='{4}' message='{5}' procedure='{6}' linenumber={7}.", 0, number, state, errorClass, server ?? "", message ?? "", procedure ?? "", lineNumber); SqlError error = new SqlError(number, state, errorClass, server, message, procedure, lineNumber); if (error.Class < TdsEnums.MIN_ERROR_CLASS) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index 95b1f8d2f1..9d96412ca1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs @@ -594,17 +594,8 @@ private string CreateInitialQuery() private Task CreateAndExecuteInitialQueryAsync(out BulkCopySimpleResultSet result) { string TDSCommand = CreateInitialQuery(); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Initial Query: '{0}'", TDSCommand); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } - + SqlClientEventSource.Log.TraceEvent(" Initial Query: '{0}'", TDSCommand); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); if (executeTask == null) @@ -894,9 +885,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i // private Task SubmitUpdateBulkCommand(string TDSCommand) { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); if (executeTask == null) @@ -2526,11 +2515,7 @@ private void CheckAndRaiseNotification() // it's also the user's chance to cause an exception ... _stateObj.BcpLock = true; abortOperation = FireRowsCopiedEvent(_rowsCopied); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(""); - } + SqlClientEventSource.Log.TraceEvent("", "INFO"); // just in case some pathological person closes the target connection ... if (ConnectionState.Open != _connection.State) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index c986772b69..57c6ee9904 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -14,6 +14,7 @@ internal class SqlClientEventSource : EventSource internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); private static long s_nextScopeId = 0; private static long s_nextNotificationScopeId = 0; + private static long s_nextPoolerScopeId = 0; private const int TraceEventId = 1; private const int EnterScopeId = 2; @@ -85,17 +86,27 @@ internal class Keywords #endregion #region overloads + //Never use event writer directly as they are not checking for enabled/disabled situations. Always use overloads. [NonEvent] - internal void Trace(string message, T0 args0) + internal void TraceEvent(string message, T0 args0) { if (Log.IsTraceEnabled()) { - Trace(string.Format(message), args0); + TraceEvent(string.Format(message), args0); } } [NonEvent] - internal void Trace(string message, T0 args0, T1 args1) + internal void TraceEvent(string message) + { + if (Log.IsTraceEnabled()) + { + Trace(message); + } + } + + [NonEvent] + internal void TraceEvent(string message, T0 args0, T1 args1) { if (Log.IsTraceEnabled()) { @@ -104,7 +115,7 @@ internal void Trace(string message, T0 args0, T1 args1) } [NonEvent] - internal void Trace(string message, T0 args0, T1 args1, T2 args2) + internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsTraceEnabled()) { @@ -113,7 +124,7 @@ internal void Trace(string message, T0 args0, T1 args1, T2 args2) } [NonEvent] - internal void Trace(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsTraceEnabled()) { @@ -122,7 +133,7 @@ internal void Trace(string message, T0 args0, T1 args1, T2 args2 } [NonEvent] - internal void Trace(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) + internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) { if (Log.IsTraceEnabled()) { @@ -131,133 +142,295 @@ internal void Trace(string message, T0 args0, T1 args1, } [NonEvent] - internal void Trace(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5, T6 args6, T7 args7) + internal void AdvanceTrace(string message) { - if (Log.IsTraceEnabled()) + if (Log.IsAdvanceTraceOn()) + { + Trace(message); + } + } + + [NonEvent] + internal void AdvanceTrace(string message, T0 args0) + { + if (Log.IsAdvanceTraceOn()) + { + Trace(string.Format(message, args0)); + } + } + + [NonEvent] + internal void AdvanceTrace(string message, T0 args0, T1 args1) + { + if (Log.IsAdvanceTraceOn()) + { + Trace(string.Format(message, args0, args1)); + } + } + + [NonEvent] + internal void AdvanceTrace(string message, T0 args0, T1 args1, T2 args2) + { + if (Log.IsAdvanceTraceOn()) + { + Trace(string.Format(message, args0, args1, args2)); + } + } + + [NonEvent] + internal void AdvanceTrace(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + if (Log.IsAdvanceTraceOn()) + { + Trace(string.Format(message, args0, args1, args2, args3)); + } + } + + [NonEvent] + internal void AdvanceTrace(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) + { + if (Log.IsAdvanceTraceOn()) + { + Trace(string.Format(message, args0, args1, args2, args3, args4, args5)); + } + } + + [NonEvent] + internal void AdvanceTrace(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5, T6 args6, T7 args7) + { + if (Log.IsAdvanceTraceOn()) { Trace(string.Format(message, args0, args1, args2, args3, args4, args5, args6, args7)); } } [NonEvent] - internal long ScopeEnter(string message, T0 args0) + internal long ScopeEnterEvent(string message, T0 args0) { - return ScopeEnter(string.Format(message, args0)); + if (Log.IsScopeEnabled()) + { + return ScopeEnter(string.Format(message, args0)); + } + return 0; } [NonEvent] - internal long ScopeEnter(string message, T0 args0, T1 args1) + internal long AdvanceScopeEnter(string message, T0 args0) { - return ScopeEnter(string.Format(message, args0, args1)); + if (IsAdvanceTraceOn()) + { + return ScopeEnter(string.Format(message, args0)); + } + return 0; } [NonEvent] - internal long ScopeEnter(string message, T0 args0, T1 args1, T2 args2) + internal long ScopeEnterEvent(string message) { - return ScopeEnter(string.Format(message, args0, args1, args2)); + if (IsScopeEnabled()) + { + return ScopeEnter(message); + } + return 0; } [NonEvent] - internal long ScopeEnter(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal long ScopeEnterEvent(string message, T0 args0, T1 args1) { - return ScopeEnter(string.Format(message, args0, args1, args2, args3)); + if (IsScopeEnabled()) + { + return ScopeEnter(string.Format(message, args0, args1)); + } + return 0; } [NonEvent] - internal long PoolerScopeEnter(string message, T0 args0) + internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) { - return PoolerScopeEnter(string.Format(message, args0)); + if (IsScopeEnabled()) + { + return ScopeEnter(string.Format(message, args0, args1, args2)); + } + return 0; } [NonEvent] - internal long NotificationsScopeEnter(string message, T0 args0) + internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { - return NotificationsScopeEnter(string.Format(message, args0)); + if (IsScopeEnabled()) + { + return ScopeEnter(string.Format(message, args0, args1, args2, args3)); + } + return 0; } [NonEvent] - internal long NotificationsScopeEnter(string message, T0 args0, T1 args1) + internal long PoolerScopeEnterEvent(string message, T0 args0) { - return NotificationsScopeEnter(string.Format(message, args0, args1)); + if (IsPoolerScopeEnabled()) + { + return PoolerScopeEnter(string.Format(message, args0)); + } + return 0; } [NonEvent] - internal long NotificationsScopeEnter(string message, T0 args0, T1 args1, T2 args2) + internal long NotificationsScopeEnterEvent(string message, T0 args0) { - return NotificationsScopeEnter(string.Format(message, args0, args1, args2)); + if (IsNotificationScopeEnabled()) + { + return NotificationsScopeEnter(string.Format(message, args0)); + } + return 0; + } + + [NonEvent] + internal long NotificationsScopeEnterEvent(string message, T0 args0, T1 args1) + { + if (IsNotificationScopeEnabled()) + { + return NotificationsScopeEnter(string.Format(message, args0, args1)); + } + return 0; } [NonEvent] - internal long NotificationsScopeEnter(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal long NotificationsScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) { - return NotificationsScopeEnter(string.Format(message, args0, args1, args2, args3)); + if (IsNotificationScopeEnabled()) + { + return NotificationsScopeEnter(string.Format(message, args0, args1, args2)); + } + return 0; } [NonEvent] - internal void PoolerTrace(string message, T0 args0) + internal long NotificationsScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { - PoolerTrace(string.Format(message, args0)); + if (IsNotificationScopeEnabled()) + { + return NotificationsScopeEnter(string.Format(message, args0, args1, args2, args3)); + } + return 0; } [NonEvent] - internal void PoolerTrace(string message, T0 args0, T1 args1) + internal void PoolerTraceEvent(string message, T0 args0) { - PoolerTrace(string.Format(message, args0, args1)); + if (IsPoolerTraceEnabled()) + { + PoolerTrace(string.Format(message, args0)); + } + } + + [NonEvent] + internal void PoolerTraceEvent(string message, T0 args0, T1 args1) + { + if (IsPoolerTraceEnabled()) + { + PoolerTrace(string.Format(message, args0, args1)); + } + } + + [NonEvent] + internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2) + { + if (IsPoolerTraceEnabled()) + { + PoolerTrace(string.Format(message, args0, args1, args2)); + } + } + + [NonEvent] + internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + if (IsPoolerTraceEnabled()) + { + PoolerTrace(string.Format(message, args0, args1, args2, args3)); + } } [NonEvent] - internal void PoolerTrace(string message, T0 args0, T1 args1, T2 args2) + internal void CorrelationTraceEvent(string message, T0 args0) { - PoolerTrace(string.Format(message, args0, args1, args2)); + if (IsCorrelationEnabled()) + { + CorrelationTrace(string.Format(message, args0)); + } } [NonEvent] - internal void PoolerTrace(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void CorrelationTraceEvent(string message, T0 args0, T1 args1) { - PoolerTrace(string.Format(message, args0, args1, args2, args3)); + if (IsCorrelationEnabled()) + { + CorrelationTrace(string.Format(message, args0, args1)); + } } [NonEvent] - internal void CorrelationTrace(string message, T0 args0) + internal void CorrelationTraceEvent(string message, T0 args0, T1 args1, T2 args2) { - CorrelationTrace(string.Format(message, args0)); + if (IsCorrelationEnabled()) + { + CorrelationTrace(string.Format(message, args0, args1, args2)); + } } [NonEvent] - internal void CorrelationTrace(string message, T0 args0, T1 args1) + internal void NotificationsTraceEvent(string message, T0 args0) { - CorrelationTrace(string.Format(message, args0, args1)); + if (IsNotificationTraceEnabled()) + { + NotificationsTrace(string.Format(message, args0)); + } } [NonEvent] - internal void CorrelationTrace(string message, T0 args0, T1 args1, T2 args2) + internal void NotificationsTraceEvent(string message, T0 args0, T1 args1) { - CorrelationTrace(string.Format(message, args0, args1, args2)); + if (IsNotificationTraceEnabled()) + { + NotificationsTrace(string.Format(message, args0, args1)); + } } [NonEvent] - internal void NotificationsTrace(string message, T0 args0) + internal void NotificationsTraceEvent(string message, T0 args0, T1 args1, T2 args2) { - NotificationsTrace(string.Format(message, args0)); + if (IsNotificationTraceEnabled()) + { + NotificationsTrace(string.Format(message, args0, args1, args2)); + } } [NonEvent] - internal void NotificationsTrace(string message, T0 args0, T1 args1) + internal void NotificationsTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { - NotificationsTrace(string.Format(message, args0, args1)); + if (IsNotificationTraceEnabled()) + { + NotificationsTrace(string.Format(message, args0, args1, args2, args3)); + } } [NonEvent] - internal void NotificationsTrace(string message, T0 args0, T1 args1, T2 args2) + internal void TraceBinEvent(string message, T0 args0, T1 args1) { - NotificationsTrace(string.Format(message, args0, args1, args2)); + if (IsTraceEnabled()) + { + TraceBin(string.Format(message, args0, args1)); + } } [NonEvent] - internal void NotificationsTrace(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void StateDumpEvent(string message, T0 args0, T1 args1) { - NotificationsTrace(string.Format(message, args0, args1, args2, args3)); + if (IsStateDumpEnabled()) + { + Trace(string.Format(message, args0, args1)); + } } + #endregion #region Events @@ -270,12 +443,8 @@ internal void Trace(string message) [Event(EnterScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] internal long ScopeEnter(string message) { - long scopeId = 0; - if (SqlClientEventSource.Log.IsEnabled()) - { - scopeId = Interlocked.Increment(ref s_nextScopeId); - WriteEvent(EnterScopeId, message); - } + long scopeId = Interlocked.Increment(ref s_nextScopeId); + WriteEvent(EnterScopeId, message); return scopeId; } @@ -289,12 +458,9 @@ internal void ScopeLeave(long scopeId) } [Event(TraceBinId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] - internal void TraceBin(string message, byte[] whereabout, int length) + internal void TraceBin(string message) { - if (SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Trace)) - { - WriteEvent(TraceBinId, message, whereabout, length); - } + WriteEvent(TraceBinId, message); } [Event(CorrelationTraceId, Level = EventLevel.Informational, Keywords = Keywords.Correlation, Opcode = EventOpcode.Start)] @@ -306,25 +472,16 @@ internal void CorrelationTrace(string message) [Event(NotificationsScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.NotificationScope)] internal long NotificationsScopeEnter(string message) { - long scopeId = 0; - if (SqlClientEventSource.Log.IsEnabled()) - { - StringBuilder MsgstrBldr = new StringBuilder(message); - scopeId = Interlocked.Increment(ref s_nextNotificationScopeId); - WriteEvent(NotificationsScopeEnterId, MsgstrBldr.Append($", Scope ID ='[{ scopeId}]'")); - } + long scopeId = Interlocked.Increment(ref s_nextNotificationScopeId); + WriteEvent(NotificationsScopeEnterId, message); return scopeId; } [Event(PoolerScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.PoolerScope)] internal long PoolerScopeEnter(string message) { - long scopeId = 0; - if (SqlClientEventSource.Log.IsEnabled()) - { - StringBuilder MsgstrBldr = new StringBuilder(message); - WriteEvent(PoolerScopeEnterId, MsgstrBldr.Append($", Scope ID ='[{ scopeId}]'")); - } + long scopeId = Interlocked.Increment(ref s_nextPoolerScopeId); + WriteEvent(PoolerScopeEnterId, message); return scopeId; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs index b8c15cf72c..ec37b8727f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs @@ -16,19 +16,13 @@ internal enum LogLevel /// public void LogInfo(string type, string method, string message) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace($"{message}"); - } + SqlClientEventSource.Log.TraceEvent("{3}", type, method, LogLevel.Info, message); } /// public void LogError(string type, string method, string message) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace($"{message}"); - } + SqlClientEventSource.Log.TraceEvent("{3}", type, method, LogLevel.Info, message); } /// diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index cdb1b3f945..1445d85e15 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -345,11 +345,7 @@ internal CommandEventSink(SqlCommand command) : base() internal override void StatementCompleted(int rowsAffected) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, rowsAffected={1}.", _command.ObjectID, rowsAffected); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}#, rowsAffected={1}.", _command.ObjectID, rowsAffected); _command.InternalRecordsAffected = rowsAffected; // UNDONE: need to fire events back to user code, but this may be called @@ -361,23 +357,20 @@ internal override void StatementCompleted(int rowsAffected) internal override void BatchCompleted() { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#.", _command.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#.", _command.ObjectID); } internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 parameterValues) { + SqlClientEventSource.Log.AdvanceTrace(" {0}# metaData.Length={1}.", _command.ObjectID, (null != metaData) ? metaData.Length : -1); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace(" {0}# metaData.Length={1}.", _command.ObjectID, (null != metaData) ? metaData.Length : -1); - if (null != metaData) { for (int i = 0; i < metaData.Length; i++) { - SqlClientEventSource.Log.Trace(" {0}#, metaData[{1}] is {2}{3}", _command.ObjectID, i, metaData[i].GetType().ToString(), metaData[i].TraceString()); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, metaData[{1}] is {2}{3}", _command.ObjectID, i, metaData[i].GetType().ToString(), metaData[i].TraceString()); } } } @@ -388,11 +381,7 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter parameterValues, int ordinal) { - if (null != metaData && SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, metaData[{1}] is {2}{ 3}", _command.ObjectID, ordinal, metaData.GetType().ToString(), metaData.TraceString()); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}#, metaData[{1}] is {2}{ 3}", _command.ObjectID, ordinal, metaData.GetType().ToString(), metaData.TraceString()); Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion); _command.OnParameterAvailableSmi(metaData, parameterValues, ordinal); } @@ -574,13 +563,8 @@ private SqlCommand(SqlCommand from) : this() } } } - _activeConnection = value; // UNDONE: Designers need this setter. Should we block other scenarios? - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, {1}#", ObjectID, (null != value) ? value.ObjectID : -1); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, {1}#", ObjectID, (null != value) ? value.ObjectID : -1); } } @@ -658,11 +642,7 @@ public SqlNotificationRequest Notification } set { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); _sqlDep = null; _notification = value; } @@ -712,10 +692,8 @@ internal SqlStatistics Statistics } // TODO: Add objid here - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); + _transaction = value; } } @@ -750,10 +728,7 @@ override public string CommandText } set { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, String Value = '{1}'", ObjectID, value); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, String Value = '{1}'", ObjectID, value); if (0 != ADP.SrcCompare(_commandText, value)) { @@ -791,11 +766,7 @@ override public int CommandTimeout } set { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, {1}", ObjectID, value); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, {1}", ObjectID, value); if (value < 0) { throw ADP.InvalidCommandTimeout(value); @@ -840,10 +811,7 @@ override public CommandType CommandType } set { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, {1}{2}", ObjectID, (int)value, _commandType); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, {1}{2}", ObjectID, (int)value, _commandType); if (_commandType != value) { switch (value) @@ -986,11 +954,7 @@ internal void OnStatementCompleted(int recordCount) { try { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, recordCount={1}", ObjectID, recordCount); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, recordCount={1}", ObjectID, recordCount); handler(this, new StatementCompletedEventArgs(recordCount)); } catch (Exception e) @@ -1028,17 +992,8 @@ override public void Prepare() } SqlStatistics statistics = null; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); statistics = SqlStatistics.StartTimer(Statistics); @@ -1204,10 +1159,7 @@ internal void Unprepare() } _cachedMetaData = null; - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Command unprepared.", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Command unprepared.", ObjectID); } // Cancel is supposed to be multi-thread safe. @@ -1217,16 +1169,8 @@ internal void Unprepare() /// override public void Cancel() { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); SqlStatistics statistics = null; try @@ -1386,22 +1330,14 @@ override public object ExecuteScalar() // Reset _pendingCancel upon entry into any Execute - used to synchronize state // between entry into Execute* API and the thread obtaining the stateObject. _pendingCancel = false; - SqlStatistics statistics = null; - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); bool success = false; int? sqlExceptionNumber = null; + try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1466,16 +1402,8 @@ override public int ExecuteNonQuery() SqlStatistics statistics = null; - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); bool success = false; int? sqlExceptionNumber = null; @@ -1512,13 +1440,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) _pendingCancel = false; SqlStatistics statistics = null; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1544,11 +1466,7 @@ public IAsyncResult BeginExecuteNonQuery() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } - + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); SqlConnection.ExecutePermission.Demand(); return BeginExecuteNonQueryInternal(0, callback, stateObject, 0, inRetry: false); } @@ -1774,10 +1692,7 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) } finally { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } } @@ -1795,11 +1710,7 @@ private void ThrowIfReconnectionHasBeenCanceled() private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } - + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2061,10 +1972,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st { // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Command executed as RPC.", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Command executed as RPC.", ObjectID); SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, methodName, completion, timeout, out task, out usedCache, asyncWrite, inRetry); if (null != reader) @@ -2118,16 +2026,8 @@ public XmlReader ExecuteXmlReader() SqlStatistics statistics = null; - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); bool success = false; int? sqlExceptionNumber = null; @@ -2168,11 +2068,7 @@ public IAsyncResult BeginExecuteXmlReader() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } - + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); SqlConnection.ExecutePermission.Demand(); return BeginExecuteXmlReaderInternal(CommandBehavior.SequentialAccess, callback, stateObject, 0, inRetry: false); } @@ -2325,20 +2221,13 @@ public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) } finally { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } } private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } - + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2457,11 +2346,7 @@ public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObjec /// override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } - + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); return ExecuteReader(behavior, ADP.ExecuteReader); } @@ -2469,17 +2354,8 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) new public SqlDataReader ExecuteReader() { SqlStatistics statistics = null; - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -2495,16 +2371,8 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) /// new public SqlDataReader ExecuteReader(CommandBehavior behavior) { - var scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - SqlClientEventSource.Log.ScopeEnter(" {0}#, behavior={1}", ObjectID, (int)behavior); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#, behavior={1}", ObjectID, (int)behavior); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); try { @@ -2527,11 +2395,7 @@ public IAsyncResult BeginExecuteReader(CommandBehavior behavior) [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior) { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); - } - + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); SqlConnection.ExecutePermission.Demand(); return BeginExecuteReaderInternal(behavior, callback, stateObject, 0, inRetry: false); } @@ -2612,20 +2476,13 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) } finally { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } } private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } - + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -3026,11 +2883,7 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string /// public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } - + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3115,11 +2968,7 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b /// new public Task ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); - } - + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3253,10 +3102,7 @@ public Task ExecuteXmlReaderAsync() /// public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken) { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3862,11 +3708,7 @@ private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, b // no parameters are sent over // no data reader is returned // use this overload for "batch SQL" tds token type - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Command executed as SQLBATCH.", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Command executed as SQLBATCH.", ObjectID); Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(this.CommandText, timeout, this.Notification, _stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -3928,10 +3770,7 @@ private void RunExecuteNonQuerySmi(bool sendToPipe) SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, innerConnection={1}#, transactionId=0x{2}, cmdBehavior={3}.", ObjectID, innerConnection.ObjectID, transactionId, (int)CommandBehavior.Default); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, innerConnection={1}#, transactionId=0x{2}, cmdBehavior={3}.", ObjectID, innerConnection.ObjectID, transactionId, (int)CommandBehavior.Default); if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { @@ -5408,9 +5247,9 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // Send over SQL Batch command if we are not a stored proc and have no parameters // MDAC BUG #'s 73776 & 72101 Debug.Assert(!IsUserPrepared, "CommandType.Text with no params should not be prepared!"); - if (returnStream && SqlClientEventSource.Log.IsTraceEnabled()) + if (returnStream) { - SqlClientEventSource.Log.Trace(" {0}#, Command executed as SQLBATCH.", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Command executed as SQLBATCH.", ObjectID); } string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior); @@ -5473,9 +5312,9 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // if shiloh, then set NOMETADATA_UNLESSCHANGED flag if (_activeConnection.IsShiloh) rpc.options = TdsEnums.RPC_NOMETADATA; - if (returnStream && SqlClientEventSource.Log.IsTraceEnabled()) + if (returnStream) { - SqlClientEventSource.Log.Trace(" {0}#, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Command executed as RPC.", ObjectID); } // TODO: Medusa: Unprepare only happens for SQL 7.0 which may be broken anyway (it's not re-prepared). Consider removing the reset here if we're really dropping 7.0 support. @@ -5496,9 +5335,9 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // then batch sql them over. This is inefficient (3 round trips) but the only way we can get metadata only from // a stored proc optionSettings = GetSetOptionsString(cmdBehavior); - if (returnStream && SqlClientEventSource.Log.IsTraceEnabled()) + if (returnStream) { - SqlClientEventSource.Log.Trace(" {0}#, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Command executed as RPC.", ObjectID); } // turn set options ON if (null != optionSettings) @@ -5592,11 +5431,7 @@ private SqlDataReader RunExecuteReaderSmi(CommandBehavior cmdBehavior, RunBehavi long transactionId; SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, innerConnection={1}#, transactionId=0x{2}, commandBehavior={(int)cmdBehavior}.", ObjectID, innerConnection.ObjectID, transactionId); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, innerConnection={1}#, transactionId=0x{2}, commandBehavior={(int)cmdBehavior}.", ObjectID, innerConnection.ObjectID, transactionId); if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { @@ -5816,11 +5651,7 @@ private void NotifyDependency() public SqlCommand Clone() { SqlCommand clone = new SqlCommand(this); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, clone={1}#", ObjectID, clone.ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, clone={1}#", ObjectID, clone.ObjectID); return clone; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index 1b28d0920f..860fe26da7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -129,12 +129,9 @@ internal int ObjectID internal void Append(SqlCommand command) { ADP.CheckArgumentNull(command, "command"); - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace($" {ObjectID}#, command={command.ObjectID}, parameterCount={command.Parameters.Count}"); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, command={1}, parameterCount={2}", ObjectID, command.ObjectID, command.Parameters.Count); string cmdText = command.CommandText; + if (ADP.IsEmpty(cmdText)) { throw ADP.CommandTextRequired(ADP.Append); @@ -267,11 +264,7 @@ internal static void BuildStoredProcedureName(StringBuilder builder, string part internal void Clear() { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace($" {ObjectID}#"); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); DbCommand batchCommand = BatchCommand; if (null != batchCommand) { @@ -287,11 +280,7 @@ internal void Clear() internal void Dispose() { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace($" {ObjectID}#"); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); SqlCommand command = _batchCommand; _commandList = null; _batchCommand = null; @@ -305,10 +294,7 @@ internal void Dispose() internal int ExecuteNonQuery() { SqlConnection.ExecutePermission.Demand(); - - long scopeID = 0; - if (SqlClientEventSource.Log.IsEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter($" {ObjectID}#"); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); try { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index 68086117e0..1eb593a4dd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -1101,12 +1101,7 @@ public SqlTransaction BeginTransaction(string transactionName) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#, isolationLevel={1}", ObjectID, (int)isolationLevel); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#, isolationLevel={1}", ObjectID, (int)isolationLevel); try { @@ -1131,12 +1126,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam { WaitForPendingReconnection(); SqlStatistics statistics = null; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#, iso={1}, transactionName='{2}'", ObjectID, (int)iso, (ADP.IsEmpty(transactionName) ? "None" : transactionName)); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#, iso={1}, transactionName='{2}'", ObjectID, (int)iso, (ADP.IsEmpty(transactionName) ? "None" : transactionName)); try { @@ -1174,14 +1164,10 @@ override public void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } - + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG @@ -1272,16 +1258,8 @@ void CloseInnerConnection() /// override public void Close() { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); try { @@ -1419,16 +1397,8 @@ public void EnlistDistributedTransaction(System.EnterpriseServices.ITransaction /// override public void Open() { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); try { @@ -1496,10 +1466,7 @@ private async Task ReconnectAsync(int timeout) { if (ctoken.IsCancellationRequested) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Orginal ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId.ToString()); - } + SqlClientEventSource.Log.TraceEvent(" Orginal ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId.ToString()); return; } try @@ -1521,26 +1488,15 @@ private async Task ReconnectAsync(int timeout) ForceNewConnection = false; } - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Reconnection suceeded. ClientConnectionID {0} -> {1}", _originalConnectionId.ToString(), ClientConnectionId.ToString()); - } + SqlClientEventSource.Log.TraceEvent(" Reconnection suceeded. ClientConnectionID {0} -> {1}", _originalConnectionId.ToString(), ClientConnectionId.ToString()); return; } catch (SqlException e) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Orginal ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message); - } - + SqlClientEventSource.Log.TraceEvent(" Orginal ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message); if (attempt == retryCount - 1) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Orginal ClientConnectionID {0} - give up reconnection", _originalConnectionId.ToString()); - } - + SqlClientEventSource.Log.TraceEvent(" Orginal ClientConnectionID {0} - give up reconnection", _originalConnectionId.ToString()); throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) @@ -1604,14 +1560,12 @@ internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) if (runningReconnect == null) { if (cData._unrecoverableStatesCount == 0) - { // could change since the first check, but now is stable since connection is know to be broken + { + // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId.ToString()); - } + SqlClientEventSource.Log.TraceEvent(" Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId.ToString()); _recoverySessionData = cData; + if (beforeDisconnect != null) { beforeDisconnect(); @@ -1702,20 +1656,11 @@ void CancelOpenAndWait() /// public override Task OpenAsync(CancellationToken cancellationToken) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.PoolerScopeEnter(" {0}#", ObjectID); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.PoolerScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); try { - if (StatisticsEnabled) { if (null == _statistics) @@ -1810,11 +1755,9 @@ public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource retryTask) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#", _parent.ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#", _parent.ObjectID); _registration.Dispose(); + try { SqlStatistics statistics = null; @@ -2160,11 +2103,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {0}#, Connection broken.", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection broken.", ObjectID); Close(); } }; @@ -2173,10 +2112,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {0}#, Connection broken.", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection broken.", ObjectID); Close(); } } @@ -2284,13 +2220,9 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) Debug.Assert(null != imevent, "null SqlInfoMessageEventArgs"); var imeventValue = (null != imevent) ? imevent.Message : ""; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Message='{1}'", ObjectID, imeventValue); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Message='{1}'", ObjectID, imeventValue); SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage]; + if (null != handler) { notified = true; @@ -2502,16 +2434,8 @@ private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, s /// public static void ChangePassword(string connectionString, string newPassword) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(""); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ActivityID {0}", ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); + SqlClientEventSource.Log.CorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current.ToString()); try { @@ -2558,16 +2482,8 @@ public static void ChangePassword(string connectionString, string newPassword) /// public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(""); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ActivityID {0}", ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); + SqlClientEventSource.Log.CorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current.ToString()); try { @@ -2738,7 +2654,7 @@ private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) { if (asmRef.Version != TypeSystemAssemblyVersion && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace(" SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version.ToString(), TypeSystemAssemblyVersion.ToString()); + SqlClientEventSource.Log.TraceEvent(" SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version.ToString(), TypeSystemAssemblyVersion.ToString()); } asmRef.Version = TypeSystemAssemblyVersion; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs index 25000ded38..78a4838558 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs @@ -193,11 +193,7 @@ override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions { connectionTimeout *= 10; } - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace("Set connection pool CreateTimeout={0} when AD Interactive is in use.", connectionTimeout); - } + SqlClientEventSource.Log.TraceEvent("Set connection pool CreateTimeout={0} when AD Interactive is in use.", connectionTimeout); } poolingOptions = new DbConnectionPoolGroupOptions( diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs index cd1553ef1e..459ea14cca 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs @@ -56,11 +56,7 @@ internal void AliasCheck(string server) } else if (_alias != server) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" alias change detected. Clearing PoolGroup"); - } - + SqlClientEventSource.Log.TraceEvent(" alias change detected. Clearing PoolGroup"); base.PoolGroup.Clear(); _alias = server; } @@ -104,10 +100,7 @@ internal void FailoverCheck(SqlInternalConnection connection, bool actualUseFail if (UseFailoverPartner != actualUseFailoverPartner) { // TODO: will connections in progress somehow be active for two different datasources? - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Failover detected. failover partner='{0}'. Clearing PoolGroup", actualFailoverPartner); - } + SqlClientEventSource.Log.TraceEvent(" Failover detected. failover partner='{0}'. Clearing PoolGroup", actualFailoverPartner); base.PoolGroup.Clear(); _useFailoverPartner = actualUseFailoverPartner; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index 02fea66625..aa9f9f5781 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -142,11 +142,7 @@ override public int UpdateBatchSize throw ADP.ArgumentOutOfRange("UpdateBatchSize"); } _updateBatchSize = value; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, {1}", ObjectID, value); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, {1}", ObjectID, value); } } @@ -253,9 +249,7 @@ override protected RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, override protected int ExecuteBatch() { Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); return _commandSet.ExecuteNonQuery(); } @@ -279,10 +273,7 @@ override protected bool GetBatchedRecordsAffected(int commandIdentifier, out int /// override protected void InitializeBatching() { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); _commandSet = new SqlCommandSet(); SqlCommand command = SelectCommand; if (null == command) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs index 22d9a8d12c..9416c77825 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -939,12 +939,7 @@ private void CleanPartialReadReliable() override public void Close() { SqlStatistics statistics = null; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); try { @@ -1675,12 +1670,7 @@ override public int GetProviderSpecificValues(object[] values) override public DataTable GetSchemaTable() { SqlStatistics statistics = null; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); try { @@ -3612,12 +3602,9 @@ override public bool NextResult() private bool TryNextResult(out bool more) { SqlStatistics statistics = null; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG @@ -3821,12 +3808,9 @@ override public bool Read() private bool TryReadInternal(bool setTimeout, out bool more) { SqlStatistics statistics = null; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG @@ -4491,11 +4475,7 @@ private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateO // broken connection, so check state first. if (parser.State == TdsParserState.OpenLoggedIn) { - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID '{1}'", ObjectID, ActivityCorrelator.Current.ToString()); - } - + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID '{1}'", ObjectID, ActivityCorrelator.Current.ToString()); Task executeTask = parser.TdsExecuteSQLBatch(_resetOptionsString, (_command != null) ? _command.CommandTimeout : 0, null, stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -4807,11 +4787,7 @@ private void AssertReaderState(bool requireData, bool permitAsync, int? columnIn /// public override Task NextResultAsync(CancellationToken cancellationToken) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); try { @@ -4857,10 +4833,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) { if (t != null) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" attempt retry {0}#", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" attempt retry {0}#", ObjectID); PrepareForAsyncContinuation(); } @@ -4942,11 +4915,7 @@ internal Task GetBytesAsync(int i, byte[] buffer, int index, int length, in { if (t != null) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" attempt retry {0}#", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" attempt retry {0}#", ObjectID); PrepareForAsyncContinuation(); } @@ -5117,12 +5086,7 @@ private Task GetBytesAsyncReadDataStage(int i, byte[] buffer, int index, in /// public override Task ReadAsync(CancellationToken cancellationToken) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); try { if (IsClosed) @@ -5242,11 +5206,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) { if (t != null) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" attempt retry {0}#", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" attempt retry {0}#", ObjectID); PrepareForAsyncContinuation(); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs index df922d3470..12ecbe8d65 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs @@ -374,12 +374,7 @@ public override void Close() private void CloseInternal(bool closeConnection) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); bool processFinallyBlock = true; try { @@ -438,12 +433,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.AdvanceScopeEnter(" {0}#", ObjectID); try { _hasRows = false; @@ -476,10 +466,7 @@ internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) } finally { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.ScopeLeave(scopeID); - } + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -499,12 +486,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) internal unsafe bool InternalRead(bool ignoreNonFatalErrors) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.AdvanceScopeEnter(" {0}#", ObjectID); try { // Don't move unless currently in results. @@ -543,10 +525,7 @@ internal unsafe bool InternalRead(bool ignoreNonFatalErrors) } finally { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.ScopeLeave(scopeID); - } + SqlClientEventSource.Log.ScopeLeave(scopeID); } } @@ -1337,15 +1316,15 @@ internal ReaderEventSink(SqlDataReaderSmi reader, SmiEventSink parent) internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIsRow) { var mdLength = (null != md) ? md.Length : -1; + SqlClientEventSource.Log.AdvanceTrace(" {0}#, md.Length={1} nextEventIsRow={2}.", reader.ObjectID, mdLength, nextEventIsRow); if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - SqlClientEventSource.Log.Trace(" {0}#, md.Length={1} nextEventIsRow={2}.", reader.ObjectID, mdLength, nextEventIsRow); if (null != md) { for (int i = 0; i < md.Length; i++) { - SqlClientEventSource.Log.Trace(" {0}#, metaData[{1}] is {2}{3}", reader.ObjectID, i, md[i].GetType().ToString(), md[i].TraceString()); + SqlClientEventSource.Log.TraceEvent(" {0}#, metaData[{1}] is {2}{3}", reader.ObjectID, i, md[i].GetType().ToString(), md[i].TraceString()); } } } @@ -1355,37 +1334,25 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs // Obsolete V2- method internal override void RowAvailable(ITypedGetters row) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# (v2).", reader.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# (v2).", reader.ObjectID); this.reader.RowAvailable(row); } internal override void RowAvailable(ITypedGettersV3 row) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# (ITypedGettersV3).", reader.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# (ITypedGettersV3).", reader.ObjectID); this.reader.RowAvailable(row); } internal override void RowAvailable(SmiTypedGetterSetter rowData) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# (SmiTypedGetterSetter).", reader.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# (SmiTypedGetterSetter).", reader.ObjectID); this.reader.RowAvailable(rowData); } internal override void StatementCompleted(int recordsAffected) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# recordsAffected= {1}.", reader.ObjectID, recordsAffected); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# recordsAffected= {1}.", reader.ObjectID, recordsAffected); // devnote: relies on SmiEventSink_Default to pass event to parent // Both command and reader care about StatementCompleted, but for different reasons. @@ -1396,10 +1363,7 @@ internal override void StatementCompleted(int recordsAffected) internal override void BatchCompleted() { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#.", reader.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#.", reader.ObjectID); // devnote: relies on SmiEventSink_Default to pass event to parent // parent's callback *MUST* come before reader's BatchCompleted, since diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs index 1d3a6396ab..006fc1f15a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs @@ -89,12 +89,9 @@ public void Initialize() // transaction. SqlInternalConnection connection = _connection; SqlConnection usersConnection = connection.Connection; - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Connection {1}#, delegating transaction.", ObjectID, connection.ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection {1}#, delegating transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG @@ -109,10 +106,7 @@ public void Initialize() #endif //DEBUG if (connection.IsEnlistedInTransaction) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Connection {1}#, was enlisted, now defecting.", ObjectID, connection.ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection {1}#, was enlisted, now defecting.", ObjectID, connection.ObjectID); // defect first connection.EnlistNull(); @@ -174,13 +168,9 @@ public Byte[] Promote() Exception promoteException; byte[] returnValue = null; SqlConnection usersConnection = connection.Connection; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Connection {1}#, promoting transaction.", ObjectID, connection.ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection {1}#, promoting transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG @@ -278,13 +268,9 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) SqlInternalConnection connection = GetValidConnection(); SqlConnection usersConnection = connection.Connection; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Connection {1}#, aborting transaction.", ObjectID, connection.ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection {1}#, aborting transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG @@ -376,13 +362,9 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) SqlInternalConnection connection = GetValidConnection(); SqlConnection usersConnection = connection.Connection; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Connection {1}#, committing transaction.", ObjectID, connection.ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection {1}#, committing transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG @@ -512,10 +494,7 @@ internal void TransactionEnded(SysTx.Transaction transaction) if (connection != null) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Connection {1}#, transaction completed externally.", ObjectID, connection.ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection {1}#, transaction completed externally.", ObjectID, connection.ObjectID); lock (connection) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs index 48685daec1..fd0a6d5e75 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -316,12 +316,7 @@ public SqlDependency(SqlCommand command) : this(command, null, SQL.SqlDependency [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public SqlDependency(SqlCommand command, string options, int timeout) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, options: '{1}', timeout: '{2}'", ObjectID, options, timeout); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, options: '{1}', timeout: '{2}'", ObjectID, options, timeout); try { if (InOutOfProcHelper.InProc) @@ -441,11 +436,7 @@ public event OnChangeEventHandler OnChange // EventHandlers to be fired when dependency is notified. add { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { @@ -458,20 +449,12 @@ public event OnChangeEventHandler OnChange if (_dependencyFired) { // If fired, fire the new event immediately. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Dependency already fired, firing new event."); - } - + SqlClientEventSource.Log.NotificationsTrace(" Dependency already fired, firing new event."); sqlNotificationEvent = new SqlNotificationEventArgs(SqlNotificationType.Subscribe, SqlNotificationInfo.AlreadyChanged, SqlNotificationSource.Client); } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Dependency has not fired, adding new event."); - } - + SqlClientEventSource.Log.NotificationsTrace(" Dependency has not fired, adding new event."); EventContextPair pair = new EventContextPair(value, this); if (!_eventList.Contains(pair)) { @@ -497,12 +480,7 @@ public event OnChangeEventHandler OnChange } remove { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { if (null != value) @@ -537,12 +515,7 @@ public void AddCommandDependency(SqlCommand command) { // Adds command to dependency collection so we automatically create the SqlNotificationsRequest object // and listen for a notification for the added commands. - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { if (command == null) @@ -580,16 +553,11 @@ private static void ObtainProcessDispatcher() if (nativeStorage == null) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher."); - } + SqlClientEventSource.Log.NotificationsTrace(" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher."); #if DEBUG // Possibly expensive, limit to debug. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); + #endif _AppDomain masterDomain = SNINativeMethodWrapper.GetDefaultAppDomain(); @@ -614,55 +582,33 @@ private static void ObtainProcessDispatcher() } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - ObjectHandle.Unwrap returned null!"); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR - ObjectHandle.Unwrap returned null!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyObtainProcessDispatcherFailureObjectHandle); } } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!"); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureCreateInstance); } } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - unable to obtain default AppDomain!"); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR - unable to obtain default AppDomain!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureAppDomain); } } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher."); - } + SqlClientEventSource.Log.NotificationsTrace(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher."); #if DEBUG // Possibly expensive, limit to debug. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); #endif BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(nativeStorage); _processDispatcher = GetDeserializedObject(formatter, stream); // Deserialize and set for appdomain. - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" processDispatcher obtained, ID: {0}", _processDispatcher.ObjectID); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" processDispatcher obtained, ID: {0}", _processDispatcher.ObjectID); } } @@ -709,12 +655,7 @@ public static bool Start(string connectionString, string queue) internal static bool Start(string connectionString, string queue, bool useDefaults) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -787,10 +728,8 @@ internal static bool Start(string connectionString, string queue, bool useDefaul SqlDependencyPerAppDomainDispatcher.SingletonInstance, out errorOccurred, out appDomainStart); - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Start (defaults) returned: '{0}', with service: '{1}', server: '{2}', database: '{3}'", result, service, server, database); - } + + SqlClientEventSource.Log.NotificationsTraceEvent(" Start (defaults) returned: '{0}', with service: '{1}', server: '{2}', database: '{3}'", result, service, server, database); } finally { @@ -812,11 +751,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Exception occurred from Stop() after duplicate was found on Start()."); - } + SqlClientEventSource.Log.NotificationsTrace(" Exception occurred from Stop() after duplicate was found on Start()."); } throw SQL.SqlDependencyDuplicateStart(); } @@ -829,10 +764,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul queue, _appDomainKey, SqlDependencyPerAppDomainDispatcher.SingletonInstance); - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Start (user provided queue) returned: '{0}'", result); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" Start (user provided queue) returned: '{0}'", result); // No need to call AddToServerDatabaseHash since if not using default queue user is required // to provide options themselves. @@ -847,11 +779,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); - } - + SqlClientEventSource.Log.NotificationsTrace(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); throw; } } @@ -880,12 +808,7 @@ public static bool Stop(string connectionString, string queue) internal static bool Stop(string connectionString, string queue, bool useDefaults, bool startFailed) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -1005,11 +928,8 @@ internal static bool Stop(string connectionString, string queue, bool useDefault private static bool AddToServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); - } + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + try { bool result = false; @@ -1020,11 +940,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!_serverUserHash.ContainsKey(server)) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Hash did not contain server, adding."); - } - + SqlClientEventSource.Log.NotificationsTrace(" Hash did not contain server, adding."); identityDatabaseHash = new Dictionary>(); _serverUserHash.Add(server, identityDatabaseHash); } @@ -1037,11 +953,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!identityDatabaseHash.ContainsKey(identityUser)) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Hash contained server but not user, adding user."); - } - + SqlClientEventSource.Log.NotificationsTrace(" Hash contained server but not user, adding user."); databaseServiceList = new List(); identityDatabaseHash.Add(identityUser, databaseServiceList); } @@ -1058,10 +970,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash already contained server, user, and database - we will throw!."); - } + SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash already contained server, user, and database - we will throw!."); } } @@ -1075,11 +984,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden private static void RemoveFromServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); - } + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); try { @@ -1100,58 +1005,36 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair int index = databaseServiceList.IndexOf(databaseService); if (index >= 0) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Hash contained server, user, and database - removing database."); - } - + SqlClientEventSource.Log.NotificationsTrace(" Hash contained server, user, and database - removing database."); databaseServiceList.RemoveAt(index); if (databaseServiceList.Count == 0) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" databaseServiceList count 0, removing the list for this server and user."); - } - + SqlClientEventSource.Log.NotificationsTrace(" databaseServiceList count 0, removing the list for this server and user."); identityDatabaseHash.Remove(identityUser); if (identityDatabaseHash.Count == 0) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" identityDatabaseHash count 0, removing the hash for this server."); - } - + SqlClientEventSource.Log.NotificationsTrace(" identityDatabaseHash count 0, removing the hash for this server."); _serverUserHash.Remove(server); } } } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash contained server and user but not database!"); - + SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash contained server and user but not database!"); Debug.Assert(false, "Unexpected state - hash did not contain database!"); } } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash contained server but not user!"); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash contained server but not user!"); Debug.Assert(false, "Unexpected state - hash did not contain user!"); } } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash did not contain server!"); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR - hash did not contain server!"); Debug.Assert(false, "Unexpected state - hash did not contain server!"); } } @@ -1166,9 +1049,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { // Server must be an exact match, but user and database only needs to match exactly if there is more than one // for the given user or database passed. That is ambiguious and we must fail. - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" server: '{0}', failoverServer: '{1}', database: '{2}'", server, failoverServer, database); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" server: '{0}', failoverServer: '{1}', database: '{2}'", server, failoverServer, database); try { @@ -1181,11 +1062,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS if (0 == _serverUserHash.Count) { // Special error for no calls to start. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - no start calls have been made, about to throw."); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR - no start calls have been made, about to throw."); throw SQL.SqlDepDefaultOptionsButNoStart(); } else if (!ADP.IsEmpty(failoverServer) && _serverUserHash.ContainsKey(failoverServer)) @@ -1195,11 +1072,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - not listening to this server, about to throw."); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR - not listening to this server, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } } @@ -1212,12 +1085,8 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { if (identityDatabaseHash.Count > 1) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - not listening for this user, " + - "but listening to more than one other user, about to throw."); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR - not listening for this user, " + + "but listening to more than one other user, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } else @@ -1264,23 +1133,14 @@ internal static string GetDefaultComposedOptions(string server, string failoverS else { // More than one database for given server, ambiguous - fail the default case! - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); throw SQL.SqlDependencyNoMatchingServerDatabaseStart(); } } } Debug.Assert(!ADP.IsEmpty(result), "GetDefaultComposedOptions should never return null or empty string!"); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" resulting options: '{0}'.", result); - } - + SqlClientEventSource.Log.NotificationsTraceEvent(" resulting options: '{0}'.", result); return result; } finally @@ -1297,27 +1157,18 @@ internal static string GetDefaultComposedOptions(string server, string failoverS // use this list for a reverse lookup based on server. internal void AddToServerList(string server) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, server: '{1}'", ObjectID, server); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, server: '{1}'", ObjectID, server); try { lock (_serverList) { int index = _serverList.BinarySearch(server, StringComparer.OrdinalIgnoreCase); if (0 > index) - { // If less than 0, item was not found in list. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Server not present in hashtable, adding server: '{0}'.", server); - } - + { + // If less than 0, item was not found in list. + SqlClientEventSource.Log.NotificationsTraceEvent(" Server not present in hashtable, adding server: '{0}'.", server); index = ~index; // BinarySearch returns the 2's compliment of where the item should be inserted to preserver a sorted list after insertion. _serverList.Insert(index, server); - } } } @@ -1337,11 +1188,7 @@ internal bool ContainsServer(string server) internal string ComputeHashAndAddToDispatcher(SqlCommand command) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, SqlCommand: {1}#", ObjectID, command.ObjectID); - } + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, SqlCommand: {1}#", ObjectID, command.ObjectID); try { // Create a string representing the concatenation of the connection string, command text and .ToString on all parameter values. @@ -1356,11 +1203,7 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) string commandHash = ComputeCommandHash(command.Connection.ConnectionString, command); // calculate the string representation of command string idString = SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddCommandEntry(commandHash, this); // Add to map. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" computed id string: '{0}'.", idString); - } - + SqlClientEventSource.Log.NotificationsTraceEvent(" computed id string: '{0}'.", idString); return idString; } finally @@ -1371,12 +1214,7 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { List eventList = null; @@ -1394,19 +1232,12 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql // raises Timeout event but before removing this event from the list. If notification is received from // server in this case, we will hit this code path. // It is safe to ignore this race condition because no event is sent to user and no leak happens. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ignore notification received after timeout!"); - } + SqlClientEventSource.Log.NotificationsTrace(" ignore notification received after timeout!"); } else { Debug.Assert(false, "Received notification twice - we should never enter this state!"); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - notification received twice - we should never enter this state!"); - } + SqlClientEventSource.Log.NotificationsTrace(" ERROR - notification received twice - we should never enter this state!"); } } else @@ -1420,11 +1251,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (eventList != null) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Firing events."); - } - + SqlClientEventSource.Log.NotificationsTrace(" Firing events."); foreach (EventContextPair pair in eventList) { pair.Invoke(new SqlNotificationEventArgs(type, info, source)); @@ -1440,21 +1267,12 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql // This method is used by SqlCommand. internal void StartTimer(SqlNotificationRequest notificationRequest) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { if (_expirationTime == DateTime.MaxValue) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" We've timed out, executing logic."); - } - + SqlClientEventSource.Log.NotificationsTrace(" We've timed out, executing logic."); int seconds = SQL.SqlDependencyServerTimeout; if (0 != _timeout) { @@ -1485,12 +1303,7 @@ private void AddCommandInternal(SqlCommand cmd) if (cmd != null) { // Don't bother with BID if command null. - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, SqlCommand: {1}#", ObjectID, cmd.ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, SqlCommand: {1}#", ObjectID, cmd.ObjectID); try { SqlConnection connection = cmd.Connection; @@ -1500,11 +1313,7 @@ private void AddCommandInternal(SqlCommand cmd) // Fail if cmd has notification that is not already associated with this dependency. if (cmd._sqlDep == null || cmd._sqlDep != this) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception."); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception."); throw SQL.SqlCommandHasExistingSqlNotificationRequest(); } } @@ -1536,11 +1345,7 @@ private void AddCommandInternal(SqlCommand cmd) if (0 == _eventList.Count) { // Keep logic just in case. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point."); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point."); needToInvalidate = true; // Delay invalidation until outside of lock. } } @@ -1561,11 +1366,7 @@ private void AddCommandInternal(SqlCommand cmd) private string ComputeCommandHash(string connectionString, SqlCommand command) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, SqlCommand: {1}#", ObjectID, command.ObjectID); - } + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, SqlCommand: {1}#", ObjectID, command.ObjectID); try { @@ -1623,12 +1424,7 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) } string result = builder.ToString(); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ComputeCommandHash result: '{0}'.", result); - } - + SqlClientEventSource.Log.NotificationsTraceEvent(" ComputeCommandHash result: '{0}'.", result); return result; } finally diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index 056956b9c4..35de9d0c49 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -79,12 +79,7 @@ internal int ObjectID internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, queue: '{1}'", ObjectID, HashHelper.Queue); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, queue: '{1}'", ObjectID, HashHelper.Queue); bool setupCompleted = false; try @@ -107,11 +102,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(_hashHelper.ConnectionStringBuilder.ConnectionString); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif // Always use ConnectionStringBuilder since in default case it is different from the @@ -286,12 +277,7 @@ internal string Server // SqlDependencyProcessDispatcher.QueueAppDomainUnload on AppDomain.Unload. internal bool AppDomainUnload(string appDomainKey) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, AppDomainKey: '{1}'", ObjectID, appDomainKey); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, AppDomainKey: '{1}'", ObjectID, appDomainKey); try { Debug.Assert(!ADP.IsEmpty(appDomainKey), "Unexpected empty appDomainKey!"); @@ -303,18 +289,9 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { // Do nothing if AppDomain did not call Start! - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" _appDomainKeyHash contained AppDomainKey: '{0}'.", appDomainKey); - } - + SqlClientEventSource.Log.NotificationsTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}'.", appDomainKey); int value = _appDomainKeyHash[appDomainKey]; - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{0}' count: '{1}'.", appDomainKey, value); - } - + SqlClientEventSource.Log.NotificationsTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{0}' count: '{1}'.", appDomainKey, value); Debug.Assert(value > 0, "Why is value 0 or less?"); bool ignored = false; @@ -331,26 +308,15 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace("SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{0}' entry not removed from hash. Count: {1}'", appDomainKey, _appDomainKeyHash[appDomainKey]); - } + SqlClientEventSource.Log.NotificationsTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{0}' entry not removed from hash. Count: {1}'", appDomainKey, _appDomainKeyHash[appDomainKey]); } } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{0}'.", appDomainKey); - } + SqlClientEventSource.Log.NotificationsTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{0}'.", appDomainKey); } } - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace("SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{0}'.", _stopped); - } - + SqlClientEventSource.Log.NotificationsTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{0}'.", _stopped); return _stopped; } finally @@ -361,12 +327,7 @@ internal bool AppDomainUnload(string appDomainKey) private void AsynchronouslyQueryServiceBrokerQueue() { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { AsyncCallback callback = new AsyncCallback(AsyncResultCallback); @@ -380,12 +341,7 @@ private void AsynchronouslyQueryServiceBrokerQueue() private void AsyncResultCallback(IAsyncResult asyncResult) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { using (SqlDataReader reader = _com.EndExecuteReader(asyncResult)) @@ -411,11 +367,7 @@ private void AsyncResultCallback(IAsyncResult asyncResult) _errorState = true; throw; } - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Exception occurred."); - } + SqlClientEventSource.Log.NotificationsTrace(" Exception occurred."); if (!_stop) { // Only assert if not in cancel path. @@ -441,12 +393,7 @@ private void AsyncResultCallback(IAsyncResult asyncResult) private void CreateQueueAndService(bool restart) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { SqlCommand com = new SqlCommand(); @@ -582,21 +529,12 @@ private void CreateQueueAndService(bool restart) internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { appDomainStart = false; // Reset out param. int result = Interlocked.Increment(ref _startCount); // Add to refCount. - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace("SqlConnectionContainer.IncrementStartCount|DEP> {0}#, incremented _startCount: {1}", _staticInstance.ObjectID, result); - } + SqlClientEventSource.Log.NotificationsTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> {0}#, incremented _startCount: {1}", _staticInstance.ObjectID, result); // Dictionary used to track how many times start has been called per app domain. // For each increment, add to count, and create entry if not present. @@ -605,21 +543,13 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { _appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1; - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace("SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{0}', incremented count: '{1}'.", appDomainKey, _appDomainKeyHash[appDomainKey]); - } + SqlClientEventSource.Log.NotificationsTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{0}', incremented count: '{1}'.", appDomainKey, _appDomainKeyHash[appDomainKey]); } else { _appDomainKeyHash[appDomainKey] = 1; appDomainStart = true; - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" _appDomainKeyHash did not contain AppDomainKey: '{0}', added to hashtable and value set to 1.", appDomainKey); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" _appDomainKeyHash did not contain AppDomainKey: '{0}', added to hashtable and value set to 1.", appDomainKey); } } } @@ -631,12 +561,7 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) private void ProcessNotificationResults(SqlDataReader reader) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { Guid handle = Guid.Empty; // Conversation_handle. Always close this! @@ -646,27 +571,18 @@ private void ProcessNotificationResults(SqlDataReader reader) { while (reader.Read()) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Row read."); - } + SqlClientEventSource.Log.NotificationsTrace(" Row read."); #if DEBUG - for (int i = 0; i < reader.FieldCount; i++) + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) { - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + for (int i = 0; i < reader.FieldCount; i++) { - SqlClientEventSource.Log.NotificationsTrace(" column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i).ToString()); + SqlClientEventSource.Log.NotificationsTraceEvent(" column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i).ToString()); } } #endif string msgType = reader.GetString(0); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" msgType: '{0}'", msgType); - } - + SqlClientEventSource.Log.NotificationsTraceEvent(" msgType: '{0}'", msgType); handle = reader.GetGuid(1); // SqlClientEventSource.SqlClientEventSource.Log.NotificationsTrace($"SqlConnectionContainer.ProcessNotificationResults(SqlDataReader)|DEP> conversationHandle: '%p(GUID)'", conversationHandle); @@ -680,12 +596,7 @@ private void ProcessNotificationResults(SqlDataReader reader) if (null != notification) { string key = notification.Key; - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Key: '{0}'", key); - } - + SqlClientEventSource.Log.NotificationsTraceEvent(" Key: '{0}'", key); int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash" if (index >= 0) @@ -714,41 +625,25 @@ private void ProcessNotificationResults(SqlDataReader reader) else { Debug.Assert(false, "Received notification but do not have an associated PerAppDomainDispatcher!"); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Received notification but do not have an associated PerAppDomainDispatcher!"); - } + SqlClientEventSource.Log.NotificationsTrace(" Received notification but do not have an associated PerAppDomainDispatcher!"); } } else { Debug.Assert(false, "Unexpected ID format received!"); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Unexpected ID format received!"); - } + SqlClientEventSource.Log.NotificationsTrace(" Unexpected ID format received!"); } } else { Debug.Assert(false, "Null notification returned from ProcessMessage!"); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Null notification returned from ProcessMessage!"); - } + SqlClientEventSource.Log.NotificationsTrace(" Null notification returned from ProcessMessage!"); } } else { Debug.Assert(false, "Null payload for QN notification type!"); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Null payload for QN notification type!"); - } + SqlClientEventSource.Log.NotificationsTrace(" Null payload for QN notification type!"); } } else @@ -756,11 +651,7 @@ private void ProcessNotificationResults(SqlDataReader reader) handle = Guid.Empty; // VSDD 546707: this assert was hit by SQL Notification fuzzing tests, disable it to let these tests run on Debug bits // Debug.Assert(false, "Unexpected message format received!"); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Unexpected message format received!"); - } + SqlClientEventSource.Log.NotificationsTrace(" Unexpected message format received!"); } } } @@ -803,12 +694,7 @@ private void ProcessNotificationResults(SqlDataReader reader) private void Restart(object unused) { // Unused arg required by TimerCallback. - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { try @@ -976,12 +862,7 @@ private void Restart(object unused) internal bool Stop(string appDomainKey, out bool appDomainStop) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { appDomainStop = false; @@ -1001,11 +882,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) int value = _appDomainKeyHash[appDomainKey]; Debug.Assert(value > 0, "Unexpected count for appDomainKey"); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" _appDomainKeyHash contained AppDomainKey: '{0}', pre-decrement Count: '{1}'.", appDomainKey, value); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}', pre-decrement Count: '{1}'.", appDomainKey, value); if (value > 0) { @@ -1013,11 +890,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR pre-decremented count <= 0!"); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR pre-decremented count <= 0!"); Debug.Assert(false, "Unexpected AppDomainKey count in Stop()"); } @@ -1029,11 +902,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR appDomainKey not null and not found in hash!"); - } - + SqlClientEventSource.Log.NotificationsTrace(" ERROR appDomainKey not null and not found in hash!"); Debug.Assert(false, "Unexpected state on Stop() - no AppDomainKey entry in hashtable!"); } } @@ -1045,11 +914,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) if (0 == result) { // If we've reached refCount 0, destroy. // Lock to ensure Cancel() complete prior to other thread calling TearDown. - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Reached 0 count, cancelling and waiting."); - } + SqlClientEventSource.Log.NotificationsTrace(" Reached 0 count, cancelling and waiting."); lock (this) { @@ -1093,11 +958,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) // TearDownAndDispose in the maximum retry period case as well as in the _errorState case. if (_errorState || retryStopwatch.Elapsed.Seconds >= 30) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" forcing cleanup. elapsedSeconds: '{0}', _errorState: '{1}'.", retryStopwatch.Elapsed.Seconds, _errorState); - } - + SqlClientEventSource.Log.NotificationsTraceEvent(" forcing cleanup. elapsedSeconds: '{0}', _errorState: '{1}'.", retryStopwatch.Elapsed.Seconds, _errorState); Timer retryTimer = _retryTimer; _retryTimer = null; if (retryTimer != null) @@ -1116,10 +977,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" _startCount not 0 after decrement. _startCount: '{0}'.", _startCount); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" _startCount not 0 after decrement. _startCount: '{0}'.", _startCount); } Debug.Assert(0 <= _startCount, "Invalid start count state"); @@ -1134,11 +992,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) private void SynchronouslyQueryServiceBrokerQueue() { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { @@ -1156,11 +1010,7 @@ private void SynchronouslyQueryServiceBrokerQueue() [SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")] private void TearDownAndDispose() { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { @@ -1378,61 +1228,42 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) catch (ArgumentException e) { ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace. - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Exception thrown - Enum.Parse failed to parse the value '{0}' of the attribute '{1}'.", xmlReader.Value, xmlReader.LocalName); - } + SqlClientEventSource.Log.TraceEvent(" Exception thrown - Enum.Parse failed to parse the value '{0}' of the attribute '{1}'.", xmlReader.Value, xmlReader.LocalName); return null; } } if (MessageAttributes.All != messageAttributes) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Not all expected attributes in Message; messageAttributes = '{0}'.", (int)messageAttributes); - } + SqlClientEventSource.Log.TraceEvent(" Not all expected attributes in Message; messageAttributes = '{0}'.", (int)messageAttributes); return null; } // Proceed to the "Message" node. if (!xmlReader.Read()) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); - } + SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Verify state after Read(). if ((XmlNodeType.Element != xmlReader.NodeType) || (0 != string.Compare(xmlReader.LocalName, MessageNode, StringComparison.OrdinalIgnoreCase))) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); - } + SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Proceed to the Text Node. if (!xmlReader.Read()) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); - } + SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Verify state after Read(). if (xmlReader.NodeType != XmlNodeType.Text) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); - } + SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } @@ -1442,10 +1273,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the Text Node. if (!xmlMessageReader.Read()) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); - } + SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } @@ -1456,10 +1284,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); - } + SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } } @@ -1468,10 +1293,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" unexpected Read failure on xml or unexpected structure of xml."); - } + SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; // failure } } @@ -1651,21 +1473,12 @@ internal int ObjectID private SqlDependencyProcessDispatcher(object dummyVariable) { Debug.Assert(null == _staticInstance, "Real constructor called with static instance already created!"); - - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { #if DEBUG // Possibly expensive, limit to debug. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" {0}#, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); #endif _connectionContainers = new Dictionary(); _sqlDependencyPerAppDomainDispatchers = new Dictionary(); @@ -1680,21 +1493,13 @@ private SqlDependencyProcessDispatcher(object dummyVariable) // Required to be public, even on internal class, for Remoting infrastructure. public SqlDependencyProcessDispatcher() { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { // Empty constructor and object - dummy to obtain singleton. #if DEBUG // Possibly expensive, limit to debug. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" {0}#, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); #endif } finally @@ -1725,12 +1530,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS out string user, string queue) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, queue: {1}", _staticInstance.ObjectID, queue); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, queue: {1}", _staticInstance.ObjectID, queue); try { // Force certain connection string properties to be used by SqlDependencyProcessDispatcher. @@ -1775,12 +1575,7 @@ public override object InitializeLifetimeService() private void Invalidate(string server, SqlNotification sqlNotification) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, server: {1}", ObjectID, server); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, server: {1}", ObjectID, server); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1829,12 +1624,7 @@ internal void QueueAppDomainUnloading(string appDomainKey) // This method is only called by queued work-items from the method above. private void AppDomainUnloading(object state) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { string appDomainKey = (string)state; @@ -1933,12 +1723,7 @@ private bool Start(string connectionString, out bool appDomainStart, bool useDefaults) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, queue: '{1}', appDomainKey: '{2}', perAppDomainDispatcher ID: '{3}'", ObjectID, queueService, appDomainKey, dispatcher.ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, queue: '{1}', appDomainKey: '{2}', perAppDomainDispatcher ID: '{3}'", ObjectID, queueService, appDomainKey, dispatcher.ObjectID); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1965,11 +1750,7 @@ private bool Start(string connectionString, queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif bool started = false; @@ -1979,11 +1760,7 @@ private bool Start(string connectionString, { if (!_connectionContainers.ContainsKey(hashHelper)) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" {0}#, hashtable miss, creating new container.", ObjectID); - } - + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, hashtable miss, creating new container.", ObjectID); container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults); _connectionContainers.Add(hashHelper, container); started = true; @@ -1992,19 +1769,10 @@ private bool Start(string connectionString, else { container = _connectionContainers[hashHelper]; - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" {0}#, hashtable hit, container: {1}", ObjectID, container.ObjectID); - } - + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, hashtable hit, container: {1}", ObjectID, container.ObjectID); if (container.InErrorState) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" {0}#, container: {1} is in error state!", ObjectID, container.ObjectID); - } - + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, container: {1} is in error state!", ObjectID, container.ObjectID); errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start(). } else @@ -2019,18 +1787,10 @@ private bool Start(string connectionString, server = container.Server; database = container.Database; queueService = container.Queue; - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" {0}#, default service: '{1}', server: '{2}', database: '{3}'", ObjectID, queueService, server, database); - } - } - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" {0}#, started: {1}", ObjectID, started); + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, default service: '{1}', server: '{2}', database: '{3}'", ObjectID, queueService, server, database); } + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, started: {1}", ObjectID, started); return started; } finally @@ -2052,12 +1812,7 @@ internal bool Stop(string connectionString, string appDomainKey, out bool appDomainStop) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, queue: '{1}'", ObjectID, queueService); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, queue: '{1}'", ObjectID, queueService); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -2075,11 +1830,7 @@ internal bool Stop(string connectionString, queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif bool stopped = false; @@ -2089,11 +1840,7 @@ internal bool Stop(string connectionString, if (_connectionContainers.ContainsKey(hashHelper)) { SqlConnectionContainer container = _connectionContainers[hashHelper]; - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" {0}#, hashtable hit, container: {1}", ObjectID, container.ObjectID); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, hashtable hit, container: {1}", ObjectID, container.ObjectID); server = container.Server; // Return server, database, and queue info for use by calling SqlDependency. database = container.Database; @@ -2106,18 +1853,11 @@ internal bool Stop(string connectionString, } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" {0}#, hashtable miss.", ObjectID); - } + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, hashtable miss.", ObjectID); } } - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" {0}#, stopped: {1}", ObjectID, stopped); - } - + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, stopped: {1}", ObjectID, stopped); return stopped; } finally diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs index 011dc7ac40..63298ce852 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs @@ -92,12 +92,7 @@ internal int ObjectID private SqlDependencyPerAppDomainDispatcher() { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { _dependencyIdToDependencyHash = new Dictionary(); @@ -129,12 +124,7 @@ public override object InitializeLifetimeService() private void UnloadEventHandler(object sender, EventArgs e) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { // Make non-blocking call to ProcessDispatcher to ThreadPool.QueueUserWorkItem to complete @@ -160,12 +150,7 @@ private void UnloadEventHandler(object sender, EventArgs e) // This method is called upon SqlDependency constructor. internal void AddDependencyEntry(SqlDependency dep) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, SqlDependency: {1}#", ObjectID, dep.ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, SqlDependency: {1}#", ObjectID, dep.ObjectID); try { lock (this) @@ -183,13 +168,7 @@ internal void AddDependencyEntry(SqlDependency dep) internal string AddCommandEntry(string commandHash, SqlDependency dep) { string notificationId = string.Empty; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, commandHash: '{1}', SqlDependency: {2}#", ObjectID, commandHash, dep.ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, commandHash: '{1}', SqlDependency: {2}#", ObjectID, commandHash, dep.ObjectID); try { lock (this) @@ -197,10 +176,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) if (!_dependencyIdToDependencyHash.ContainsKey(dep.Id)) { // Determine if depId->dep hashtable contains dependency. If not, it's been invalidated. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Dependency not present in depId->dep hash, must have been invalidated."); - } + SqlClientEventSource.Log.NotificationsTrace(" Dependency not present in depId->dep hash, must have been invalidated."); } else { @@ -221,19 +197,12 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // join the new dependency to the list if (!dependencyList.Contains(dep)) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Dependency not present for commandHash, adding."); - } - + SqlClientEventSource.Log.NotificationsTrace(" Dependency not present for commandHash, adding."); dependencyList.Add(dep); } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Dependency already present for commandHash."); - } + SqlClientEventSource.Log.NotificationsTrace(" Dependency already present for commandHash."); } } else @@ -247,12 +216,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) SqlDependency.AppDomainKey, // must be first Guid.NewGuid().ToString("D", System.Globalization.CultureInfo.InvariantCulture) ); - - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Creating new Dependencies list for commandHash."); - } - + SqlClientEventSource.Log.NotificationsTrace(" Creating new Dependencies list for commandHash."); DependencyList dependencyList = new DependencyList(commandHash); dependencyList.Add(dep); @@ -283,12 +247,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // This method is called by the ProcessDispatcher upon a notification for this AppDomain. internal void InvalidateCommandID(SqlNotification sqlNotification) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, commandHash: '{1}'", ObjectID, sqlNotification.Key); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, commandHash: '{1}'", ObjectID, sqlNotification.Key); try { List dependencyList = null; @@ -299,11 +258,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) if (null != dependencyList) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" commandHash found in hashtable."); - } - + SqlClientEventSource.Log.NotificationsTrace(" commandHash found in hashtable."); foreach (SqlDependency dependency in dependencyList) { // Ensure we remove from process static app domain hash for dependency initiated invalidates. @@ -315,10 +270,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" commandHash NOT found in hashtable."); - } + SqlClientEventSource.Log.NotificationsTrace(" commandHash NOT found in hashtable."); } } @@ -327,11 +279,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) // After removal from hashtables, invalidate. foreach (SqlDependency dependency in dependencyList) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Dependency found in commandHash dependency ArrayList - calling invalidate."); - } - + SqlClientEventSource.Log.NotificationsTrace(" Dependency found in commandHash dependency ArrayList - calling invalidate."); try { dependency.Invalidate(sqlNotification.Type, sqlNotification.Info, sqlNotification.Source); @@ -359,12 +307,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) // This method is called when a connection goes down or other unknown error occurs in the ProcessDispatcher. internal void InvalidateServer(string server, SqlNotification sqlNotification) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, server: '{1}'", ObjectID, server); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, server: '{1}'", ObjectID, server); try { List dependencies = new List(); @@ -418,12 +361,7 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) // This method is called by SqlCommand to enable ASP.NET scenarios - map from ID to Dependency. internal SqlDependency LookupDependencyEntry(string id) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, Key: '{1}'", ObjectID, id); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, Key: '{1}'", ObjectID, id); try { if (null == id) @@ -445,10 +383,7 @@ internal SqlDependency LookupDependencyEntry(string id) } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" ERROR - dependency ID mismatch - not throwing."); - } + SqlClientEventSource.Log.NotificationsTrace(" ERROR - dependency ID mismatch - not throwing."); } } @@ -463,23 +398,14 @@ internal SqlDependency LookupDependencyEntry(string id) // Remove the dependency from the hashtable with the passed id. private void LookupDependencyEntryWithRemove(string id) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, id: '{1}'", ObjectID, id); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, id: '{1}'", ObjectID, id); try { lock (this) { if (_dependencyIdToDependencyHash.ContainsKey(id)) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Entry found in hashtable - removing."); - } - + SqlClientEventSource.Log.NotificationsTrace(" Entry found in hashtable - removing."); _dependencyIdToDependencyHash.Remove(id); // if there are no more dependencies then we can dispose the timer. @@ -491,10 +417,7 @@ private void LookupDependencyEntryWithRemove(string id) } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Entry NOT found in hashtable."); - } + SqlClientEventSource.Log.NotificationsTrace(" Entry NOT found in hashtable."); } } } @@ -507,12 +430,7 @@ private void LookupDependencyEntryWithRemove(string id) // Find and return arraylist, and remove passed hash value. private List LookupCommandEntryWithRemove(string notificationId) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, commandHash: '{1}'", ObjectID, notificationId); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, commandHash: '{1}'", ObjectID, notificationId); try { DependencyList entry = null; @@ -521,10 +439,7 @@ private List LookupCommandEntryWithRemove(string notificationId) { if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry)) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Entries found in hashtable - removing."); - } + SqlClientEventSource.Log.NotificationsTrace(" Entries found in hashtable - removing."); // update the tables - do it inside finally block to avoid ThreadAbort exception interrupt this operation try @@ -538,10 +453,7 @@ private List LookupCommandEntryWithRemove(string notificationId) } else { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Entries NOT found in hashtable."); - } + SqlClientEventSource.Log.NotificationsTrace(" Entries NOT found in hashtable."); } Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!"); @@ -558,11 +470,8 @@ private List LookupCommandEntryWithRemove(string notificationId) // Remove from commandToDependenciesHash all references to the passed dependency. private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency dependency) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, SqlDependency: {1}#", ObjectID, dependency.ObjectID); - } + + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, SqlDependency: {1}#", ObjectID, dependency.ObjectID); try { @@ -576,11 +485,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende DependencyList dependencies = entry.Value; if (dependencies.Remove(dependency)) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Removed SqlDependency: {0}#, with ID: '{1}'.", dependency.ObjectID, dependency.Id); - } - + SqlClientEventSource.Log.NotificationsTraceEvent(" Removed SqlDependency: {0}#, with ID: '{1}'.", dependency.ObjectID, dependency.Id); if (dependencies.Count == 0) { // this dependency was the last associated with this notification ID, remove the entry @@ -623,12 +528,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende internal void StartTimer(SqlDependency dep) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" {0}#, SqlDependency: {1}#", ObjectID, dep.ObjectID); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, SqlDependency: {1}#", ObjectID, dep.ObjectID); try { // If this dependency expires sooner than the current next timeout, change @@ -639,11 +539,7 @@ internal void StartTimer(SqlDependency dep) // Enable the timer if needed (disable when empty, enable on the first addition). if (!_SqlDependencyTimeOutTimerStarted) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Timer not yet started, starting."); - } - + SqlClientEventSource.Log.NotificationsTrace(" Timer not yet started, starting."); _timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */); // Save this as the earlier timeout to come. @@ -652,10 +548,7 @@ internal void StartTimer(SqlDependency dep) } else if (_nextTimeout > dep.ExpirationTime) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" Timer already started, resetting time."); - } + SqlClientEventSource.Log.NotificationsTrace(" Timer already started, resetting time."); // Save this as the earlier timeout to come. _nextTimeout = dep.ExpirationTime; @@ -670,12 +563,7 @@ internal void StartTimer(SqlDependency dep) private static void TimeoutTimerCallback(object state) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - scopeID = SqlClientEventSource.Log.NotificationsScopeEnter(" AppDomainKey: '{0}'", SqlDependency.AppDomainKey); - } - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" AppDomainKey: '{0}'", SqlDependency.AppDomainKey); try { SqlDependency[] dependencies; @@ -688,18 +576,12 @@ private static void TimeoutTimerCallback(object state) if (0 == SingletonInstance._dependencyIdToDependencyHash.Count) { // Nothing to check. - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" No dependencies, exiting."); - } + SqlClientEventSource.Log.NotificationsTrace(" No dependencies, exiting."); return; } if (SingletonInstance._nextTimeout > DateTime.UtcNow) { - if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) - { - SqlClientEventSource.Log.NotificationsTrace(" No timeouts expired, exiting."); - } + SqlClientEventSource.Log.NotificationsTrace(" No timeouts expired, exiting."); // No dependency timed-out yet. return; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs index a1f2a87334..10ac16d708 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs @@ -41,10 +41,7 @@ internal SqlError(int infoNumber, byte errorState, byte errorClass, string serve this.lineNumber = lineNumber; if (errorClass != 0) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" infoNumber={0}, errorState={1}, errorClass={2}, errorMessage='{3}', procedure='{4}', lineNumber={5}", infoNumber, (int)errorState, (int)errorClass, errorMessage, procedure ?? "None", (int)lineNumber); - } + SqlClientEventSource.Log.TraceEvent(" infoNumber={0}, errorState={1}, errorClass={2}, errorMessage='{3}', procedure='{4}', lineNumber={5}", infoNumber, (int)errorState, (int)errorClass, errorMessage, procedure ?? "None", (int)lineNumber); } this.win32ErrorCode = 0; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index 6facbfa35a..d7079a0dcb 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -313,11 +313,7 @@ override protected DbReferenceCollection CreateReferenceCollection() override protected void Deactivate() { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# deactivating", ObjectID); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}# deactivating", ObjectID); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -439,20 +435,12 @@ protected void Enlist(SysTx.Transaction tx) private void EnlistNonNull(SysTx.Transaction tx) { Debug.Assert(null != tx, "null transaction?"); - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, transaction {1}#.", ObjectID, tx.GetHashCode()); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}#, transaction {1}#.", ObjectID, tx.GetHashCode()); bool hasDelegatedTransaction = false; if (IsYukonOrNewer) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, attempting to delegate", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, attempting to delegate", ObjectID); // Promotable transactions are only supported on Yukon // servers or newer. @@ -518,13 +506,8 @@ private void EnlistNonNull(SysTx.Transaction tx) if (hasDelegatedTransaction) { - this.DelegatedTransaction = delegatedTransaction; - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, delegated to transaction {1}# with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, delegated to transaction {1}# with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); } } catch (SqlException e) @@ -557,11 +540,7 @@ private void EnlistNonNull(SysTx.Transaction tx) if (!hasDelegatedTransaction) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, delegation not possible, enlisting.", ObjectID); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}#, delegation not possible, enlisting.", ObjectID); byte[] cookie = null; if (_isGlobalTransaction) @@ -591,13 +570,7 @@ private void EnlistNonNull(SysTx.Transaction tx) // send cookie to server to finish enlistment PropagateTransactionCookie(cookie); _isEnlistedInTransaction = true; - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - long transactionId = null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId; - int transactionObjectID = null != CurrentTransaction ? CurrentTransaction.ObjectID : 0; - SqlClientEventSource.Log.Trace(" {0}#, enlisted with transaction {1}# with transactionId=0x{2}", ObjectID, transactionObjectID, transactionId); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, enlisted with transaction {1}# with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); } EnlistedTransaction = tx; // Tell the base class about our enlistment @@ -620,10 +593,7 @@ private void EnlistNonNull(SysTx.Transaction tx) internal void EnlistNull() { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, unenlisting.", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, unenlisting.", ObjectID); // We were in a transaction, but now we are not - so send // message to server with empty transaction - confirmed proper @@ -636,16 +606,12 @@ internal void EnlistNull() // that are not affiliated with any transactions. When this // occurs, we will have a new transaction of null and we are // required to send an empty transaction payload to the server. - PropagateTransactionCookie(null); _isEnlistedInTransaction = false; EnlistedTransaction = null; // Tell the base class about our enlistment - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, unenlisted.", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, unenlisted.", ObjectID); // The EnlistTransaction above will return an TransactionEnded event, // which causes the TdsParser or SmiEventSink should to clear the diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs index b97dc0057f..8252977f10 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs @@ -65,55 +65,37 @@ internal EventSink(SqlInternalConnectionSmi connection) internal override void DefaultDatabaseChanged(string databaseName) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, databaseName='{1}'.", _connection.ObjectID, databaseName); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, databaseName='{1}'.", _connection.ObjectID, databaseName); _connection.CurrentDatabase = databaseName; } internal override void TransactionCommitted(long transactionId) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionEnded(transactionId, TransactionState.Committed); } internal override void TransactionDefected(long transactionId) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionEnded(transactionId, TransactionState.Unknown); } internal override void TransactionEnlisted(long transactionId) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionStarted(transactionId, true); // distributed; } internal override void TransactionEnded(long transactionId) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionEndedByServer(transactionId, TransactionState.Unknown); } internal override void TransactionRolledBack(long transactionId) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); // Dev11 1066: ensure delegated transaction is rolled back _connection.TransactionEndedByServer(transactionId, TransactionState.Aborted); @@ -121,10 +103,7 @@ internal override void TransactionRolledBack(long transactionId) internal override void TransactionStarted(long transactionId) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionStarted(transactionId, false); // not distributed; } } @@ -140,11 +119,7 @@ internal SqlInternalConnectionSmi(SqlConnectionString connectionOptions, SmiCont Debug.Assert(null != _smiConnection, "null SmiContext.ContextConnection?"); _smiEventSink = new EventSink(this); - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, constructed new SMI internal connection", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, constructed new SMI internal connection", ObjectID); } internal SmiContext InternalContext @@ -294,11 +269,7 @@ internal void AutomaticEnlistment() SysTx.Transaction currentSystemTransaction = ADP.GetCurrentTransaction(); // NOTE: Must be first to ensure _smiContext.ContextTransaction is set! SysTx.Transaction contextTransaction = _smiContext.ContextTransaction; // returns the transaction that was handed to SysTx that wraps the ContextTransactionId. long contextTransactionId = _smiContext.ContextTransactionId; - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, contextTransactionId=0x{1}, contextTransaction={2}#, currentSystemTransaction={3}#.", ObjectID, contextTransactionId, (null != contextTransaction) ? contextTransaction.GetHashCode() : 0, (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, contextTransactionId=0x{1}, contextTransaction={2}#, currentSystemTransaction={3}#.", ObjectID, contextTransactionId, (null != contextTransaction) ? contextTransaction.GetHashCode() : 0, (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0); if (SqlInternalTransaction.NullTransactionId != contextTransactionId) { @@ -307,28 +278,18 @@ internal void AutomaticEnlistment() throw SQL.NestedTransactionScopesNotSupported(); // can't use TransactionScope(RequiresNew) inside a Sql Transaction. } - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, using context transaction with transactionId=0x{1}", ObjectID, contextTransactionId); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, using context transaction with transactionId=0x{1}", ObjectID, contextTransactionId); _currentTransaction = new SqlInternalTransaction(this, TransactionType.Context, null, contextTransactionId); ContextTransaction = contextTransaction; } else if (null == currentSystemTransaction) { _currentTransaction = null; // there really isn't a transaction. - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, no transaction.", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, no transaction.", ObjectID); } else { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, using current System.Transaction.", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, using current System.Transaction.", ObjectID); base.Enlist(currentSystemTransaction); } } @@ -341,10 +302,7 @@ override protected void ChangeDatabaseInternal(string database) override protected void InternalDeactivate() { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, Deactivating.", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, Deactivating.", ObjectID); // When we put this to bed, we should not hold on to the transaction // or any activity (commit/rollback) may cause it to stop responding. @@ -373,21 +331,13 @@ override protected void InternalDeactivate() override internal void DelegatedTransactionEnded() { base.DelegatedTransactionEnded(); - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, cleaning up after Delegated Transaction Completion", ObjectID); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}#, cleaning up after Delegated Transaction Completion", ObjectID); _currentTransaction = null; // clean up our current transaction too } override internal void DisconnectTransaction(SqlInternalTransaction internalTransaction) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, Disconnecting Transaction {1}#.", ObjectID, internalTransaction.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, Disconnecting Transaction {1}#.", ObjectID, internalTransaction.ObjectID); // VSTS 215465/15029: allow _currentTransaction to be null - it can be cleared before by server's callback Debug.Assert(_currentTransaction == null || _currentTransaction == internalTransaction, "disconnecting different transaction"); @@ -411,11 +361,8 @@ override internal void ExecuteTransaction( SqlInternalTransaction internalTransaction, bool isDelegateControlRequest) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, transactionRequest={1}, " + - "transactionName='{2}', isolationLevel={3}, internalTransaction=#{4} transactionId=0x{5}.", ObjectID, transactionRequest.ToString(), transactionName ?? "null", iso.ToString(), (null != internalTransaction) ? internalTransaction.ObjectID : 0, (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, transactionRequest={1}, " + + "transactionName='{2}', isolationLevel={3}, internalTransaction=#{4} transactionId=0x{5}.", ObjectID, transactionRequest.ToString(), transactionName ?? "null", iso.ToString(), (null != internalTransaction) ? internalTransaction.ObjectID : 0, (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); switch (transactionRequest) { @@ -470,17 +417,15 @@ override protected byte[] GetDTCAddress() _smiEventSink.ProcessMessagesAndThrow(); - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + if (null != whereAbouts) { - if (null != whereAbouts) - { - SqlClientEventSource.Log.TraceBin(" whereAbouts", whereAbouts, (ushort)whereAbouts.Length); - } - else - { - SqlClientEventSource.Log.Trace(" whereAbouts=null"); - } + SqlClientEventSource.Log.AdvanceTrace(" whereAbouts = {0}, Length = {1}", whereAbouts, (ushort)whereAbouts.Length); } + else + { + SqlClientEventSource.Log.AdvanceTrace(" whereAbouts=null"); + } + return whereAbouts; } @@ -504,10 +449,7 @@ private void OnOutOfScope(object s, EventArgs e) // Called whenever the context goes out of scope, we need to make // sure that we close the connection, or the next person that uses // the context may appear to have the connection in use. - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# context is out of scope", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# context is out of scope", ObjectID); // TODO: This is suspect to me -- if I go out of scope, who will commit the transaction? DelegatedTransaction = null; // we don't want to hold this over to the next usage; it will automatically be reused as the context transaction... @@ -535,16 +477,14 @@ private void OnOutOfScope(object s, EventArgs e) override protected void PropagateTransactionCookie(byte[] transactionCookie) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + + if (null != transactionCookie) { - if (null != transactionCookie) - { - SqlClientEventSource.Log.TraceBin(" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); - } - else - { - SqlClientEventSource.Log.Trace(" null"); - } + SqlClientEventSource.Log.AdvanceTrace(" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); + } + else + { + SqlClientEventSource.Log.AdvanceTrace(" null"); } // Propagate the transaction cookie to the server diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs index 00fc01bbd3..81a8ec8642 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs @@ -516,10 +516,7 @@ internal SqlInternalConnectionTds( ThreadHasParserLockForClose = false; _parserLock.Release(); } - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, constructed new TDS internal connection", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, constructed new TDS internal connection", ObjectID); } // The erros in the transient error set are contained in @@ -774,11 +771,7 @@ override protected void ChangeDatabaseInternal(string database) override public void Dispose() { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# disposing", ObjectID); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}# disposing", ObjectID); try { TdsParser parser = Interlocked.Exchange(ref _parser, null); // guard against multiple concurrent dispose calls -- Delegated Transactions might cause this. @@ -1369,19 +1362,12 @@ private void CompleteLogin(bool enlistOK) { // ROR should not affect state of connection recovery if (_federatedAuthenticationRequested && !_federatedAuthenticationAcknowledged) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Server did not acknowledge the federated authentication request", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Server did not acknowledge the federated authentication request", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged); } if (_federatedAuthenticationInfoRequested && !_federatedAuthenticationInfoReceived) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Server never sent the requested federated authentication info", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Server never sent the requested federated authentication info", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoNotReceived); } @@ -1419,11 +1405,7 @@ private void CompleteLogin(bool enlistOK) _parser.EnableMars(); _fConnectionOpen = true; // mark connection as open - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" Post-Login Phase: Server connection obtained."); - } + SqlClientEventSource.Log.AdvanceTrace(" Post-Login Phase: Server connection obtained."); // for non-pooled connections, enlist in a distributed transaction // if present - and user specified to enlist @@ -1552,10 +1534,7 @@ private void Login(ServerInfo server, TimeoutTimer timeout, string newPassword, private void LoginFailure() { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); // If the parser was allocated and we failed, then we must have failed on // either the Connect or Login, either way we should call Disconnect. @@ -1681,10 +1660,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt int routingAttempts = 0; ServerInfo originalServerInfo = serverInfo; // serverInfo may end up pointing to new object due to routing, original object is used to set CurrentDatasource - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, host={1}", ObjectID, serverInfo.UserServerName); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, host={1}", ObjectID, serverInfo.UserServerName); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. @@ -1790,10 +1766,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt if (_routingInfo != null) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Routed to {0}", serverInfo.ExtendedServerName); - } + SqlClientEventSource.Log.TraceEvent(" Routed to {0}", serverInfo.ExtendedServerName); if (routingAttempts > _maxNumberOfRedirectRoute) { @@ -1882,10 +1855,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt // Sleep for a bit to prevent clogging the network with requests, // then update sleep interval for next iteration (max 1 second interval) - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, sleeping {1}[milisec]", ObjectID, sleepInterval); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; @@ -1967,11 +1937,7 @@ TimeoutTimer timeout { Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used"); - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, useFailover={1}[bool], primary={2}, failover={failoverHost}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, useFailover={1}[bool], primary={2}, failover={failoverHost}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. long timeoutUnitInterval; @@ -2039,10 +2005,7 @@ TimeoutTimer timeout // Primary server may give us a different failover partner than the connection string indicates. Update it if (null != ServerProvidedFailOverPartner && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); failoverServerInfo.SetDerivedNames(protocol, ServerProvidedFailOverPartner); } currentServerInfo = failoverServerInfo; @@ -2075,10 +2038,7 @@ TimeoutTimer timeout } routingAttempts++; - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Routed to {0}", _routingInfo.ServerName); - } + SqlClientEventSource.Log.TraceEvent(" Routed to {0}", _routingInfo.ServerName); if (_parser != null) _parser.Disconnect(); @@ -2147,11 +2107,7 @@ TimeoutTimer timeout // the network with requests, then update sleep interval for next iteration (max 1 second interval) if (1 == attemptNumber % 2) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, sleeping {1}[milisec]", ObjectID, sleepInterval); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}#, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } @@ -2226,10 +2182,7 @@ private void ResolveExtendedServerName(ServerInfo serverInfo, bool aliasLookup, // Common code path for making one attempt to establish a connection and log in to server. private void AttemptOneLogin(ServerInfo serverInfo, string newPassword, SecureString newSecurePassword, bool ignoreSniOpenTimeout, TimeoutTimer timeout, bool withFailover = false, bool isFirstTransparentAttempt = true, bool disableTnir = false) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); _routingInfo = null; // forget routing information @@ -2380,13 +2333,10 @@ internal bool GetSessionAndReconnectIfNeeded(SqlConnection parent, int timeout = internal void BreakConnection() { - var connection = Connection; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Breaking connection.", ObjectID); - } + SqlConnection connection = Connection; + SqlClientEventSource.Log.TraceEvent(" {0}#, Breaking connection.", ObjectID); DoomThisConnection(); // Mark connection as unusable, so it will be destroyed + if (null != connection) { connection.Close(); @@ -2476,12 +2426,7 @@ internal void OnEnvChange(SqlEnvChange rec) break; case TdsEnums.ENV_ROUTING: - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Received routing info", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Received routing info", ObjectID); if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0) { throw SQL.ROR_InvalidRoutingInfo(this); @@ -2525,12 +2470,7 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) "Credentials aren't provided for calling MSAL"); Debug.Assert(fedAuthInfo != null, "info should not be null."); Debug.Assert(_dbConnectionPoolAuthenticationContextKey == null, "_dbConnectionPoolAuthenticationContextKey should be null."); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Generating federated authentication token", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Generating federated authentication token", ObjectID); DbConnectionPoolAuthenticationContext dbConnectionPoolAuthenticationContext = null; // We want to refresh the token without taking a lock on the context, allowed when the access token is expiring within the next 10 mins. @@ -2561,12 +2501,9 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // And on successful login, try to update the cache with the new token. if (contextValidity <= _dbAuthenticationContextUnLockedRefreshTimeSpan) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, " + - "The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + - "The expiration time is {1}. Current Time is {DateTime.UtcNow.ToLongTimeString()}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, " + + "The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + + "The expiration time is {1}. Current Time is {DateTime.UtcNow.ToLongTimeString()}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()); attemptRefreshTokenUnLocked = true; } @@ -2587,12 +2524,9 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // If a thread is already doing the refresh, just use the existing token in the cache and proceed. else if (contextValidity <= _dbAuthenticationContextLockedRefreshTimeSpan) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, " + - "The authentication context needs a refresh.The expiration time is {1}. " + - "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, " + + "The authentication context needs a refresh.The expiration time is {1}. " + + "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); // Call the function which tries to acquire a lock over the authentication context before trying to update. // If the lock could not be obtained, it will return false, without attempting to fetch a new token. @@ -2606,17 +2540,11 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // Indicate in Bid Trace that we are successful with the update. if (attemptRefreshTokenLocked) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" %d#, The attempt to get a new access token succeeded under the locked mode."); - } + SqlClientEventSource.Log.TraceEvent(" %d#, The attempt to get a new access token succeeded under the locked mode."); } } - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); } } @@ -2676,21 +2604,15 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP // Else some other thread is already updating it, so just proceed forward with the existing token in the cache. if (dbConnectionPoolAuthenticationContext.LockToUpdate()) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, " + - "Acquired the lock to update the authentication context.The expiration time is {1}. " + - "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, " + + "Acquired the lock to update the authentication context.The expiration time is {1}. " + + "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); authenticationContextLocked = true; } else { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {}#, Refreshing the context is already in progress by another thread.", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {}#, Refreshing the context is already in progress by another thread.", ObjectID); } if (authenticationContextLocked) @@ -2848,10 +2770,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) || _timeout.IsExpired || _timeout.MillisecondsRemaining <= sleepInterval) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#", msalException.ErrorCode); - } + SqlClientEventSource.Log.TraceEvent(" {0}#", msalException.ErrorCode); // Error[0] SqlErrorCollection sqlErs = new SqlErrorCollection(); @@ -2870,11 +2789,8 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) throw exc; } - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); - SqlClientEventSource.Log.Trace(" {0}#, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); Thread.Sleep(sleepInterval); sleepInterval *= 2; @@ -2890,12 +2806,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) DateTime expirationTime = DateTime.FromFileTimeUtc(fedAuthToken.expirationFileTime); _newDbConnectionPoolAuthenticationContext = new DbConnectionPoolAuthenticationContext(fedAuthToken.accessToken, expirationTime); } - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Finished generating federated authentication token.", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Finished generating federated authentication token.", ObjectID); return fedAuthToken; } @@ -2958,18 +2869,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_FEDAUTH: { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Received feature extension acknowledgement for federated authentication", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Received feature extension acknowledgement for federated authentication", ObjectID); if (!_federatedAuthenticationRequested) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Did not request federated authentication", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Did not request federated authentication", ObjectID); throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); } @@ -2982,22 +2886,16 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // The server shouldn't have sent any additional data with the ack (like a nonce) if (data.Length != 0) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, " + - "Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, " + + "Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthFeatureAckContainsExtraData); } break; default: Debug.Fail("Unknown _fedAuthLibrary type"); - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Attempting to use unknown federated authentication library", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Attempting to use unknown federated authentication library", ObjectID); throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType); } _federatedAuthenticationAcknowledged = true; @@ -3013,17 +2911,14 @@ internal void OnFeatureExtAck(int featureId, byte[] data) Debug.Assert(newAuthenticationContextInCacheAfterAddOrUpdate != null, "newAuthenticationContextInCacheAfterAddOrUpdate should not be null."); #if DEBUG - if (SqlClientEventSource.Log.IsTraceEnabled()) + // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. + if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) { - // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. - if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) - { - SqlClientEventSource.Log.Trace(" {0}#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); - } - else - { - SqlClientEventSource.Log.Trace(" {0}#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); + } + else + { + SqlClientEventSource.Log.TraceEvent(" {0}#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); } #endif } @@ -3032,28 +2927,17 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_TCE: { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Received feature extension acknowledgement for TCE", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Received feature extension acknowledgement for TCE", ObjectID); if (data.Length < 1) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Unknown version number for TCE", ObjectID); - } - + SqlClientEventSource.Log.TraceEvent(" {0}#, Unknown version number for TCE", ObjectID); throw SQL.ParsingError(ParsingErrorState.TceUnknownVersion); } byte supportedTceVersion = data[0]; if (0 == supportedTceVersion || supportedTceVersion > TdsEnums.MAX_SUPPORTED_TCE_VERSION) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Invalid version number for TCE", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Invalid version number for TCE", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidVersion, supportedTceVersion); } @@ -3072,17 +2956,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS: { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Received feature extension acknowledgement for GlobalTransactions", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Received feature extension acknowledgement for GlobalTransactions", ObjectID); if (data.Length < 1) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Unknown version number for GlobalTransactions", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Unknown version number for GlobalTransactions", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } @@ -3097,18 +2975,10 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_AZURESQLSUPPORT: { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Received feature extension acknowledgement for AzureSQLSupport", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Received feature extension acknowledgement for AzureSQLSupport", ObjectID); if (data.Length < 1) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Unknown token for AzureSQLSupport", ObjectID); - } - throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } @@ -3117,43 +2987,31 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // Bit 0 for RO/FP support if ((data[0] & 1) == 1 && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.Trace(" {0}#, FailoverPartner enabled with Readonly intent for AzureSQL DB", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, FailoverPartner enabled with Readonly intent for AzureSQL DB", ObjectID); } break; } case TdsEnums.FEATUREEXT_DATACLASSIFICATION: { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); if (data.Length < 1) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Unknown token for DATACLASSIFICATION", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte supportedDataClassificationVersion = data[0]; if ((0 == supportedDataClassificationVersion) || (supportedDataClassificationVersion > TdsEnums.MAX_SUPPORTED_DATA_CLASSIFICATION_VERSION)) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Invalid version number for DATACLASSIFICATION", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Invalid version number for DATACLASSIFICATION", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.DataClassificationInvalidVersion, supportedDataClassificationVersion); } if (data.Length != 2) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Unknown token for DATACLASSIFICATION", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte enabled = data[1]; @@ -3163,17 +3021,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_UTF8SUPPORT: { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Received feature extension acknowledgement for UTF8 support", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Received feature extension acknowledgement for UTF8 support", ObjectID); if (data.Length < 1) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, Unknown value for UTF8 support", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, Unknown value for UTF8 support", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } break; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs index 987b3eb0d3..b42c28ba05 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -142,17 +142,8 @@ override public void Commit() ZombieCheck(); SqlStatistics statistics = null; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -276,11 +267,8 @@ override public void Rollback() { if (IsYukonPartialZombie) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - // Put something in the trace in case a customer has an issue - SqlClientEventSource.Log.Trace(" {0}# partial zombie no rollback required", ObjectID); - } + // Put something in the trace in case a customer has an issue + SqlClientEventSource.Log.AdvanceTrace(" {0}# partial zombie no rollback required", ObjectID); _internalTransaction = null; // yukon zombification } @@ -289,17 +277,8 @@ override public void Rollback() ZombieCheck(); SqlStatistics statistics = null; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - - if (SqlClientEventSource.Log.IsCorrelationEnabled()) - { - SqlClientEventSource.Log.CorrelationTrace(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -363,13 +342,7 @@ public void Rollback(string transactionName) ZombieCheck(); SqlStatistics statistics = null; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}# transactionName='{1}'", ObjectID, transactionName); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}# transactionName='{1}'", ObjectID, transactionName); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -431,12 +404,7 @@ public void Save(string savePointName) ZombieCheck(); SqlStatistics statistics = null; - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}# savePointName='{1}'", ObjectID, savePointName); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}# savePointName='{1}'", ObjectID, savePointName); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -502,10 +470,7 @@ internal void Zombie() if (null != internalConnection && internalConnection.IsYukonOrNewer && !_isFromAPI) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# yukon deferred zombie", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# yukon deferred zombie", ObjectID); } else { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index 1481862733..0bcd2e1696 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -502,42 +502,27 @@ internal void Connect(ServerInfo serverInfo, LoadSSPILibrary(); // now allocate proper length of buffer _sniSpnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength]; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication"); - } + SqlClientEventSource.Log.TraceEvent(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication", "SEC"); } else { _sniSpnBuffer = null; if (authType == SqlAuthenticationMethod.ActiveDirectoryPassword) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Active Directory Password authentication"); - } + SqlClientEventSource.Log.TraceEvent(" Active Directory Password authentication", "SEC"); } else if (authType == SqlAuthenticationMethod.SqlPassword) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" SQL Password authentication"); - } + + SqlClientEventSource.Log.TraceEvent(" SQL Password authentication", "SEC"); } else if (authType == SqlAuthenticationMethod.ActiveDirectoryInteractive) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Active Directory Interactive authentication"); - } + SqlClientEventSource.Log.TraceEvent(" Active Directory Interactive authentication", "SEC"); } else { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" SQL authentication"); - } + SqlClientEventSource.Log.TraceEvent(" SQL authentication", "SEC"); } } @@ -574,12 +559,7 @@ internal void Connect(ServerInfo serverInfo, // don't, the memory for the connection object might not be accurate and thus // a bad error could be returned (as it was when it was freed to early for me). _physicalStateObj.Dispose(); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Login failure"); - } - + SqlClientEventSource.Log.TraceEvent(" Login failure", "ERR|SEC"); ThrowExceptionAndWarning(_physicalStateObj); Debug.Fail("SNI returned status != success, but no error thrown?"); } @@ -609,32 +589,21 @@ internal void Connect(ServerInfo serverInfo, Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); // UNDONE - send "" for instance now, need to fix later - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Sending prelogin handshake"); - } - + SqlClientEventSource.Log.TraceEvent(" Sending prelogin handshake", "SEC"); SendPreLoginHandshake(instanceName, encrypt, !string.IsNullOrEmpty(certificate), useOriginalAddressInfo); _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake); _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake); _physicalStateObj.SniContext = SniContext.Snix_PreLogin; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Consuming prelogin handshake"); - } + SqlClientEventSource.Log.TraceEvent(" Consuming prelogin handshake", "SEC"); PreLoginHandshakeStatus status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, out marsCapable, out _connHandler._fedAuthRequired); if (status == PreLoginHandshakeStatus.InstanceFailure) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Prelogin handshake unsuccessful. Reattempting prelogin handshake"); - } + SqlClientEventSource.Log.TraceEvent(" Prelogin handshake unsuccessful. Reattempting prelogin handshake", "SEC"); _physicalStateObj.Dispose(); // Close previous connection // On Instance failure re-connect and flush SNI named instance cache. @@ -644,21 +613,14 @@ internal void Connect(ServerInfo serverInfo, if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); + SqlClientEventSource.Log.TraceEvent(" Login failure", "ERR|SEC"); - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Login failure"); - } ThrowExceptionAndWarning(_physicalStateObj); } UInt32 retCode = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId); Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Sending prelogin handshake"); - } + SqlClientEventSource.Log.TraceEvent(" Sending prelogin handshake", "SEC"); SendPreLoginHandshake(instanceName, encrypt, !string.IsNullOrEmpty(certificate), useOriginalAddressInfo); status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, out marsCapable, @@ -668,18 +630,11 @@ internal void Connect(ServerInfo serverInfo, // one pre-login packet and know we are connecting to Shiloh. if (status == PreLoginHandshakeStatus.InstanceFailure) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Prelogin handshake unsuccessful. Login failure"); - } + SqlClientEventSource.Log.TraceEvent(" Prelogin handshake unsuccessful. Login failure", "ERR|SEC"); throw SQL.InstanceFailure(); } } - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Prelogin handshake successful"); - } + SqlClientEventSource.Log.TraceEvent(" Prelogin handshake successful", "SEC"); if (_fMARS && marsCapable) { @@ -771,12 +726,7 @@ internal void EnableMars() internal TdsParserStateObject CreateSession() { TdsParserStateObject session = new TdsParserStateObject(this, (SNIHandle)_pMarsPhysicalConObj.Handle, true); - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# created session {1}", ObjectID, session.ObjectID); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}# created session {1}", ObjectID, session.ObjectID); return session; } @@ -791,19 +741,12 @@ internal TdsParserStateObject GetSession(object owner) session = _sessionPool.GetSession(owner); Debug.Assert(!session._pendingData, "pending data on a pooled MARS session"); - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# getting session {1} from pool", ObjectID, session.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# getting session {1} from pool", ObjectID, session.ObjectID); } else { session = _physicalStateObj; - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# getting physical session {1}", ObjectID, session.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# getting physical session {1}", ObjectID, session.ObjectID); } Debug.Assert(session._outputPacketNumber == 1, "The packet number is expected to be 1"); return session; @@ -1018,10 +961,7 @@ private void SendPreLoginHandshake(byte[] instanceName, bool encrypt, bool clien offset += actIdSize; optionDataSize += actIdSize; - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" ClientConnectionID {0}, ActivityID {1}", _connHandler._clientConnectionId.ToString(), actId.ToString()); - } + SqlClientEventSource.Log.TraceEvent(" ClientConnectionID {0}, ActivityID {1}", _connHandler._clientConnectionId.ToString(), actId.ToString()); break; case (int)PreLoginOptions.FEDAUTHREQUIRED: @@ -1332,11 +1272,8 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod // Only 0x00 and 0x01 are accepted values from the server. if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, " + - "Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {1}.", ObjectID, (int)payload[payloadOffset]); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, " + + "Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {1}.", ObjectID, (int)payload[payloadOffset]); throw SQL.ParsingErrorValue(ParsingErrorState.FedAuthRequiredPreLoginResponseInvalidValue, (int)payload[payloadOffset]); } @@ -1377,14 +1314,9 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod internal void Deactivate(bool connectionIsDoomed) { // Called when the connection that owns us is deactivated. - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# deactivating", ObjectID); - } - if (SqlClientEventSource.Log.IsStateDumpEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, {1}", ObjectID, TraceString()); - } + + SqlClientEventSource.Log.AdvanceTrace(" {0}# deactivating", ObjectID); + SqlClientEventSource.Log.StateDumpEvent(" {0}#, {1}", ObjectID, TraceString()); if (MARSOn) { @@ -1540,10 +1472,7 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle Debug.Assert(temp.Count > 0, "TdsParser::ThrowExceptionAndWarning called with no exceptions or warnings!"); if (temp.Count == 0) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {0}#", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {0}#", ObjectID); } Debug.Assert(_connHandler != null, "TdsParser::ThrowExceptionAndWarning called with null connectionHandler!"); @@ -2262,11 +2191,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead Debug.Fail($"unexpected token; token = {token,-2:X2}"); _state = TdsParserState.Broken; _connHandler.BreakConnection(); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Potential multi-threaded misuse of connection, unexpected TDS token found {0}#", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, unexpected TDS token found {0}#", ObjectID); throw SQL.ParsingErrorToken(ParsingErrorState.InvalidTdsTokenReceived, token); // MDAC 82443 } @@ -2588,10 +2513,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead } case TdsEnums.SQLLOGINACK: { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Received login acknowledgement token"); - } + SqlClientEventSource.Log.TraceEvent(" Received login acknowledgement token", "SEC"); SqlLoginAck ack; if (!TryProcessLoginAck(stateObj, out ack)) @@ -2614,11 +2536,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead { _connHandler._federatedAuthenticationInfoReceived = true; SqlFedAuthInfo info; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Received federated authentication info token"); - } + SqlClientEventSource.Log.TraceEvent(" Received federated authentication info token", "SEC"); if (!TryProcessFedAuthInfo(stateObj, tokenLength, out info)) { @@ -4032,18 +3950,12 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, SqlFedAuthInfo tempFedAuthInfo = new SqlFedAuthInfo(); // Skip reading token length, since it has already been read in caller - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" FEDAUTHINFO token stream length = {0}", tokenLen); - } + SqlClientEventSource.Log.AdvanceTrace(" FEDAUTHINFO token stream length = {0}", tokenLen); if (tokenLen < sizeof(uint)) { // the token must at least contain a DWORD indicating the number of info IDs - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); - } + SqlClientEventSource.Log.AdvanceTrace(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen); } @@ -4051,18 +3963,13 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, uint optionsCount; if (!stateObj.TryReadUInt32(out optionsCount)) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream."); - } + + SqlClientEventSource.Log.TraceEvent(" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadCountOfInfoIds); } - tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); - } + tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount + SqlClientEventSource.Log.TraceEvent(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); if (tokenLen > 0) { @@ -4071,17 +3978,11 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, int totalRead = 0; bool successfulRead = stateObj.TryReadByteArray(tokenData, 0, tokenLen, out totalRead); - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); - } + SqlClientEventSource.Log.TraceEvent(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); if (!successfulRead || totalRead != tokenLen) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}", tokenLen, totalRead); - } + SqlClientEventSource.Log.TraceEvent(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}", tokenLen, totalRead); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadTokenStream); } @@ -4102,11 +4003,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, byte id = tokenData[currentOptionOffset]; uint dataLen = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 1))); uint dataOffset = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 5))); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture)); - } + SqlClientEventSource.Log.TraceEvent(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture)); // offset is measured from optCount, so subtract to make offset measured // from the beginning of tokenData @@ -4118,10 +4015,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, // if dataOffset points to a region within FedAuthInfoOpt or after the end of the token, throw if (dataOffset < totalOptionsSize || dataOffset >= tokenLen) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" FedAuthInfoDataOffset points to an invalid location."); - } + SqlClientEventSource.Log.TraceEvent(" FedAuthInfoDataOffset points to an invalid location.", "ERR"); throw SQL.ParsingErrorOffset(ParsingErrorState.FedAuthInfoInvalidOffset, unchecked((int)dataOffset)); } @@ -4133,25 +4027,15 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } catch (ArgumentOutOfRangeException e) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Failed to read FedAuthInfoData."); - } + SqlClientEventSource.Log.TraceEvent(" Failed to read FedAuthInfoData.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadData, e); } catch (ArgumentException e) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" FedAuthInfoData is not in unicode format."); - } + SqlClientEventSource.Log.TraceEvent(" FedAuthInfoData is not in unicode format.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e); } - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" FedAuthInfoData: {0}", data); - } + SqlClientEventSource.Log.TraceEvent(" FedAuthInfoData: {0}", data); // store data in tempFedAuthInfo switch ((TdsEnums.FedAuthInfoId)id) @@ -4163,35 +4047,22 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, tempFedAuthInfo.stsurl = data; break; default: - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" Ignoring unknown federated authentication info option: {0}", id); - } + SqlClientEventSource.Log.TraceEvent(" Ignoring unknown federated authentication info option: {0}", id); break; } } } else { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" FEDAUTHINFO token stream is not long enough to contain the data it claims to."); - } + SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream is not long enough to contain the data it claims to.", "ERR"); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForData, tokenLen); } - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Processed FEDAUTHINFO token stream: {0}", tempFedAuthInfo.ToString()); - } - + SqlClientEventSource.Log.TraceEvent(" Processed FEDAUTHINFO token stream: {0}", tempFedAuthInfo.ToString()); if (string.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || string.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) { // We should be receiving both stsurl and spn - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" FEDAUTHINFO token stream does not contain both STSURL and SPN."); - } + SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream does not contain both STSURL and SPN.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDoesNotContainStsurlAndSpn); } @@ -4620,10 +4491,7 @@ internal bool TryProcessTceCryptoMetadata(TdsParserStateObject stateObj, // validate the index (ordinal passed) if (index >= cipherTable.Value.Size) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Incorrect ordinal received {0}, max tab size: {1}", index, cipherTable.Value.Size); - } + SqlClientEventSource.Log.TraceEvent(" Incorrect ordinal received {0}, max tab size: {1}", index, cipherTable.Value.Size); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidOrdinalIntoCipherInfoTable, index); } } @@ -8890,11 +8758,7 @@ internal void TdsLogin(SqlLogin rec, } WriteInt(log7Flags, _physicalStateObj); - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, TDS Login7 flags = {1}:", ObjectID, log7Flags); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, TDS Login7 flags = {1}:", ObjectID, log7Flags); WriteInt(0, _physicalStateObj); // ClientTimeZone is not used WriteInt(0, _physicalStateObj); // LCID is unused by server @@ -9053,10 +8917,7 @@ internal void TdsLogin(SqlLogin rec, }; if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Sending federated authentication feature request"); - } + SqlClientEventSource.Log.TraceEvent(" Sending federated authentication feature request", "SEC"); Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null."); WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true); }; @@ -9129,11 +8990,7 @@ internal void SendFedAuthToken(SqlFedAuthToken fedAuthToken) { Debug.Assert(fedAuthToken != null, "fedAuthToken cannot be null"); Debug.Assert(fedAuthToken.accessToken != null, "fedAuthToken.accessToken cannot be null"); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Sending federated authentication token"); - } + SqlClientEventSource.Log.TraceEvent(" Sending federated authentication token", "SEC"); _physicalStateObj._outputMessageType = TdsEnums.MT_FEDAUTH; @@ -9524,11 +9381,7 @@ internal SqlDataReader TdsExecuteTransactionManagerRequest( internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) { int old_outputPacketNumber = stateObj._outputPacketNumber; - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Exception caught on ExecuteXXX: '{0}'", e.ToString()); - } + SqlClientEventSource.Log.TraceEvent(" Exception caught on ExecuteXXX: '{0}'", e.ToString()); if (stateObj.HasOpenResult) { // SQL BU DT 383773 - need to decrement openResultCount if operation failed. @@ -9561,11 +9414,7 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) _connHandler.ThreadHasParserLockForClose = originalThreadHasParserLock; } } - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Exception rethrown."); - } + SqlClientEventSource.Log.TraceEvent(" Exception rethrown.", "ERR"); } internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, bool sync, bool callerHasConnectionLock = false, byte[] enclavePackage = null) @@ -9621,10 +9470,7 @@ internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationReques stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}#", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}#", ObjectID); } stateObj.SniContext = SniContext.Snix_Execute; @@ -9753,10 +9599,7 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}#", ObjectID); - } + SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}#", ObjectID); } stateObj.SniContext = SniContext.Snix_Execute; @@ -10620,11 +10463,7 @@ private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefa } var sendDefaultValue = sendDefault ? 1 : 0; - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); // // Write parameter metadata @@ -11680,7 +11519,7 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio Debug.Assert(-1 <= timeout, "Timeout"); - SqlClientEventSource.Log.NotificationsTrace(" NotificationRequest: userData: '{0}', options: '{1}', timeout: '{2}'", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); + SqlClientEventSource.Log.NotificationsTraceEvent(" NotificationRequest: userData: '{0}', options: '{1}', timeout: '{2}'", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj); // Query notifications Type @@ -11707,10 +11546,7 @@ private void WriteTraceHeaderData(TdsParserStateObject stateObj) stateObj.WriteByteArray(actId.Id.ToByteArray(), GUID_SIZE, 0); // Id (Guid) WriteUnsignedInt(actId.Sequence, stateObj); // sequence number - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" ActivityID {0}", actId.ToString()); - } + SqlClientEventSource.Log.TraceEvent(" ActivityID {0}", actId.ToString()); } private void WriteRPCBatchHeaders(TdsParserStateObject stateObj, SqlNotificationRequest notificationRequest) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index 9efc9af57c..f8e88d525d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -36,11 +36,7 @@ internal TdsParserSessionPool(TdsParser parser) _cache = new List(); _freeStateObjects = new TdsParserStateObject[MaxInactiveCount]; _freeStateObjectCount = 0; - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# created session pool for parser {1}", ObjectID, parser.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# created session pool for parser {1}", ObjectID, parser.ObjectID); } private bool IsDisposed @@ -64,13 +60,7 @@ internal void Deactivate() // When being deactivated, we check all the sessions in the // cache to make sure they're cleaned up and then we dispose of // sessions that are past what we want to keep around. - - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}# deactivating cachedCount={1}", ObjectID, _cachedCount); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}# deactivating cachedCount={1}", ObjectID, _cachedCount); try { lock (_cache) @@ -89,12 +79,7 @@ internal void Deactivate() if (session.IsOrphaned) { // TODO: consider adding a performance counter for the number of sessions we reclaim - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# reclaiming session {1}", ObjectID, session.ObjectID); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}# reclaiming session {1}", ObjectID, session.ObjectID); PutSession(session); } } @@ -128,11 +113,7 @@ internal void BestEffortCleanup() internal void Dispose() { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# disposing cachedCount={1}", ObjectID, _cachedCount); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}# disposing cachedCount={1}", ObjectID, _cachedCount); lock (_cache) { // Dispose free sessions @@ -191,11 +172,7 @@ internal TdsParserStateObject GetSession(object owner) { // No free objects, create a new one session = _parser.CreateSession(); - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# adding session {1} to pool", ObjectID, session.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# adding session {1} to pool", ObjectID, session.ObjectID); _cache.Add(session); _cachedCount = _cache.Count; @@ -203,12 +180,7 @@ internal TdsParserStateObject GetSession(object owner) session.Activate(owner); } - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# using session {1}", ObjectID, session.ObjectID); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}# using session {1}", ObjectID, session.ObjectID); return session; } @@ -230,11 +202,7 @@ internal void PutSession(TdsParserStateObject session) else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount)) { // Session is good to re-use and our cache has space - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# keeping session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}# keeping session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); Debug.Assert(!session._pendingData, "pending data on a pooled session?"); _freeStateObjects[_freeStateObjectCount] = session; @@ -243,10 +211,7 @@ internal void PutSession(TdsParserStateObject session) else { // Either the session is bad, or we have no cache space - so dispose the session and remove it - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}# disposing session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# disposing session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); bool removed = _cache.Remove(session); Debug.Assert(removed, "session not in pool?"); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index 73b11e1f3d..bf115e3d96 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -559,12 +559,8 @@ internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount) { return false; } - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" {0}#, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount); - SqlClientEventSource.Log.TraceBin(" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); - } + SqlClientEventSource.Log.TraceEvent(" {0}#, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount); + SqlClientEventSource.Log.TraceBinEvent(" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); return true; } @@ -917,18 +913,11 @@ internal void DecrementOpenResultCount() internal int DecrementPendingCallbacks(bool release) { int remaining = Interlocked.Decrement(ref _pendingCallbacks); - - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); if ((0 == remaining || release) && _gcHandle.IsAllocated) { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, FREEING HANDLE!", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, FREEING HANDLE!", ObjectID); _gcHandle.Free(); } @@ -1037,11 +1026,7 @@ internal int IncrementPendingCallbacks() { int remaining = Interlocked.Increment(ref _pendingCallbacks); - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}#, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}"); return remaining; } @@ -2174,10 +2159,7 @@ internal bool TryReadNetworkPacket() _snapshot.CheckStack(new StackTrace()); } #endif - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Async packet replay"); - } + SqlClientEventSource.Log.TraceEvent(" Async packet replay{0}", "INFO"); return true; } #if DEBUG @@ -2599,10 +2581,8 @@ internal bool IsConnectionAlive(bool throwOnException) if ((error != TdsEnums.SNI_SUCCESS) && (error != TdsEnums.SNI_WAIT_TIMEOUT)) { // Connection is dead - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" received error {0} on idle connection", (int)error); - } + SqlClientEventSource.Log.TraceEvent(" received error {0} on idle connection", (int)error); + isAlive = false; if (throwOnException) { @@ -2815,14 +2795,8 @@ public void ProcessSniPacket(IntPtr packet, UInt32 error) #endif } } - SniReadStatisticsAndTracing(); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.TraceBin(" Packet read", _inBuff, (UInt16)_inBytesRead); - } - + SqlClientEventSource.Log.TraceBinEvent(" Packet read", _inBuff, (ushort)_inBytesRead); AssertValidState(); } else @@ -2979,11 +2953,7 @@ public void WriteAsyncCallback(IntPtr key, IntPtr packet, UInt32 sniError) { if (sniError != TdsEnums.SNI_SUCCESS) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" write async returned error code {0}", (int)sniError); - } - + SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)sniError); try { AddError(_parser.ProcessSNIError(this)); @@ -3451,10 +3421,8 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr if (error != TdsEnums.SNI_SUCCESS) { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" write async returned error code {0}", (int)error); - } + SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)error); + AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(); } @@ -3491,10 +3459,7 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr } else { - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" write async returned error code {0}", (int)sniError); - } + SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)sniError); AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(callerHasConnectionLock); } @@ -3554,11 +3519,7 @@ internal void SendAttention(bool mustTakeWriteLock = false) UInt32 sniError; _parser._asyncWrite = false; // stop async write SNIWritePacket(Handle, attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Send Attention ASync."); - } + SqlClientEventSource.Log.TraceEvent(" Send Attention ASync.", "Info"); } finally { @@ -3581,12 +3542,8 @@ internal void SendAttention(bool mustTakeWriteLock = false) _attentionSending = false; } - SqlClientEventSource.Log.TraceBin(" Packet sent", _outBuff, (ushort)_outBytesUsed); - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.Trace(" Attention sent to the server."); - } + SqlClientEventSource.Log.TraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); + SqlClientEventSource.Log.TraceEvent(" Attention sent to the server.", "Info"); AssertValidState(); } @@ -3770,11 +3727,7 @@ private void SniWriteStatisticsAndTracing() _traceChangePasswordOffset = 0; _traceChangePasswordLength = 0; } - - if (SqlClientEventSource.Log.IsTraceEnabled()) - { - SqlClientEventSource.Log.TraceBin(" Packet sent", _outBuff, (ushort)_outBytesUsed); - } + SqlClientEventSource.Log.TraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); } [Conditional("DEBUG")] diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs index 28909a4981..afb16a65ef 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs @@ -53,10 +53,7 @@ internal SqlInternalTransaction(SqlInternalConnection innerConnection, Transacti internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction, long transactionId) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Created for connection {1}#, outer transaction {2}#, Type {3}", ObjectID, innerConnection.ObjectID, (null != outerTransaction) ? outerTransaction.ObjectID : -1, (int)type); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Created for connection {1}#, outer transaction {2}#, Type {3}", ObjectID, innerConnection.ObjectID, (null != outerTransaction) ? outerTransaction.ObjectID : -1, (int)type); _innerConnection = innerConnection; _transactionType = type; @@ -271,11 +268,7 @@ internal void CloseFromConnection() SqlInternalConnection innerConnection = _innerConnection; Debug.Assert(innerConnection != null, "How can we be here if the connection is null?"); - - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Closing", ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Closing", ObjectID); bool processFinallyBlock = true; try @@ -303,12 +296,7 @@ internal void CloseFromConnection() internal void Commit() { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { throw SQL.ConnectionLockedForBcpEvent(); @@ -381,10 +369,7 @@ internal void Dispose() private /*protected override*/ void Dispose(bool disposing) { - if (SqlClientEventSource.Log.IsPoolerTraceEnabled()) - { - SqlClientEventSource.Log.PoolerTrace(" {0}#, Disposing", ObjectID); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Disposing", ObjectID); if (disposing) { @@ -440,7 +425,7 @@ internal void InitParent(SqlTransaction transaction) internal void Rollback() { - var scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#", ObjectID); + var scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { @@ -487,11 +472,7 @@ internal void Rollback() internal void Rollback(string transactionName) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#, transactionName='{transactionName}'", ObjectID); - } + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#, transactionName='{transactionName}'", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { @@ -540,12 +521,7 @@ internal void Rollback(string transactionName) internal void Save(string savePointName) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}#, savePointName='{savePointName}'", ObjectID); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#, savePointName='{savePointName}'", ObjectID); _innerConnection.ValidateConnectionForExecute(null); try diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs index 641ae836f5..d9c261abcd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs @@ -65,12 +65,7 @@ public SqlFileStream Int64 allocationSize ) { - long scopeID = 0; - if (SqlClientEventSource.Log.IsScopeEnabled()) - { - scopeID = SqlClientEventSource.Log.ScopeEnter(" {0}# access={1} options={2} path='{3}'", ObjectID, (int)access, (int)options, path); - } - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}# access={1} options={2} path='{3}'", ObjectID, (int)access, (int)options, path); try { //----------------------------------------------------------------- @@ -718,11 +713,8 @@ Int64 allocationSize UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode); try { - if (SqlClientEventSource.Log.IsAdvanceTraceOn()) - { - SqlClientEventSource.Log.Trace(" {0}#, desiredAccess=0x{1}, allocationSize={2}, " + - "fileAttributes=0x{3}, shareAccess=0x{4}, dwCreateDisposition=0x{5}, createOptions=0x{ dwCreateOptions}", ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, desiredAccess=0x{1}, allocationSize={2}, " + + "fileAttributes=0x{3}, shareAccess=0x{4}, dwCreateDisposition=0x{5}, createOptions=0x{ dwCreateOptions}", ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition); retval = UnsafeNativeMethods.NtCreateFile(out hFile, nDesiredAccess, ref oa, out ioStatusBlock, ref allocationSize, From 6e52adddc9cced00e13278b6891d71a3cbfedad0 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Wed, 19 Feb 2020 12:53:30 -0800 Subject: [PATCH 32/46] integrating SqlEventSource to SqlClientEventSource --- .../netfx/src/Microsoft.Data.SqlClient.csproj | 3 +- .../Data/SqlClient/SqlClientEventSource.cs | 97 ++++++++++++++----- .../Microsoft/Data/SqlClient/SqlCommand.cs | 8 +- .../src/Microsoft/Data/SqlEventSource.cs | 71 -------------- 4 files changed, 78 insertions(+), 101 deletions(-) delete mode 100644 src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlEventSource.cs diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj index 489daf514b..2f7540c531 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj @@ -269,7 +269,6 @@ - @@ -362,4 +361,4 @@ - + \ No newline at end of file diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 57c6ee9904..fd223119d7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -11,48 +11,75 @@ namespace Microsoft.Data.SqlClient [EventSource(Name = "Microsoft.Data.SqlClient.EventSource")] internal class SqlClientEventSource : EventSource { + // Defines the singleton instance for the Resources ETW provider internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); + private static long s_nextScopeId = 0; private static long s_nextNotificationScopeId = 0; private static long s_nextPoolerScopeId = 0; - private const int TraceEventId = 1; - private const int EnterScopeId = 2; - private const int ExitScopeId = 3; - private const int TraceBinId = 4; - private const int CorrelationTraceId = 5; - private const int NotificationsScopeEnterId = 6; - private const int NotificationsTraceId = 7; - private const int PoolerScopeEnterId = 8; - private const int PoolerTraceId = 9; - - //if we add more keywords they need to be a power of 2. - //Keyword class needs to be nested inside this class otherwise nothing will be logged as the SqlClientEventSource wont have contorol over that. + /// + /// Defines EventId for BeginExecute (Reader, Scalar, NonQuery, XmlReader). + /// + private const int BeginExecuteEventId = 1; + + /// + /// Defines EventId for EndExecute (Reader, Scalar, NonQuery, XmlReader). + /// + private const int EndExecuteEventId = 2; + private const int TraceEventId = 3; + private const int EnterScopeId = 4; + private const int ExitScopeId = 5; + private const int TraceBinId = 6; + private const int CorrelationTraceId = 7; + private const int NotificationsScopeEnterId = 8; + private const int NotificationsTraceId = 9; + private const int PoolerScopeEnterId = 10; + private const int PoolerTraceId = 11; + + /// + /// Keyword definitions. These represent logical groups of events that can be turned on and off independently + /// Often each task has a keyword, but where tasks are determined by subsystem, keywords are determined by + /// usefulness to end users to filter. Generally users don't mind extra events if they are not high volume + /// so grouping low volume events together in a single keywords is OK (users can post-filter by task if desired) + /// + /// The visibility of the enum has to be public, otherwise there will be an ArgumentException on calling related WriteEvent method. the Keywords class has to be a nested class. + /// Each keyword must be a power of 2. + /// + /// #region Keywords - internal class Keywords - { - internal const EventKeywords Trace = (EventKeywords)1; + public class Keywords + { + internal const EventKeywords SqlClient = (EventKeywords)3; + + internal const EventKeywords Trace = (EventKeywords)2; - internal const EventKeywords Scope = (EventKeywords)2; + internal const EventKeywords Scope = (EventKeywords)4; - internal const EventKeywords NotificationTrace = (EventKeywords)4; + internal const EventKeywords NotificationTrace = (EventKeywords)8; - internal const EventKeywords Pooling = (EventKeywords)8; + internal const EventKeywords Pooling = (EventKeywords)16; - internal const EventKeywords Correlation = (EventKeywords)16; + internal const EventKeywords Correlation = (EventKeywords)32; - internal const EventKeywords NotificationScope = (EventKeywords)32; + internal const EventKeywords NotificationScope = (EventKeywords)64; - internal const EventKeywords PoolerScope = (EventKeywords)64; + internal const EventKeywords PoolerScope = (EventKeywords)128; - internal const EventKeywords PoolerTrace = (EventKeywords)128; + internal const EventKeywords PoolerTrace = (EventKeywords)256; - internal const EventKeywords Advanced = (EventKeywords)256; + internal const EventKeywords Advanced = (EventKeywords)512; - internal const EventKeywords StateDump = (EventKeywords)512; + internal const EventKeywords StateDump = (EventKeywords)1024; } #endregion + public static class Tasks // this name is important for EventSource + { + /// Task that tracks sql command execute. + public const EventTask ExecuteCommand = (EventTask)1; + } + #region Enable/Disable Events [NonEvent] internal bool IsTraceEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Trace); @@ -496,6 +523,28 @@ internal void PoolerTrace(string message) { WriteEvent(PoolerTraceId, message); } + + // unfortunately these are not marked as Start/Stop opcodes. The reason is that we dont want them to participate in + // the EventSource activity IDs (because they currently don't use tasks and this simply confuses the logic) and + // because of versioning requirements we don't have ActivityOptions capability (because mscorlib and System.Data version + // at different rates) Sigh... + [Event(BeginExecuteEventId, Keywords = Keywords.SqlClient, Task = Tasks.ExecuteCommand, Opcode = EventOpcode.Start)] + public void BeginExecute(int objectId, string dataSource, string database, string commandText) + { + // we do not use unsafe code for better performance optization here because optimized helpers make the code unsafe where that would not be the case otherwise. + // This introduces the question of partial trust, which is complex in the SQL case (there are a lot of scenarios and SQL has special security support). + WriteEvent(BeginExecuteEventId, objectId, dataSource, database, commandText); + } + + // unfortunately these are not marked as Start/Stop opcodes. The reason is that we dont want them to participate in + // the EventSource activity IDs (because they currently don't use tasks and this simply confuses the logic) and + // because of versioning requirements we don't have ActivityOptions capability (because mscorlib and System.Data version + // at different rates) Sigh... + [Event(EndExecuteEventId, Keywords = Keywords.SqlClient, Task = Tasks.ExecuteCommand, Opcode = EventOpcode.Stop)] + public void EndExecute(int objectId, int compositeState, int sqlExceptionNumber) + { + WriteEvent(EndExecuteEventId, objectId, compositeState, sqlExceptionNumber); + } #endregion } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index 1445d85e15..b1ce215c35 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -7438,9 +7438,9 @@ private SmiRequestExecutor SetUpSmiRequest(SqlInternalConnectionSmi innerConnect private void WriteBeginExecuteEvent() { - if (SqlEventSource.Log.IsEnabled() && Connection != null) + if (SqlClientEventSource.Log.IsEnabled() && Connection != null) { - SqlEventSource.Log.BeginExecute(GetHashCode(), Connection.DataSource, Connection.Database, CommandText); + SqlClientEventSource.Log.BeginExecute(GetHashCode(), Connection.DataSource, Connection.Database, CommandText); } } @@ -7452,7 +7452,7 @@ private void WriteBeginExecuteEvent() /// True if SQL command was executed synchronously, otherwise false. private void WriteEndExecuteEvent(bool success, int? sqlExceptionNumber, bool synchronous) { - if (SqlEventSource.Log.IsEnabled()) + if (SqlClientEventSource.Log.IsEnabled()) { // SqlEventSource.WriteEvent(int, int, int, int) is faster than provided overload SqlEventSource.WriteEvent(int, object[]). // that's why trying to fit several booleans in one integer value @@ -7468,7 +7468,7 @@ private void WriteEndExecuteEvent(bool success, int? sqlExceptionNumber, bool sy int compositeState = successFlag | isSqlExceptionFlag | synchronousFlag; - SqlEventSource.Log.EndExecute(GetHashCode(), compositeState, sqlExceptionNumber.GetValueOrDefault()); + SqlClientEventSource.Log.EndExecute(GetHashCode(), compositeState, sqlExceptionNumber.GetValueOrDefault()); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlEventSource.cs deleted file mode 100644 index da1843d6d4..0000000000 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlEventSource.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.Data -{ - using System.Diagnostics.Tracing; - - [EventSource(Name = SqlEventSource.EventSourceName)] - internal sealed class SqlEventSource : EventSource - { - internal const string EventSourceName = "Microsoft-AdoNet-SystemData"; - - /// - /// Defines EventId for BeginExecute (Reader, Scalar, NonQuery, XmlReader). - /// - private const int BeginExecuteEventId = 1; - - /// - /// Defines EventId for EndExecute (Reader, Scalar, NonQuery, XmlReader). - /// - private const int EndExecuteEventId = 2; - - // Defines the singleton instance for the Resources ETW provider - internal static readonly SqlEventSource Log = new SqlEventSource(); - - /// - /// Keyword definitions. These represent logical groups of events that can be turned on and off independently - /// Often each task has a keyword, but where tasks are determined by subsystem, keywords are determined by - /// usefulness to end users to filter. Generally users don't mind extra events if they are not high volume - /// so grouping low volume events together in a single keywords is OK (users can post-filter by task if desired) - /// The visibility of the enum has to be public, otherwise there will be an ArgumentException on calling related WriteEvent method. - /// - public static class Keywords - { - public const EventKeywords SqlClient = (EventKeywords)0x0001; // This is bit 0 - } - - public static class Tasks // this name is important for EventSource - { - /// Task that tracks sql command execute. - public const EventTask ExecuteCommand = (EventTask)1; - } - - private SqlEventSource() - { - } - - // unfortunately these are not marked as Start/Stop opcodes. The reason is that we dont want them to participate in - // the EventSource activity IDs (because they currently don't use tasks and this simply confuses the logic) and - // because of versioning requirements we don't have ActivityOptions capability (because mscorlib and System.Data version - // at different rates) Sigh... - [Event(SqlEventSource.BeginExecuteEventId, Keywords = Keywords.SqlClient, Task = Tasks.ExecuteCommand, Opcode = EventOpcode.Start)] - public void BeginExecute(int objectId, string dataSource, string database, string commandText) - { - // we do not use unsafe code for better performance optization here because optimized helpers make the code unsafe where that would not be the case otherwise. - // This introduces the question of partial trust, which is complex in the SQL case (there are a lot of scenarios and SQL has special security support). - WriteEvent(SqlEventSource.BeginExecuteEventId, objectId, dataSource, database, commandText); - } - - // unfortunately these are not marked as Start/Stop opcodes. The reason is that we dont want them to participate in - // the EventSource activity IDs (because they currently don't use tasks and this simply confuses the logic) and - // because of versioning requirements we don't have ActivityOptions capability (because mscorlib and System.Data version - // at different rates) Sigh... - [Event(SqlEventSource.EndExecuteEventId, Keywords = Keywords.SqlClient, Task = Tasks.ExecuteCommand, Opcode = EventOpcode.Stop)] - public void EndExecute(int objectId, int compositeState, int sqlExceptionNumber) - { - WriteEvent(SqlEventSource.EndExecuteEventId, objectId, compositeState, sqlExceptionNumber); - } - } -} From 26d3c2e447619fea34312931562ceae8d2486549 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Wed, 19 Feb 2020 16:50:34 -0800 Subject: [PATCH 33/46] Adding null value checker to SqlDependencyListener EventSource logger --- .../netfx/src/Microsoft.Data.SqlClient.csproj | 20 ++++++++++++++----- .../src/Microsoft/Data/Common/AdapterUtil.cs | 2 +- .../Data/SqlClient/SqlClientEventSource.cs | 11 +++++++++- .../Microsoft/Data/SqlClient/SqlDependency.cs | 2 +- .../Data/SqlClient/SqlDependencyListener.cs | 2 +- 5 files changed, 28 insertions(+), 9 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj index 2f7540c531..3ddcbd8312 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj @@ -159,10 +159,16 @@ - - + + Component + + + Component + - + + Component + @@ -171,7 +177,9 @@ - + + Component + @@ -252,7 +260,9 @@ - + + Component + diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index 6921eb18d2..736080b5fb 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -100,7 +100,7 @@ static private void TraceException( string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e && SqlClientEventSource.Log.IsTraceEnabled()) + if (null != e) { SqlClientEventSource.Log.TraceEvent(trace, e.ToString()); // will include callstack if permission is available } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index fd223119d7..21d39eec50 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -49,7 +49,7 @@ internal class SqlClientEventSource : EventSource /// #region Keywords public class Keywords - { + { internal const EventKeywords SqlClient = (EventKeywords)3; internal const EventKeywords Trace = (EventKeywords)2; @@ -404,6 +404,15 @@ internal void CorrelationTraceEvent(string message, T0 args0, T1 arg } } + [NonEvent] + internal void NotificationsTraceEvent(string message) + { + if (IsNotificationTraceEnabled()) + { + NotificationsTrace(message); + } + } + [NonEvent] internal void NotificationsTraceEvent(string message, T0 args0) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs index fd0a6d5e75..d0951d1e7c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -779,7 +779,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - SqlClientEventSource.Log.NotificationsTrace(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); + SqlClientEventSource.Log.NotificationsTraceEvent(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); throw; } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index 35de9d0c49..88b7d51a10 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -79,7 +79,7 @@ internal int ObjectID internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { - long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, queue: '{1}'", ObjectID, HashHelper.Queue); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, queue: '{1}'", ObjectID, HashHelper?.Queue); bool setupCompleted = false; try From 5b1a7ee62d91939147f8b06cb50af97274d0713e Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Thu, 20 Feb 2020 14:57:58 -0800 Subject: [PATCH 34/46] EventSource --- .../netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs | 6 +++--- .../netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs | 2 -- .../src/Microsoft/Data/SqlClient/SqlDependencyListener.cs | 1 - 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs index ec37b8727f..0cdd9c8cff 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientLogger.cs @@ -25,9 +25,6 @@ public void LogError(string type, string method, string message) SqlClientEventSource.Log.TraceEvent("{3}", type, method, LogLevel.Info, message); } - /// - public bool IsLoggingEnabled => SqlClientEventSource.Log.IsEnabled(); - /// public bool LogAssert(bool value, string type, string method, string message) { @@ -35,5 +32,8 @@ public bool LogAssert(bool value, string type, string method, string message) LogError(type, method, message); return value; } + + /// + public bool IsLoggingEnabled => SqlClientEventSource.Log.IsEnabled(); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs index 12ecbe8d65..1c15e83c37 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs @@ -1356,7 +1356,6 @@ internal override void StatementCompleted(int recordsAffected) // devnote: relies on SmiEventSink_Default to pass event to parent // Both command and reader care about StatementCompleted, but for different reasons. - base.StatementCompleted(recordsAffected); this.reader.StatementCompleted(); } @@ -1369,7 +1368,6 @@ internal override void BatchCompleted() // parent's callback *MUST* come before reader's BatchCompleted, since // reader will close the event stream during this call, and parent wants // to extract parameter values before that happens. - base.BatchCompleted(); this.reader.BatchCompleted(); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index 88b7d51a10..b73d9b1061 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -76,7 +76,6 @@ internal int ObjectID // ----------- // Constructor // ----------- - internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, queue: '{1}'", ObjectID, HashHelper?.Queue); From 34bedaf266fe8cb9e0427c865fa855be859173e0 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Thu, 20 Feb 2020 16:16:26 -0800 Subject: [PATCH 35/46] Fixing ScopeLeave related logic --- .../netfx/src/Microsoft.Data.SqlClient.csproj | 22 +++------- .../netfx/src/Microsoft/Data/DataException.cs | 1 - .../Data/ProviderBase/DbConnectionFactory.cs | 6 +-- .../Data/ProviderBase/DbConnectionPool.cs | 2 +- .../Data/ProviderBase/SqlConnectionHelper.cs | 2 +- .../Data/SqlClient/SqlClientEventSource.cs | 40 +++++++++++++++++-- .../Microsoft/Data/SqlClient/SqlCommand.cs | 16 ++++---- .../Microsoft/Data/SqlClient/SqlCommandSet.cs | 2 +- .../Microsoft/Data/SqlClient/SqlConnection.cs | 14 +++---- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 12 +++--- .../Data/SqlClient/SqlDataReaderSmi.cs | 6 +-- .../Microsoft/Data/SqlClient/SqlDependency.cs | 30 +++++++------- .../Data/SqlClient/SqlDependencyListener.cs | 36 ++++++++--------- .../Data/SqlClient/SqlDependencyUtils.cs | 24 +++++------ .../Data/SqlClient/SqlTransaction.cs | 8 ++-- .../Data/SqlClient/TdsParserSessionPool.cs | 2 +- .../Data/SqlClient/sqlinternaltransaction.cs | 8 ++-- .../Microsoft/Data/SqlTypes/SqlFileStream.cs | 2 +- 18 files changed, 127 insertions(+), 106 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj index 3ddcbd8312..79d181249a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj @@ -159,16 +159,10 @@ - - Component - - - Component - + + - - Component - + @@ -177,9 +171,7 @@ - - Component - + @@ -260,9 +252,7 @@ - - Component - + @@ -371,4 +361,4 @@ - \ No newline at end of file + diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs index 82665dd592..f8f21a1574 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -36,7 +36,6 @@ static private void TraceException( catch (System.Security.SecurityException) { // if you don't have permission - you don't get the stack trace - SqlClientEventSource.Log.AdvanceTrace("Permission Denied"); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index 27c589c2ed..75df4299ec 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -80,7 +80,7 @@ public void ClearAllPools() } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -98,7 +98,7 @@ public void ClearPool(DbConnection connection) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -119,7 +119,7 @@ public void ClearPool(DbConnectionPoolKey key) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index f9d35dff1d..5257e39751 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -1780,7 +1780,7 @@ private void PoolCreateRequest(object state) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.PoolerScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs index 0b0f5b8ef8..c90c78e665 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs @@ -208,7 +208,7 @@ override protected DbCommand CreateDbCommand() } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } return command; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 21d39eec50..988da85ab6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -467,6 +467,41 @@ internal void StateDumpEvent(string message, T0 args0, T1 args1) } } + [NonEvent] + internal void ScopeLeaveEvent(long scopeId) + { + if (IsScopeEnabled()) + { + ScopeLeave(scopeId); + } + } + + [NonEvent] + internal void NotificationsScopeLeaveEvent(long scopeId) + { + if (IsNotificationScopeEnabled()) + { + ScopeLeave(scopeId); + } + } + + [NonEvent] + internal void PoolerScopeLeaveEvent(long scopeId) + { + if (IsPoolerScopeEnabled()) + { + ScopeLeave(scopeId); + } + } + + [NonEvent] + internal void AdvanceScopeLeave(long scopeId) + { + if (IsAdvanceTraceOn()) + { + ScopeLeave(scopeId); + } + } #endregion #region Events @@ -487,10 +522,7 @@ internal long ScopeEnter(string message) [Event(ExitScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] internal void ScopeLeave(long scopeId) { - if (SqlClientEventSource.Log.IsEnabled()) - { - WriteEvent(ExitScopeId, scopeId); - } + WriteEvent(ExitScopeId, scopeId); } [Event(TraceBinId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index b1ce215c35..0763a26ab2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -1095,7 +1095,7 @@ override public void Prepare() } SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } private void InternalPrepare() @@ -1289,7 +1289,7 @@ override public void Cancel() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -1356,7 +1356,7 @@ override public object ExecuteScalar() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1424,7 +1424,7 @@ override public int ExecuteNonQuery() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1450,7 +1450,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -2051,7 +2051,7 @@ public XmlReader ExecuteXmlReader() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -2364,7 +2364,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -2380,7 +2380,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index 860fe26da7..81acaf4c38 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -315,7 +315,7 @@ internal int ExecuteNonQuery() } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index 1eb593a4dd..a7d7c4847a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -1117,7 +1117,7 @@ override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLeve } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -1154,7 +1154,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); SqlStatistics.StopTimer(statistics); } } @@ -1343,7 +1343,7 @@ override public void Close() SqlDebugContext sdc = _sdc; _sdc = null; - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); if (sdc != null) { @@ -1432,7 +1432,7 @@ override public void Open() } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -1734,7 +1734,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.PoolerScopeLeaveEvent(scopeID); } } @@ -2475,7 +2475,7 @@ public static void ChangePassword(string connectionString, string newPassword) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -2546,7 +2546,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs index 9416c77825..6a45822409 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -1026,7 +1026,7 @@ override public void Close() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -1694,7 +1694,7 @@ override public DataTable GetSchemaTable() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -3780,7 +3780,7 @@ private bool TryNextResult(out bool more) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -4010,7 +4010,7 @@ private bool TryReadInternal(bool setTimeout, out bool more) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -4851,7 +4851,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -5245,7 +5245,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs index 1c15e83c37..1f589c0de2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs @@ -410,7 +410,7 @@ private void CloseInternal(bool closeConnection) Connection.Close(); } - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } } @@ -466,7 +466,7 @@ internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.AdvanceScopeLeave(scopeID); } } @@ -525,7 +525,7 @@ internal unsafe bool InternalRead(bool ignoreNonFatalErrors) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.AdvanceScopeLeave(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs index d0951d1e7c..1f3c4a1ea3 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -339,7 +339,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -475,7 +475,7 @@ public event OnChangeEventHandler OnChange } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } remove @@ -498,7 +498,7 @@ public event OnChangeEventHandler OnChange } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } } @@ -527,7 +527,7 @@ public void AddCommandDependency(SqlCommand command) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -788,7 +788,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -918,7 +918,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -978,7 +978,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1041,7 +1041,7 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1145,7 +1145,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1174,7 +1174,7 @@ internal void AddToServerList(string server) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1208,7 +1208,7 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1260,7 +1260,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1290,7 +1290,7 @@ internal void StartTimer(SqlNotificationRequest notificationRequest) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1359,7 +1359,7 @@ private void AddCommandInternal(SqlCommand cmd) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } } @@ -1429,7 +1429,7 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index b73d9b1061..f15dca1967 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -216,7 +216,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -320,7 +320,7 @@ internal bool AppDomainUnload(string appDomainKey) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -334,7 +334,7 @@ private void AsynchronouslyQueryServiceBrokerQueue() } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -386,7 +386,7 @@ private void AsyncResultCallback(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -522,7 +522,7 @@ private void CreateQueueAndService(bool restart) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -554,7 +554,7 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -682,7 +682,7 @@ private void ProcessNotificationResults(SqlDataReader reader) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -855,7 +855,7 @@ private void Restart(object unused) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -985,7 +985,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1002,7 +1002,7 @@ private void SynchronouslyQueryServiceBrokerQueue() } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1083,7 +1083,7 @@ private void TearDownAndDispose() } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } } @@ -1484,7 +1484,7 @@ private SqlDependencyProcessDispatcher(object dummyVariable) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1503,7 +1503,7 @@ public SqlDependencyProcessDispatcher() } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1562,7 +1562,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1606,7 +1606,7 @@ private void Invalidate(string server, SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1655,7 +1655,7 @@ private void AppDomainUnloading(object state) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1794,7 +1794,7 @@ private bool Start(string connectionString, } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1861,7 +1861,7 @@ internal bool Stop(string connectionString, } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs index 63298ce852..170e740b6c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs @@ -106,7 +106,7 @@ private SqlDependencyPerAppDomainDispatcher() } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -139,7 +139,7 @@ private void UnloadEventHandler(object sender, EventArgs e) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -160,7 +160,7 @@ internal void AddDependencyEntry(SqlDependency dep) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -238,7 +238,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } return notificationId; @@ -300,7 +300,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -354,7 +354,7 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -391,7 +391,7 @@ internal SqlDependency LookupDependencyEntry(string id) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -423,7 +423,7 @@ private void LookupDependencyEntryWithRemove(string id) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -463,7 +463,7 @@ private List LookupCommandEntryWithRemove(string notificationId) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -518,7 +518,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -557,7 +557,7 @@ internal void StartTimer(SqlDependency dep) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -652,7 +652,7 @@ private static void TimeoutTimerCallback(object state) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs index b42c28ba05..69ce8dec81 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -206,7 +206,7 @@ override public void Commit() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -329,7 +329,7 @@ override public void Rollback() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } } @@ -392,7 +392,7 @@ public void Rollback(string transactionName) _isFromAPI = false; SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -451,7 +451,7 @@ public void Save(string savePointName) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index f8e88d525d..0063243702 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -90,7 +90,7 @@ internal void Deactivate() } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs index afb16a65ef..5a107878b8 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs @@ -340,7 +340,7 @@ internal void Commit() } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -466,7 +466,7 @@ internal void Rollback() } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -515,7 +515,7 @@ internal void Rollback(string transactionName) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -552,7 +552,7 @@ internal void Save(string savePointName) } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs index d9c261abcd..785f22ae31 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs @@ -90,7 +90,7 @@ Int64 allocationSize } finally { - SqlClientEventSource.Log.ScopeLeave(scopeID); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } From e3fa4a483db1759508d4a5909566be15ff32db16 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Mon, 24 Feb 2020 09:57:59 -0800 Subject: [PATCH 36/46] Fixing PR issues and Tests --- .../Data/ProviderBase/DbConnectionInternal.cs | 2 +- .../Data/ProviderBase/DbConnectionPool.cs | 2 +- .../Data/ProviderBase/SqlConnectionHelper.cs | 2 +- .../SqlAuthenticationProviderManager.cs | 4 +- .../Data/SqlClient/SqlClientEventSource.cs | 89 ++++++++++++------- .../Microsoft/Data/SqlClient/SqlCommand.cs | 4 +- .../SqlClient/SqlInternalConnectionTds.cs | 31 ++++--- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 14 +-- .../Data/SqlClient/TdsParserStateObject.cs | 52 +++++------ .../EventSource/EventSourceTest.cs | 56 ++++++------ 10 files changed, 139 insertions(+), 117 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index e672ed1a26..446d22b560 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -803,7 +803,7 @@ internal void PrePush(object expectedOwner) } //DbConnection x = (expectedOwner as DbConnection); - SqlClientEventSource.Log.PoolerTraceEvent(" {}#, Preparing to push into pool, owning connection {0}#, pooledCount={1}", ObjectID, _pooledCount); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Preparing to push into pool, owning connection {1}#, pooledCount={2}", ObjectID, 0, _pooledCount); _pooledCount++; _owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2% diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index 5257e39751..33630971e2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -886,7 +886,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio } } } - SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Added to pool.", ObjectID, newObj.ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Added to pool.", ObjectID, newObj != null ? newObj?.ObjectID.ToString() ?? "null" : "null"); // Reset the error wait: _errorWait = ERROR_WAIT_DEFAULT; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs index c90c78e665..19cd0322d6 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs @@ -132,7 +132,7 @@ private void ConnectionString_Set(DbConnectionPoolKey key) } string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); - SqlClientEventSource.Log.TraceEvent(" {0}#, '{1}'", ObjectID, cstr); + SqlClientEventSource.Log.TraceEvent(" {0}#, '{1}'", ObjectID, connectionOptions.UsersConnectionStringForTrace()); } internal DbConnectionInternal InnerConnection diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs index 39434bf0f7..b979d89768 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs @@ -81,7 +81,7 @@ public SqlAuthenticationProviderManager(SqlAuthenticationProviderConfigurationSe } else { - _sqlAuthLogger.LogInfo(_typeName, methodName, "No user-defined SqlAuthenticationInitializer found."); + // _sqlAuthLogger.LogInfo(_typeName, methodName, "No user-defined SqlAuthenticationInitializer found."); } // add user-defined providers, if any. @@ -106,7 +106,7 @@ public SqlAuthenticationProviderManager(SqlAuthenticationProviderConfigurationSe _providers[authentication] = provider; authenticationsWithAppSpecifiedProvider.Add(authentication); - _sqlAuthLogger.LogInfo(_typeName, methodName, $"Added user-defined auth provider: {providerSettings.Type} for authentication {authentication}."); + _sqlAuthLogger.LogInfo(_typeName, methodName, string.Format("Added user-defined auth provider: {0} for authentication {1}.", providerSettings?.Type, authentication)); } } else diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 988da85ab6..73c6cc0e32 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -50,9 +50,9 @@ internal class SqlClientEventSource : EventSource #region Keywords public class Keywords { - internal const EventKeywords SqlClient = (EventKeywords)3; + internal const EventKeywords Trace = (EventKeywords)1; - internal const EventKeywords Trace = (EventKeywords)2; + internal const EventKeywords TraceBin = (EventKeywords)2; internal const EventKeywords Scope = (EventKeywords)4; @@ -71,6 +71,8 @@ public class Keywords internal const EventKeywords Advanced = (EventKeywords)512; internal const EventKeywords StateDump = (EventKeywords)1024; + + internal const EventKeywords SqlClient = (EventKeywords)2048; } #endregion @@ -84,6 +86,9 @@ public class Keywords [NonEvent] internal bool IsTraceEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Trace); + [NonEvent] + internal bool IsTraceBinEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.TraceBin); + [NonEvent] internal bool IsScopeEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Scope); @@ -110,6 +115,9 @@ public class Keywords [NonEvent] internal bool IsStateDumpEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.StateDump); + + [NonEvent] + internal bool IsSqlClientEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.SqlClient); #endregion #region overloads @@ -119,7 +127,7 @@ internal void TraceEvent(string message, T0 args0) { if (Log.IsTraceEnabled()) { - TraceEvent(string.Format(message), args0); + TraceEvent(string.Format(message, args0)); } } @@ -231,6 +239,15 @@ internal void AdvanceTrace(string message, T0 ar } } + [NonEvent] + internal void AdvanceTraceBin(string message, T0 args0, T1 args1) + { + if (Log.IsAdvanceTraceOn()) + { + TraceBin(string.Format(message, args0, args1)); + } + } + [NonEvent] internal long ScopeEnterEvent(string message, T0 args0) { @@ -244,7 +261,7 @@ internal long ScopeEnterEvent(string message, T0 args0) [NonEvent] internal long AdvanceScopeEnter(string message, T0 args0) { - if (IsAdvanceTraceOn()) + if (Log.IsAdvanceTraceOn()) { return ScopeEnter(string.Format(message, args0)); } @@ -254,7 +271,7 @@ internal long AdvanceScopeEnter(string message, T0 args0) [NonEvent] internal long ScopeEnterEvent(string message) { - if (IsScopeEnabled()) + if (Log.IsScopeEnabled()) { return ScopeEnter(message); } @@ -264,7 +281,7 @@ internal long ScopeEnterEvent(string message) [NonEvent] internal long ScopeEnterEvent(string message, T0 args0, T1 args1) { - if (IsScopeEnabled()) + if (Log.IsScopeEnabled()) { return ScopeEnter(string.Format(message, args0, args1)); } @@ -274,7 +291,7 @@ internal long ScopeEnterEvent(string message, T0 args0, T1 args1) [NonEvent] internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) { - if (IsScopeEnabled()) + if (Log.IsScopeEnabled()) { return ScopeEnter(string.Format(message, args0, args1, args2)); } @@ -284,7 +301,7 @@ internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 [NonEvent] internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { - if (IsScopeEnabled()) + if (Log.IsScopeEnabled()) { return ScopeEnter(string.Format(message, args0, args1, args2, args3)); } @@ -294,7 +311,7 @@ internal long ScopeEnterEvent(string message, T0 args0, T1 args1 [NonEvent] internal long PoolerScopeEnterEvent(string message, T0 args0) { - if (IsPoolerScopeEnabled()) + if (Log.IsPoolerScopeEnabled()) { return PoolerScopeEnter(string.Format(message, args0)); } @@ -304,7 +321,7 @@ internal long PoolerScopeEnterEvent(string message, T0 args0) [NonEvent] internal long NotificationsScopeEnterEvent(string message, T0 args0) { - if (IsNotificationScopeEnabled()) + if (Log.IsNotificationScopeEnabled()) { return NotificationsScopeEnter(string.Format(message, args0)); } @@ -314,7 +331,7 @@ internal long NotificationsScopeEnterEvent(string message, T0 args0) [NonEvent] internal long NotificationsScopeEnterEvent(string message, T0 args0, T1 args1) { - if (IsNotificationScopeEnabled()) + if (Log.IsNotificationScopeEnabled()) { return NotificationsScopeEnter(string.Format(message, args0, args1)); } @@ -324,7 +341,7 @@ internal long NotificationsScopeEnterEvent(string message, T0 args0, T1 [NonEvent] internal long NotificationsScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) { - if (IsNotificationScopeEnabled()) + if (Log.IsNotificationScopeEnabled()) { return NotificationsScopeEnter(string.Format(message, args0, args1, args2)); } @@ -334,7 +351,7 @@ internal long NotificationsScopeEnterEvent(string message, T0 args0, [NonEvent] internal long NotificationsScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { - if (IsNotificationScopeEnabled()) + if (Log.IsNotificationScopeEnabled()) { return NotificationsScopeEnter(string.Format(message, args0, args1, args2, args3)); } @@ -344,7 +361,7 @@ internal long NotificationsScopeEnterEvent(string message, T0 ar [NonEvent] internal void PoolerTraceEvent(string message, T0 args0) { - if (IsPoolerTraceEnabled()) + if (Log.IsPoolerTraceEnabled()) { PoolerTrace(string.Format(message, args0)); } @@ -353,7 +370,7 @@ internal void PoolerTraceEvent(string message, T0 args0) [NonEvent] internal void PoolerTraceEvent(string message, T0 args0, T1 args1) { - if (IsPoolerTraceEnabled()) + if (Log.IsPoolerTraceEnabled()) { PoolerTrace(string.Format(message, args0, args1)); } @@ -362,7 +379,7 @@ internal void PoolerTraceEvent(string message, T0 args0, T1 args1) [NonEvent] internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2) { - if (IsPoolerTraceEnabled()) + if (Log.IsPoolerTraceEnabled()) { PoolerTrace(string.Format(message, args0, args1, args2)); } @@ -371,7 +388,7 @@ internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T [NonEvent] internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { - if (IsPoolerTraceEnabled()) + if (Log.IsPoolerTraceEnabled()) { PoolerTrace(string.Format(message, args0, args1, args2, args3)); } @@ -380,7 +397,7 @@ internal void PoolerTraceEvent(string message, T0 args0, T1 args [NonEvent] internal void CorrelationTraceEvent(string message, T0 args0) { - if (IsCorrelationEnabled()) + if (Log.IsCorrelationEnabled()) { CorrelationTrace(string.Format(message, args0)); } @@ -389,7 +406,7 @@ internal void CorrelationTraceEvent(string message, T0 args0) [NonEvent] internal void CorrelationTraceEvent(string message, T0 args0, T1 args1) { - if (IsCorrelationEnabled()) + if (Log.IsCorrelationEnabled()) { CorrelationTrace(string.Format(message, args0, args1)); } @@ -398,7 +415,7 @@ internal void CorrelationTraceEvent(string message, T0 args0, T1 args1) [NonEvent] internal void CorrelationTraceEvent(string message, T0 args0, T1 args1, T2 args2) { - if (IsCorrelationEnabled()) + if (Log.IsCorrelationEnabled()) { CorrelationTrace(string.Format(message, args0, args1, args2)); } @@ -407,7 +424,7 @@ internal void CorrelationTraceEvent(string message, T0 args0, T1 arg [NonEvent] internal void NotificationsTraceEvent(string message) { - if (IsNotificationTraceEnabled()) + if (Log.IsNotificationTraceEnabled()) { NotificationsTrace(message); } @@ -416,7 +433,7 @@ internal void NotificationsTraceEvent(string message) [NonEvent] internal void NotificationsTraceEvent(string message, T0 args0) { - if (IsNotificationTraceEnabled()) + if (Log.IsNotificationTraceEnabled()) { NotificationsTrace(string.Format(message, args0)); } @@ -425,7 +442,7 @@ internal void NotificationsTraceEvent(string message, T0 args0) [NonEvent] internal void NotificationsTraceEvent(string message, T0 args0, T1 args1) { - if (IsNotificationTraceEnabled()) + if (Log.IsNotificationTraceEnabled()) { NotificationsTrace(string.Format(message, args0, args1)); } @@ -434,7 +451,7 @@ internal void NotificationsTraceEvent(string message, T0 args0, T1 args1 [NonEvent] internal void NotificationsTraceEvent(string message, T0 args0, T1 args1, T2 args2) { - if (IsNotificationTraceEnabled()) + if (Log.IsNotificationTraceEnabled()) { NotificationsTrace(string.Format(message, args0, args1, args2)); } @@ -443,7 +460,7 @@ internal void NotificationsTraceEvent(string message, T0 args0, T1 a [NonEvent] internal void NotificationsTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { - if (IsNotificationTraceEnabled()) + if (Log.IsNotificationTraceEnabled()) { NotificationsTrace(string.Format(message, args0, args1, args2, args3)); } @@ -452,7 +469,7 @@ internal void NotificationsTraceEvent(string message, T0 args0, [NonEvent] internal void TraceBinEvent(string message, T0 args0, T1 args1) { - if (IsTraceEnabled()) + if (Log.IsTraceBinEnabled()) { TraceBin(string.Format(message, args0, args1)); } @@ -461,7 +478,7 @@ internal void TraceBinEvent(string message, T0 args0, T1 args1) [NonEvent] internal void StateDumpEvent(string message, T0 args0, T1 args1) { - if (IsStateDumpEnabled()) + if (Log.IsStateDumpEnabled()) { Trace(string.Format(message, args0, args1)); } @@ -470,7 +487,7 @@ internal void StateDumpEvent(string message, T0 args0, T1 args1) [NonEvent] internal void ScopeLeaveEvent(long scopeId) { - if (IsScopeEnabled()) + if (Log.IsScopeEnabled()) { ScopeLeave(scopeId); } @@ -479,7 +496,7 @@ internal void ScopeLeaveEvent(long scopeId) [NonEvent] internal void NotificationsScopeLeaveEvent(long scopeId) { - if (IsNotificationScopeEnabled()) + if (Log.IsNotificationScopeEnabled()) { ScopeLeave(scopeId); } @@ -488,7 +505,7 @@ internal void NotificationsScopeLeaveEvent(long scopeId) [NonEvent] internal void PoolerScopeLeaveEvent(long scopeId) { - if (IsPoolerScopeEnabled()) + if (Log.IsPoolerScopeEnabled()) { ScopeLeave(scopeId); } @@ -497,7 +514,7 @@ internal void PoolerScopeLeaveEvent(long scopeId) [NonEvent] internal void AdvanceScopeLeave(long scopeId) { - if (IsAdvanceTraceOn()) + if (Log.IsAdvanceTraceOn()) { ScopeLeave(scopeId); } @@ -574,7 +591,10 @@ public void BeginExecute(int objectId, string dataSource, string database, strin { // we do not use unsafe code for better performance optization here because optimized helpers make the code unsafe where that would not be the case otherwise. // This introduces the question of partial trust, which is complex in the SQL case (there are a lot of scenarios and SQL has special security support). - WriteEvent(BeginExecuteEventId, objectId, dataSource, database, commandText); + if (Log.IsSqlClientEnabled()) + { + WriteEvent(BeginExecuteEventId, objectId, dataSource, database, commandText); + } } // unfortunately these are not marked as Start/Stop opcodes. The reason is that we dont want them to participate in @@ -584,7 +604,10 @@ public void BeginExecute(int objectId, string dataSource, string database, strin [Event(EndExecuteEventId, Keywords = Keywords.SqlClient, Task = Tasks.ExecuteCommand, Opcode = EventOpcode.Stop)] public void EndExecute(int objectId, int compositeState, int sqlExceptionNumber) { - WriteEvent(EndExecuteEventId, objectId, compositeState, sqlExceptionNumber); + if (Log.IsSqlClientEnabled()) + { + WriteEvent(EndExecuteEventId, objectId, compositeState, sqlExceptionNumber); + } } #endregion } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index 0763a26ab2..c96f03211d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -7438,7 +7438,7 @@ private SmiRequestExecutor SetUpSmiRequest(SqlInternalConnectionSmi innerConnect private void WriteBeginExecuteEvent() { - if (SqlClientEventSource.Log.IsEnabled() && Connection != null) + if (Connection != null) { SqlClientEventSource.Log.BeginExecute(GetHashCode(), Connection.DataSource, Connection.Database, CommandText); } @@ -7452,7 +7452,7 @@ private void WriteBeginExecuteEvent() /// True if SQL command was executed synchronously, otherwise false. private void WriteEndExecuteEvent(bool success, int? sqlExceptionNumber, bool synchronous) { - if (SqlClientEventSource.Log.IsEnabled()) + if (SqlClientEventSource.Log.IsSqlClientEnabled()) { // SqlEventSource.WriteEvent(int, int, int, int) is faster than provided overload SqlEventSource.WriteEvent(int, object[]). // that's why trying to fit several booleans in one integer value diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs index 81a8ec8642..1e2ef55a62 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs @@ -1937,7 +1937,7 @@ TimeoutTimer timeout { Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used"); - SqlClientEventSource.Log.AdvanceTrace(" {0}#, useFailover={1}[bool], primary={2}, failover={failoverHost}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, useFailover={1}[bool], primary={2}, failover={3}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName, failoverHost ?? "null"); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. long timeoutUnitInterval; @@ -2426,7 +2426,7 @@ internal void OnEnvChange(SqlEnvChange rec) break; case TdsEnums.ENV_ROUTING: - SqlClientEventSource.Log.TraceEvent(" {0}#, Received routing info", ObjectID); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, Received routing info", ObjectID); if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0) { throw SQL.ROR_InvalidRoutingInfo(this); @@ -2503,7 +2503,7 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) { SqlClientEventSource.Log.TraceEvent(" {0}#, " + "The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + - "The expiration time is {1}. Current Time is {DateTime.UtcNow.ToLongTimeString()}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString()); + "The expiration time is {1}. Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); attemptRefreshTokenUnLocked = true; } @@ -2524,7 +2524,7 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // If a thread is already doing the refresh, just use the existing token in the cache and proceed. else if (contextValidity <= _dbAuthenticationContextLockedRefreshTimeSpan) { - SqlClientEventSource.Log.TraceEvent(" {0}#, " + + SqlClientEventSource.Log.AdvanceTrace(" {0}#, " + "The authentication context needs a refresh.The expiration time is {1}. " + "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); @@ -2540,11 +2540,11 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // Indicate in Bid Trace that we are successful with the update. if (attemptRefreshTokenLocked) { - SqlClientEventSource.Log.TraceEvent(" %d#, The attempt to get a new access token succeeded under the locked mode."); + SqlClientEventSource.Log.TraceEvent(" {0}#, The attempt to get a new access token succeeded under the locked mode.", ObjectID); } } - SqlClientEventSource.Log.TraceEvent(" {0}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); } } @@ -2612,7 +2612,7 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP } else { - SqlClientEventSource.Log.TraceEvent(" {}#, Refreshing the context is already in progress by another thread.", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Refreshing the context is already in progress by another thread.", ObjectID); } if (authenticationContextLocked) @@ -2869,7 +2869,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_FEDAUTH: { - SqlClientEventSource.Log.TraceEvent(" {0}#, Received feature extension acknowledgement for federated authentication", ObjectID); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, Received feature extension acknowledgement for federated authentication", ObjectID); if (!_federatedAuthenticationRequested) { @@ -2886,8 +2886,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // The server shouldn't have sent any additional data with the ack (like a nonce) if (data.Length != 0) { - SqlClientEventSource.Log.TraceEvent(" {0}#, " + - "Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthFeatureAckContainsExtraData); } break; @@ -2927,7 +2926,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_TCE: { - SqlClientEventSource.Log.TraceEvent(" {0}#, Received feature extension acknowledgement for TCE", ObjectID); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, Received feature extension acknowledgement for TCE", ObjectID); if (data.Length < 1) { SqlClientEventSource.Log.TraceEvent(" {0}#, Unknown version number for TCE", ObjectID); @@ -2956,7 +2955,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS: { - SqlClientEventSource.Log.TraceEvent(" {0}#, Received feature extension acknowledgement for GlobalTransactions", ObjectID); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, Received feature extension acknowledgement for GlobalTransactions", ObjectID); if (data.Length < 1) { @@ -2975,7 +2974,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_AZURESQLSUPPORT: { - SqlClientEventSource.Log.TraceEvent(" {0}#, Received feature extension acknowledgement for AzureSQLSupport", ObjectID); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, Received feature extension acknowledgement for AzureSQLSupport", ObjectID); if (data.Length < 1) { @@ -2987,14 +2986,14 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // Bit 0 for RO/FP support if ((data[0] & 1) == 1 && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.TraceEvent(" {0}#, FailoverPartner enabled with Readonly intent for AzureSQL DB", ObjectID); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, FailoverPartner enabled with Readonly intent for AzureSQL DB", ObjectID); } break; } case TdsEnums.FEATUREEXT_DATACLASSIFICATION: { - SqlClientEventSource.Log.TraceEvent(" {0}#, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); if (data.Length < 1) { @@ -3021,7 +3020,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_UTF8SUPPORT: { - SqlClientEventSource.Log.TraceEvent(" {0}#, Received feature extension acknowledgement for UTF8 support", ObjectID); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, Received feature extension acknowledgement for UTF8 support", ObjectID); if (data.Length < 1) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index 0bcd2e1696..46da75a6a8 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -3955,7 +3955,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, if (tokenLen < sizeof(uint)) { // the token must at least contain a DWORD indicating the number of info IDs - SqlClientEventSource.Log.AdvanceTrace(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); + SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen); } @@ -3969,7 +3969,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount - SqlClientEventSource.Log.TraceEvent(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); + SqlClientEventSource.Log.AdvanceTrace(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); if (tokenLen > 0) { @@ -3978,7 +3978,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, int totalRead = 0; bool successfulRead = stateObj.TryReadByteArray(tokenData, 0, tokenLen, out totalRead); - SqlClientEventSource.Log.TraceEvent(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); + SqlClientEventSource.Log.AdvanceTrace(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); if (!successfulRead || totalRead != tokenLen) { @@ -4003,7 +4003,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, byte id = tokenData[currentOptionOffset]; uint dataLen = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 1))); uint dataOffset = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 5))); - SqlClientEventSource.Log.TraceEvent(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture)); + SqlClientEventSource.Log.AdvanceTrace(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture)); // offset is measured from optCount, so subtract to make offset measured // from the beginning of tokenData @@ -4035,7 +4035,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, SqlClientEventSource.Log.TraceEvent(" FedAuthInfoData is not in unicode format.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e); } - SqlClientEventSource.Log.TraceEvent(" FedAuthInfoData: {0}", data); + SqlClientEventSource.Log.AdvanceTrace(" FedAuthInfoData: {0}", data); // store data in tempFedAuthInfo switch ((TdsEnums.FedAuthInfoId)id) @@ -4047,7 +4047,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, tempFedAuthInfo.stsurl = data; break; default: - SqlClientEventSource.Log.TraceEvent(" Ignoring unknown federated authentication info option: {0}", id); + SqlClientEventSource.Log.AdvanceTrace(" Ignoring unknown federated authentication info option: {0}", id); break; } } @@ -8758,7 +8758,7 @@ internal void TdsLogin(SqlLogin rec, } WriteInt(log7Flags, _physicalStateObj); - SqlClientEventSource.Log.TraceEvent(" {0}#, TDS Login7 flags = {1}:", ObjectID, log7Flags); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, TDS Login7 flags = {1}:", ObjectID, log7Flags); WriteInt(0, _physicalStateObj); // ClientTimeZone is not used WriteInt(0, _physicalStateObj); // LCID is unused by server diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index bf115e3d96..15b2803f94 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -2796,7 +2796,7 @@ public void ProcessSniPacket(IntPtr packet, UInt32 error) } } SniReadStatisticsAndTracing(); - SqlClientEventSource.Log.TraceBinEvent(" Packet read", _inBuff, (ushort)_inBytesRead); + SqlClientEventSource.Log.AdvanceTraceBin(" Packet read", _inBuff, (ushort)_inBytesRead); AssertValidState(); } else @@ -3542,7 +3542,7 @@ internal void SendAttention(bool mustTakeWriteLock = false) _attentionSending = false; } - SqlClientEventSource.Log.TraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); + SqlClientEventSource.Log.AdvanceTraceBin(" Packet sent", _outBuff, (ushort)_outBytesUsed); SqlClientEventSource.Log.TraceEvent(" Attention sent to the server.", "Info"); AssertValidState(); @@ -3699,35 +3699,37 @@ private void SniWriteStatisticsAndTracing() statistics.SafeAdd(ref statistics._bytesSent, _outBytesUsed); statistics.RequestNetworkServerTimer(); } - - // If we have tracePassword variables set, we are flushing TDSLogin and so we need to - // blank out password in buffer. Buffer has already been sent to netlib, so no danger - // of losing info. - if (_tracePasswordOffset != 0) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { - for (int i = _tracePasswordOffset; i < _tracePasswordOffset + - _tracePasswordLength; i++) + // If we have tracePassword variables set, we are flushing TDSLogin and so we need to + // blank out password in buffer. Buffer has already been sent to netlib, so no danger + // of losing info. + if (_tracePasswordOffset != 0) { - _outBuff[i] = 0; - } + for (int i = _tracePasswordOffset; i < _tracePasswordOffset + + _tracePasswordLength; i++) + { + _outBuff[i] = 0; + } - // Reset state. - _tracePasswordOffset = 0; - _tracePasswordLength = 0; - } - if (_traceChangePasswordOffset != 0) - { - for (int i = _traceChangePasswordOffset; i < _traceChangePasswordOffset + - _traceChangePasswordLength; i++) - { - _outBuff[i] = 0; + // Reset state. + _tracePasswordOffset = 0; + _tracePasswordLength = 0; } + if (_traceChangePasswordOffset != 0) + { + for (int i = _traceChangePasswordOffset; i < _traceChangePasswordOffset + + _traceChangePasswordLength; i++) + { + _outBuff[i] = 0; + } - // Reset state. - _traceChangePasswordOffset = 0; - _traceChangePasswordLength = 0; + // Reset state. + _traceChangePasswordOffset = 0; + _traceChangePasswordLength = 0; + } } - SqlClientEventSource.Log.TraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); + SqlClientEventSource.Log.AdvanceTraceBin(" Packet sent", _outBuff, (ushort)_outBytesUsed); } [Conditional("DEBUG")] diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs index 93a49e7f8b..a2a3c85e78 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs @@ -6,57 +6,55 @@ using System.Diagnostics.Tracing; using Xunit; -namespace Microsoft.Data.SqlClient.ManualTesting.Tests.EventSource +namespace Microsoft.Data.SqlClient.ManualTesting.Tests { [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "Not Implemented")] public class EventSourceTest { + List ids = new List(); + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] - public void IsTraceEnabled() + public void EventTraceTests() { - using (var listener = new SampleEventListener()) + GetIds(); + foreach (var id in ids) { - using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) + Assert.Equal(3, id); + } + } + + private void GetIds() + { + using (var TraceListener = new TraceEventListener()) + { + using (SqlConnection connection = new SqlConnection("Data Source = localhost; Initial Catalog = Northwind; Integrated Security = true;Timeout= 120")) { connection.Open(); using (SqlCommand command = new SqlCommand("SELECT * From [Customers]", connection)) { command.ExecuteNonQuery(); } + ids = TraceListener.IDs; } - - //Check if all the events are from Trace - foreach (var item in listener.eventsNames) - { - Assert.Contains("Trace", item); - } -#if net46 - //Check if we can disable the events - listener.DisableEvents(SqlClientEventSource.Log); - - Assert.False(SqlClientEventSource.Log.IsEnabled()); - - //Check if we are able to enable events again - listener.EnableEvents(SqlClientEventSource.Log, EventLevel.Informational); - Assert.True(SqlClientEventSource.Log.IsEnabled()); -#endif + ids = TraceListener.IDs; } } } - public class SampleEventListener : EventListener + public class TraceEventListener : EventListener { - public List eventsNames = new List(); - protected override void OnEventWritten(EventWrittenEventArgs eventData) + public List IDs = new List(); + protected override void OnEventSourceCreated(EventSource eventSource) { - if (eventData.Message != null) - { - eventsNames.Add(eventData.EventName); - } - else + if (eventSource.Name.Equals("Microsoft.Data.SqlClient.EventSource")) { - eventsNames.Add(eventData.EventName); + EnableEvents(eventSource, EventLevel.Informational, (EventKeywords)1); } } + + protected override void OnEventWritten(EventWrittenEventArgs eventData) + { + IDs.Add(eventData.EventId); + } } } From 7e293d3e5eaba13dea80e87216aaf6fe22a980b8 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Mon, 24 Feb 2020 10:57:50 -0800 Subject: [PATCH 37/46] EventSource --- .../Microsoft/Data/SqlClient/SqlClientEventSource.cs | 4 ++-- .../tests/ManualTests/EventSource/EventSourceTest.cs | 11 ++++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 73c6cc0e32..5e90796ade 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -50,6 +50,8 @@ internal class SqlClientEventSource : EventSource #region Keywords public class Keywords { + internal const EventKeywords SqlClient = 0; + internal const EventKeywords Trace = (EventKeywords)1; internal const EventKeywords TraceBin = (EventKeywords)2; @@ -71,8 +73,6 @@ public class Keywords internal const EventKeywords Advanced = (EventKeywords)512; internal const EventKeywords StateDump = (EventKeywords)1024; - - internal const EventKeywords SqlClient = (EventKeywords)2048; } #endregion diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs index a2a3c85e78..74eac0d06d 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs @@ -17,17 +17,17 @@ public class EventSourceTest public void EventTraceTests() { GetIds(); - foreach (var id in ids) - { - Assert.Equal(3, id); - } + //Trace EventKeyword is 3. + //We did not want to break the SqlEventSource for BeginExexute and EndExecute + // BeginExexute and EndExecute are Enabled when any kind of Event logging is enabled, so we check for those values as well. + Assert.All(ids, item => { Assert.True(3 == item || 1 == item || item == 2); }); } private void GetIds() { using (var TraceListener = new TraceEventListener()) { - using (SqlConnection connection = new SqlConnection("Data Source = localhost; Initial Catalog = Northwind; Integrated Security = true;Timeout= 120")) + using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand("SELECT * From [Customers]", connection)) @@ -41,6 +41,7 @@ private void GetIds() } } + [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "Not Implemented")] public class TraceEventListener : EventListener { public List IDs = new List(); From 42df9ec52b4199ebe7a0795c8a91465611b7e30f Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Mon, 24 Feb 2020 11:10:33 -0800 Subject: [PATCH 38/46] EventSource --- .../src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs index 19cd0322d6..c90c78e665 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs @@ -132,7 +132,7 @@ private void ConnectionString_Set(DbConnectionPoolKey key) } string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); - SqlClientEventSource.Log.TraceEvent(" {0}#, '{1}'", ObjectID, connectionOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TraceEvent(" {0}#, '{1}'", ObjectID, cstr); } internal DbConnectionInternal InnerConnection From 959ca0385afe2cdaf054572ffd8a803f928245f8 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Mon, 24 Feb 2020 16:32:33 -0800 Subject: [PATCH 39/46] EventSource --- .../netfx/src/Microsoft/Data/Common/AdapterUtil.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index 736080b5fb..0947158b5f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -96,8 +96,7 @@ static internal Task FalseTask } } - static private void TraceException( - string trace, Exception e) + static private void TraceException(string trace, Exception e) { Debug.Assert(null != e, "TraceException: null Exception"); if (null != e) @@ -113,12 +112,12 @@ static internal void TraceExceptionAsReturnValue(Exception e) static internal void TraceExceptionForCapture(Exception e) { Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!"); - TraceException(" '%ls'\n", e); + TraceException(" '{0}'", e); } static internal void TraceExceptionWithoutRethrow(Exception e) { Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!"); - TraceException(" '%ls'\n", e); + TraceException(" '{0}'", e); } // From 7c55d8c082760ad0daf1adf8135a810259d11a6b Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 25 Feb 2020 09:27:28 -0800 Subject: [PATCH 40/46] Removing Doc --- .../SqlClientEventSource_EventLogger.cs | 55 ------------------- 1 file changed, 55 deletions(-) delete mode 100644 doc/samples/SqlClientEventSource_EventLogger.cs diff --git a/doc/samples/SqlClientEventSource_EventLogger.cs b/doc/samples/SqlClientEventSource_EventLogger.cs deleted file mode 100644 index 39b8a0213d..0000000000 --- a/doc/samples/SqlClientEventSource_EventLogger.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Data; -using System.Diagnostics.Tracing; -using Microsoft.Data.SqlClient; - -// -class Program -{ - static void Main() - { - static void Main(string[] args) - { - using (var listener = new SampleEventListener()) - { - //This Enables events for Keywords.Tracing - //We also can select EventKeywords.All to get all possible available events. - listener.EnableEvents(SqlClientEventSource.Log, EventLevel.Informational, SqlClientEventSource.Keywords.Trace); - using (SqlConnection connection = new SqlConnection("Data Source=tcp:localhost;Database=Northwind;Integrated Security=SSIP;")) - { - connection.Open(); - using (SqlCommand command = new SqlCommand("SELECT * From [Customers]", connection)) - { - command.ExecuteNonQuery(); - } - } - } - } - } -} - -public class SampleEventListener : EventListener -{ - static TextWriter Out = Console.Out; - - /// - /// We override this method to get a callback on every event. - /// - /// - protected override void OnEventWritten(EventWrittenEventArgs eventData) - { - // report all event information - Out.Write(" Event {0} ", eventData.EventName); - - // Events can have formatting strings 'the Message property on the 'Event' attribute. - // If the event has a formatted message, print that, otherwise print out argument values. - if (eventData.Message != null) - Out.WriteLine(eventData.Message, eventData.Payload.ToArray()); - else - { - string[] sargs = eventData.Payload != null ? eventData.Payload.Select(o => o.ToString()).ToArray() : null; - Out.WriteLine("({0}).", sargs != null ? string.Join(", ", sargs) : ""); - } - } -} -// From ad7a3bdcd4799d2984f478be9be2a149e3be86b2 Mon Sep 17 00:00:00 2001 From: Javad Rahnama Date: Tue, 25 Feb 2020 15:56:07 -0800 Subject: [PATCH 41/46] ExceptionTrace Fix --- .../netfx/src/Microsoft/Data/DataException.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs index f8f21a1574..059d0acc6f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -28,10 +28,10 @@ static private void TraceException( Debug.Assert(null != e, "TraceException: null Exception"); if (null != e) { - SqlClientEventSource.Log.AdvanceTrace(e.Message); + SqlClientEventSource.Log.AdvanceTrace(trace, e.Message); try { - SqlClientEventSource.Log.AdvanceTrace(", StackTrace='{0}'", Environment.StackTrace); + SqlClientEventSource.Log.AdvanceTrace(" Environment StackTrace = '{0}'", Environment.StackTrace); } catch (System.Security.SecurityException) { @@ -42,15 +42,15 @@ static private void TraceException( static internal void TraceExceptionAsReturnValue(Exception e) { - TraceException(" Message='%ls'", e); + TraceException(" Message='{0}'", e); } static internal void TraceExceptionForCapture(Exception e) { - TraceException(" Message='%ls'", e); + TraceException(" Message = {0}", e); } static internal void TraceExceptionWithoutRethrow(Exception e) { - TraceException(" Message='%ls'", e); + TraceException(" Message = '{0}'", e); } // From dac6ecfb4f83146fc58f2032a731c6c857234d5c Mon Sep 17 00:00:00 2001 From: Javad Date: Thu, 27 Feb 2020 10:38:10 -0800 Subject: [PATCH 42/46] Update SqlAuthenticationProviderManager.cs --- .../Data/SqlClient/SqlAuthenticationProviderManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs index b979d89768..32356f85ba 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs @@ -81,7 +81,7 @@ public SqlAuthenticationProviderManager(SqlAuthenticationProviderConfigurationSe } else { - // _sqlAuthLogger.LogInfo(_typeName, methodName, "No user-defined SqlAuthenticationInitializer found."); + _sqlAuthLogger.LogInfo(_typeName, methodName, "No user-defined SqlAuthenticationInitializer found."); } // add user-defined providers, if any. From dc79898348e4782fb9fec06cdb291f5a8ad0fe02 Mon Sep 17 00:00:00 2001 From: Javad Date: Thu, 27 Feb 2020 10:39:26 -0800 Subject: [PATCH 43/46] Update SqlBulkCopy.cs --- .../netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index 9d96412ca1..fff3bf78eb 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs @@ -16,7 +16,6 @@ using System.Xml; using Microsoft.Data.Common; - // todo list: // * An ID column need to be ignored - even if there is an association // * Spec: ID columns will be ignored - even if there is an association From 52b9e6d717ae4c937ecfa18c74e3a8a472deb0e5 Mon Sep 17 00:00:00 2001 From: Javad Date: Thu, 27 Feb 2020 10:40:37 -0800 Subject: [PATCH 44/46] Update SqlConnectionFactory.cs --- .../netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs index 78a4838558..ba0c018224 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs @@ -13,7 +13,6 @@ using Microsoft.Data.ProviderBase; using Microsoft.Data.SqlClient.Server; - namespace Microsoft.Data.SqlClient { sealed internal class SqlConnectionFactory : DbConnectionFactory From 18eccbe566334f53296b244b0ed3fd96c7163228 Mon Sep 17 00:00:00 2001 From: Javad Date: Thu, 27 Feb 2020 10:42:27 -0800 Subject: [PATCH 45/46] Update SqlConnectionPoolGroupProviderInfo.cs --- .../Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs index 459ea14cca..767f5d97db 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs @@ -5,7 +5,6 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; - namespace Microsoft.Data.SqlClient { sealed internal class SqlConnectionPoolGroupProviderInfo : DbConnectionPoolGroupProviderInfo From 27f3bba874d55ef3d6670b945cc584e7cd2de69c Mon Sep 17 00:00:00 2001 From: Javad Date: Thu, 27 Feb 2020 11:36:05 -0800 Subject: [PATCH 46/46] Update SqlCommand.cs --- .../netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index c96f03211d..2fe57230ad 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -693,7 +693,6 @@ internal SqlStatistics Statistics // TODO: Add objid here SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); - _transaction = value; } }