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 ed6135157b..6f77a7d592 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj @@ -116,6 +116,7 @@ + @@ -227,7 +228,6 @@ - @@ -268,7 +268,6 @@ - @@ -302,8 +301,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..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,15 +96,12 @@ 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) + static private void TraceException(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.TraceEvent(trace, e.ToString()); // will include callstack if permission is available } } @@ -115,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); } // @@ -475,11 +472,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); @@ -488,11 +486,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); @@ -501,7 +500,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 @@ -528,12 +528,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); @@ -542,12 +543,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); @@ -557,14 +559,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); @@ -574,13 +577,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); @@ -590,16 +594,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); @@ -609,11 +614,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); @@ -623,12 +629,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); @@ -638,12 +645,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); @@ -653,13 +661,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); @@ -669,13 +678,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); @@ -684,11 +694,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); @@ -697,13 +708,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); @@ -713,11 +725,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); @@ -727,14 +740,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); @@ -744,13 +758,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); @@ -760,13 +775,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); @@ -785,12 +801,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); @@ -1301,9 +1318,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); @@ -1316,16 +1333,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)); @@ -1351,12 +1369,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); @@ -1519,10 +1537,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); @@ -1556,9 +1574,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); @@ -2929,15 +2947,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 2f502a12ef..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 @@ -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.AdvanceTrace(" Restrictions='{0}'", restrictions); #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.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 f446add866..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 @@ -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); + + if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) + { + // don't trace passwords ever! + if (null != keyvalue) + { + SqlClientEventSource.Log.AdvanceTrace(" KeyName='{0}', KeyValue='{1}'", keyname, keyvalue); } - else { - Bid.Trace(" KeyName='%ls'\n", keyname); + else + { + SqlClientEventSource.Log.AdvanceTrace(" KeyName='{0}'", keyname); } } } @@ -918,7 +925,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 +934,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 +1013,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 +1041,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..059d0acc6f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -7,10 +7,10 @@ using System.Data; using System.Diagnostics; using System.Globalization; +using Microsoft.Data.SqlClient; namespace Microsoft.Data { - internal static class ExceptionBuilder { // The class defines the exceptions that are specific to the DataSet. @@ -22,41 +22,35 @@ 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.AdvanceTrace(trace, e.Message); + try + { + SqlClientEventSource.Log.AdvanceTrace(" Environment StackTrace = '{0}'", Environment.StackTrace); + } + catch (System.Security.SecurityException) { - try - { - Bid.Trace(", StackTrace='%ls'", Environment.StackTrace); - } - catch (System.Security.SecurityException) - { - // if you don't have permission - you don't get the stack trace - } + // if you don't have permission - you don't get the stack trace } - Bid.Trace("\n"); } } 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); } // @@ -218,7 +212,6 @@ static public Exception ArgumentContainsNull(string paramName) return _Argument(paramName, StringsHelper.GetString(Strings.Data_ArgumentContainsNull, paramName)); } - // // Collections // @@ -899,7 +892,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)); @@ -1168,11 +1160,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); @@ -1296,7 +1289,6 @@ static public Exception StorageSetFailed() return _Argument(StringsHelper.GetString(Strings.DataStorage_SetInvalidDataType)); } - // // XML schema // @@ -1450,7 +1442,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)); @@ -1528,7 +1519,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 53de68caf1..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 @@ -4,7 +4,6 @@ namespace Microsoft.Data.ProviderBase { - using System; using System.Collections.Generic; using System.Data; @@ -13,6 +12,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 +65,7 @@ internal int ObjectID public void ClearAllPools() { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " "); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent("", "API"); try { Dictionary connectionPoolGroups = _connectionPoolGroups; @@ -81,16 +80,14 @@ public void ClearAllPools() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } public void ClearPool(DbConnection connection) { ADP.CheckArgumentNull(connection, "connection"); - - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", GetObjectId(connection)); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", GetObjectId(connection)); try { DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); @@ -101,7 +98,7 @@ public void ClearPool(DbConnection connection) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -109,9 +106,8 @@ public void ClearPool(DbConnectionPoolKey key) { Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, "key.ConnectionString"); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" connectionString", "API"); - IntPtr hscp; - Bid.ScopeEnter(out hscp, " connectionString"); try { DbConnectionPoolGroup poolGroup; @@ -123,7 +119,7 @@ public void ClearPool(DbConnectionPoolKey key) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -155,7 +151,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.TraceEvent(" {0}#, Non-pooled database connection created.", ObjectID); return newConnection; } @@ -165,12 +161,13 @@ 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); } - Bid.Trace(" %d#, Pooled database connection created.\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Pooled database connection created.", ObjectID); return newConnection; } @@ -365,8 +362,9 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour // connection creation failed on semaphore waiting or if max pool reached if (connectionPool.IsRunning) { + SqlClientEventSource.Log.TraceEvent(" {0}#, GetConnection failed because a pool timeout occurred.", ObjectID); + // If GetConnection failed while the pool is running, the pool timeout occurred. - Bid.Trace(" %d#, GetConnection failed because a pool timeout occurred.\n", ObjectID); throw ADP.PooledOpenTimeout(); } else @@ -383,8 +381,9 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour if (connection == null) { + 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 - Bid.Trace(" %d#, GetConnection failed because a pool timeout occurred and all retries were exhausted.\n", ObjectID); throw ADP.PooledOpenTimeout(); } @@ -409,7 +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)) { - Bid.Trace(" %d#, DisabledPoolGroup=%d#\n", 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; @@ -540,10 +539,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.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 @@ -563,10 +559,7 @@ 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.AdvanceTrace(" {0}#, ReleasePool={1}#", ObjectID, pool.ObjectID); PerformanceCounters.NumberOfInactiveConnectionPools.Decrement(); } } @@ -591,10 +584,7 @@ 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.AdvanceTrace(" {0}#, ReleasePoolGroup={1}#", ObjectID, poolGroup.ObjectID); PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Decrement(); } } @@ -660,7 +650,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.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 a346bedc76..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 @@ -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,7 @@ 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); - } + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Transaction {1}#, Enlisting.", ObjectID, value.GetHashCode()); TransactionOutcomeEnlist(value); } } @@ -391,8 +388,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.PoolerTraceEvent(" {0}#, Activating", ObjectID); #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); Debug.Assert(1 == activateCount, "activated multiple times?"); @@ -463,8 +459,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.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 @@ -569,8 +564,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.PoolerTraceEvent(" {0}#, Deactivating", ObjectID); #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); Debug.Assert(0 == activateCount, "activated multiple times?"); @@ -604,8 +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. - - Bid.Trace(" %d#, Delegated Transaction Completed.\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Delegated Transaction Completed.", ObjectID); if (1 == _pooledCount) { @@ -668,7 +661,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.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. @@ -676,7 +669,7 @@ protected internal void DoNotPoolThisConnection() protected internal void DoomThisConnection() { _connectionIsDoomed = true; - Bid.PoolerTrace(" %d#, Dooming\n", ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Dooming", ObjectID); } // Reset connection doomed status so it can be re-connected and pooled. @@ -808,11 +801,10 @@ 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.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% } @@ -841,11 +833,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.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) { @@ -901,7 +892,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.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 @@ -942,11 +933,9 @@ internal void CleanupConnectionOnTransactionCompletion(SysTx.Transaction transac void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) { SysTx.Transaction transaction = e.Transaction; - - Bid.Trace(" %d#, Transaction Completed. (pooledCount=%d)\n", ObjectID, _pooledCount); + SqlClientEventSource.Log.TraceEvent(" {0}#, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); CleanupTransactionOnCompletion(transaction); - CleanupConnectionOnTransactionCompletion(transaction); } @@ -961,7 +950,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.PoolerTraceEvent(" {0}#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID); PerformanceCounters.NumberOfStasisConnections.Increment(); } @@ -969,12 +958,13 @@ 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.PoolerTraceEvent(" {0}#, Delegated Transaction has ended, connection is closed. Returning to general pool.", ObjectID); } else { - Bid.PoolerTrace(" %d#, Delegated Transaction has ended, connection is closed/leaked. Disposing.\n", ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Delegated Transaction has ended, connection is closed/leaked. Disposing.", ObjectID); } + 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..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 @@ -19,6 +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 @@ -30,8 +31,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. @@ -80,11 +79,9 @@ sealed private class TransactedConnectionPool internal TransactedConnectionPool(DbConnectionPool pool) { Debug.Assert(null != pool, "null pool?"); - _pool = pool; _transactedCxns = new Dictionary(); - - Bid.PoolerTrace(" %d#, Constructed for connection pool %d#\n", ObjectID, _pool.ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Constructed for connection pool {1}#", ObjectID, _pool.ObjectID); } internal int ObjectID @@ -143,7 +140,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.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } return transactedObject; } @@ -170,8 +167,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.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); connections.Add(transactedObject); } } @@ -206,14 +202,13 @@ 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.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); connections.Add(transactedObject); } } else { - Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Adding List to transacted pool.\n", 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); @@ -241,7 +236,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt } } } - Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Added.\n", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Added.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } Pool.PerformanceCounters.NumberOfFreeConnections.Increment(); @@ -250,8 +245,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.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); TransactedConnectionList connections; int entry = -1; @@ -285,7 +279,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.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 @@ -302,7 +296,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.PoolerTraceEvent(" {0}#, Transaction {1}#, Connection {2}#, Transacted pool not yet created prior to transaction completing. Connection may be leaked.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } } @@ -529,8 +523,7 @@ internal DbConnectionPool( _poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback _state = State.Running; - - Bid.PoolerTrace(" %d#, Constructed.\n", ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Constructed.", ObjectID); //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls // StartBackgroundCallbacks after pool is actually in the collection @@ -678,8 +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. - - Bid.PoolerTrace(" %d#\n", ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#", ObjectID); // Destroy free objects that put us above MinPoolSize from old stack. while (Count > MinPoolSize) @@ -753,9 +745,7 @@ private void CleanupCallback(Object state) break; Debug.Assert(obj != null, "null connection is not expected"); - - Bid.PoolerTrace(" %d#, ChangeStacks=%d#\n", 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"); @@ -770,8 +760,7 @@ private void CleanupCallback(Object state) internal void Clear() { - Bid.PoolerTrace(" %d#, Clearing.\n", ObjectID); - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Clearing.", ObjectID); DbConnectionInternal obj; // First, quickly doom everything. @@ -807,8 +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(); - - Bid.PoolerTrace(" %d#, Cleared.\n", ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Cleared.", ObjectID); } private Timer CreateCleanupTimer() @@ -898,7 +886,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio } } } - Bid.PoolerTrace(" %d#, Connection %d#, Added to pool.\n", 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; @@ -959,8 +947,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio private void DeactivateObject(DbConnectionInternal obj) { - Bid.PoolerTrace(" %d#, Connection %d#, Deactivating.\n", 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; @@ -1100,12 +1087,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.PoolerTraceEvent(" {0}#, Connection {1}#, Has Delegated Transaction, waiting to Dispose.", ObjectID, obj.ObjectID); } else { - Bid.PoolerTrace(" %d#, Connection %d#, Removing from pool.\n", ObjectID, obj.ObjectID); - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Removing from pool.", ObjectID, obj.ObjectID); bool removed = false; lock (_objectList) { @@ -1116,20 +1102,18 @@ internal void DestroyObject(DbConnectionInternal obj) if (removed) { - Bid.PoolerTrace(" %d#, Connection %d#, Removed from pool.\n", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Removed from pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfPooledConnections.Decrement(); } obj.Dispose(); - - Bid.PoolerTrace(" %d#, Connection %d#, Disposed.\n", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Disposed.", ObjectID, obj.ObjectID); PerformanceCounters.HardDisconnectsPerSecond.Increment(); } } private void ErrorCallback(Object state) { - Bid.PoolerTrace(" %d#, Resetting Error handling.\n", ObjectID); - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Resetting Error handling.", ObjectID); _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); @@ -1212,7 +1196,8 @@ void WaitForPendingOpen() Microsoft.Data.SqlClient.TdsParser.ReliabilitySection tdsReliabilitySection = new Microsoft.Data.SqlClient.TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -1224,7 +1209,8 @@ void WaitForPendingOpen() timeout = !TryGetConnection(next.Owner, delay, allowCreate, onlyOneCheckConnection, next.UserOptions, out connection); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -1301,7 +1287,7 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource %d#, DbConnectionInternal State != Running.\n", ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, DbConnectionInternal State != Running.", ObjectID); connection = null; return true; } @@ -1346,8 +1332,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj SysTx.Transaction transaction = null; PerformanceCounters.SoftConnectsPerSecond.Increment(); - - Bid.PoolerTrace(" %d#, Getting connection.\n", 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. @@ -1400,20 +1385,20 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj switch (waitResult) { case WAIT_TIMEOUT: - Bid.PoolerTrace(" %d#, Wait timed out.\n", 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. - Bid.PoolerTrace(" %d#, Errors are set.\n", ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Errors are set.", ObjectID); Interlocked.Decrement(ref _waitCount); throw TryCloneCachedException(); case CREATION_HANDLE: - Bid.PoolerTrace(" %d#, Creating new connection.\n", ObjectID); - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Creating new connection.", ObjectID); try { obj = UserCreateRequest(owningObject, userOptions); @@ -1466,7 +1451,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.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 @@ -1477,7 +1462,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj RuntimeHelpers.PrepareConstrainedRegions(); try { - Bid.PoolerTrace(" %d#, Creating new connection.\n", ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Creating new connection.", ObjectID); obj = UserCreateRequest(owningObject, userOptions); } finally @@ -1488,7 +1473,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.PoolerTraceEvent(" {0}#, Wait timed out.", ObjectID); connection = null; return false; } @@ -1498,24 +1483,28 @@ 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.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): - Bid.PoolerTrace(" %d#, Semaphore handle abandonded.\n", ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Semaphore handle abandonded.", ObjectID); 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.PoolerTraceEvent(" {0}#, Error handle abandonded.", ObjectID); 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.PoolerTraceEvent(" {0}#, Creation handle abandoned.", ObjectID); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(CREATION_HANDLE, _waitHandles.CreationSemaphore); + default: - Bid.PoolerTrace(" %d#, WaitForMultipleObjects=%d\n", ObjectID, waitResult); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, WaitForMultipleObjects={1}", ObjectID, waitResult); Interlocked.Decrement(ref _waitCount); throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult); } @@ -1580,8 +1569,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.PoolerTraceEvent(" {0}#, replacing connection.", ObjectID); DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); if (newConnection != null) @@ -1623,7 +1611,7 @@ private DbConnectionInternal GetFromGeneralPool() if (null != obj) { - Bid.PoolerTrace(" %d#, Connection %d#, Popped from general pool.\n", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Popped from general pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfFreeConnections.Decrement(); } return (obj); @@ -1640,7 +1628,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.PoolerTraceEvent(" {0}#, Connection {1}#, Popped from transacted pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfFreeConnections.Decrement(); if (obj.IsTransactionRoot) @@ -1651,14 +1639,14 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac } catch { - Bid.PoolerTrace(" %d#, Connection %d#, found dead and removed.\n", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); throw; } } else if (!obj.IsConnectionAlive()) { - Bid.PoolerTrace(" %d#, Connection %d#, found dead and removed.\n", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); obj = null; } @@ -1673,11 +1661,7 @@ 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); - + long scopeID = SqlClientEventSource.Log.PoolerScopeEnterEvent(" {0}#", ObjectID); try { if (State.Running == _state) @@ -1762,7 +1746,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.PoolerTraceEvent(" {0}#, PoolCreateRequest called WaitForSingleObject failed {1}", ObjectID, waitResult); } } catch (Exception e) @@ -1776,7 +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. - Bid.PoolerTrace(" %d#, PoolCreateRequest called CreateConnection which threw an exception: %ls", ObjectID, e); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, PoolCreateRequest called CreateConnection which threw an exception: {1}", ObjectID, e); } finally { @@ -1796,7 +1780,7 @@ private void PoolCreateRequest(object state) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.PoolerScopeLeaveEvent(scopeID); } } @@ -1809,8 +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"); - - Bid.PoolerTrace(" %d#, Connection %d#, Pushing to general pool.\n", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Pushing to general pool.", ObjectID, obj.ObjectID); _stackNew.Push(obj); _waitHandles.PoolSemaphore.Release(1); @@ -1859,8 +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. - - Bid.PoolerTrace(" %d#, Connection %d#, Transaction has ended.\n", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Transaction has ended.", ObjectID, obj.ObjectID); if (_state == State.Running && obj.CanBePooled) { @@ -1885,9 +1867,7 @@ private void QueuePoolCreateRequest() private bool ReclaimEmancipatedObjects() { bool emancipatedObjectFound = false; - - Bid.PoolerTrace(" %d#\n", ObjectID); - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#", ObjectID); List reclaimedObjects = new List(); int count; @@ -1939,8 +1919,7 @@ private bool ReclaimEmancipatedObjects() for (int i = 0; i < count; ++i) { DbConnectionInternal obj = reclaimedObjects[i]; - - Bid.PoolerTrace(" %d#, Connection %d#, Reclaiming.\n", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Connection {1}#, Reclaiming.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfReclaimedConnections.Increment(); emancipatedObjectFound = true; @@ -1953,9 +1932,9 @@ private bool ReclaimEmancipatedObjects() internal void Startup() { - Bid.PoolerTrace(" %d#, CleanupWait=%d\n", ObjectID, _cleanupWait); - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, CleanupWait={1}", ObjectID, _cleanupWait); _cleanupTimer = CreateCleanupTimer(); + if (NeedToReplenish) { QueuePoolCreateRequest(); @@ -1964,8 +1943,7 @@ internal void Startup() internal void Shutdown() { - Bid.PoolerTrace(" %d#\n", ObjectID); - + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#", ObjectID); _state = State.ShuttingDown; // deactivate timer callbacks @@ -1985,9 +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. - Bid.PoolerTrace(" %d#, Transaction %d#, Connection %d#, Transaction Completed\n", 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 521b820d31..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 @@ -7,6 +7,8 @@ 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 +273,7 @@ private bool MarkPoolGroupAsActive() if (PoolGroupStateIdle == _state) { _state = PoolGroupStateActive; - Bid.Trace(" %d#, Active\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Active", ObjectID); } return (PoolGroupStateActive == _state); } @@ -333,14 +335,15 @@ internal bool Prune() if (PoolGroupStateActive == _state) { _state = PoolGroupStateIdle; - Bid.Trace(" %d#, Idle\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Idle", ObjectID); } else if (PoolGroupStateIdle == _state) { _state = PoolGroupStateDisabled; - Bid.Trace(" %d#, Disabled\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Disabled", ObjectID); } } + 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..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 @@ -12,6 +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 @@ -86,7 +87,7 @@ internal DbConnectionOptions ConnectionOptions private string ConnectionString_Get() { - Bid.Trace(" %d#\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions connectionOptions = UserConnectionOptions; return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); @@ -129,11 +130,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.TraceEvent(" {0}#, '{1}'", ObjectID, cstr); } internal DbConnectionInternal InnerConnection @@ -179,15 +178,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.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.TraceEvent(" {0}#, Aborting operation due to asynchronous exception: {'OutOfMemory'}", ObjectID); } else { - Bid.Trace(" %d#, Aborting operation due to asynchronous exception: %ls\n", ObjectID, e.ToString()); + SqlClientEventSource.Log.TraceEvent(" {0}#, Aborting operation due to asynchronous exception: {1}", ObjectID, e.ToString()); } } @@ -200,8 +199,7 @@ internal void AddWeakReference(object value, int tag) override protected DbCommand CreateDbCommand() { DbCommand command = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#\n", ObjectID); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); try { DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; @@ -210,7 +208,7 @@ override protected DbCommand CreateDbCommand() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } return command; } @@ -247,7 +245,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.TraceEvent(" {0}#, Connection enlisting in a transaction.", ObjectID); SysTx.Transaction indigoTransaction = null; if (null != transaction) @@ -272,8 +270,7 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans override public void EnlistTransaction(SysTx.Transaction transaction) { SqlConnection.ExecutePermission.Demand(); - - Bid.Trace(" %d#, Connection enlisting in a transaction.\n", 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/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/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationTimeoutRetryHelper.cs index 1ecfc4d681..f0ed91dc24 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 @@ -65,7 +65,9 @@ public ActiveDirectoryAuthenticationTimeoutRetryState State default: throw new InvalidOperationException($"Unsupported state: {value}."); } - _sqlAuthLogger.LogInfo(_typeName, "SetState", $"State changed from {_state} to {value}."); + if (_sqlAuthLogger.IsLoggingEnabled) + _sqlAuthLogger.LogInfo(_typeName, "SetState", $"State changed from {_state} to {value}."); + _state = value; } } @@ -78,17 +80,14 @@ public SqlFedAuthToken CachedToken get { if (_sqlAuthLogger.IsLoggingEnabled) - { _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)}."); - } + _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..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,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.TraceEvent(" 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.TraceEvent(" GetProcAddress for LocalDBCreateInstance error 0x{0}", 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.TraceEvent(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); } s_localDBFormatMessage = (LocalDBFormatMessageDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBFormatMessageDelegate)); @@ -314,7 +314,9 @@ internal static void CreateLocalDBInstance(string instance) } } else - Bid.Trace(" No system.data.localdb section found in configuration"); + { + SqlClientEventSource.Log.TraceEvent(" No system.data.localdb section found in configuration"); + } s_configurableInstances = tempConfigurableInstances; } } @@ -340,14 +342,15 @@ 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.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); - Bid.Trace(" Finished creation of instance %ls", instance); - instanceInfo.created = true; // mark instance as created + } + 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 5fd1cc87cd..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 @@ -6,7 +6,6 @@ namespace Microsoft.Data.SqlClient.Server { - internal class SmiEventSink_Default : SmiEventSink { @@ -268,19 +267,7 @@ internal override void MessagePosted(int number, byte state, byte errorClass, st { 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.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/SqlAuthenticationProviderManager.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs index 39434bf0f7..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 @@ -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/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index ca46138662..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 @@ -593,10 +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.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) @@ -886,8 +884,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i // private Task SubmitUpdateBulkCommand(string TDSCommand) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); - + 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) @@ -2517,7 +2514,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.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 new file mode 100644 index 0000000000..5e90796ade --- /dev/null +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -0,0 +1,614 @@ +// 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; + +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; + + /// + /// 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 + public class Keywords + { + internal const EventKeywords SqlClient = 0; + + internal const EventKeywords Trace = (EventKeywords)1; + + internal const EventKeywords TraceBin = (EventKeywords)2; + + internal const EventKeywords Scope = (EventKeywords)4; + + internal const EventKeywords NotificationTrace = (EventKeywords)8; + + internal const EventKeywords Pooling = (EventKeywords)16; + + internal const EventKeywords Correlation = (EventKeywords)32; + + internal const EventKeywords NotificationScope = (EventKeywords)64; + + internal const EventKeywords PoolerScope = (EventKeywords)128; + + internal const EventKeywords PoolerTrace = (EventKeywords)256; + + internal const EventKeywords Advanced = (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); + + [NonEvent] + internal bool IsTraceBinEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.TraceBin); + + [NonEvent] + internal bool IsScopeEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Scope); + + [NonEvent] + internal bool IsPoolerScopeEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.PoolerScope); + + [NonEvent] + internal bool IsCorrelationEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Correlation); + + [NonEvent] + internal bool IsNotificationScopeEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.NotificationScope); + + [NonEvent] + internal bool IsPoolingEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Pooling); + + [NonEvent] + internal bool IsNotificationTraceEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.NotificationTrace); + + [NonEvent] + internal bool IsPoolerTraceEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.PoolerTrace); + + [NonEvent] + internal bool IsAdvanceTraceOn() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.Advanced); + + [NonEvent] + internal bool IsStateDumpEnabled() => SqlClientEventSource.Log.IsEnabled(EventLevel.Informational, Keywords.StateDump); + + [NonEvent] + internal bool IsSqlClientEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.SqlClient); + #endregion + + #region overloads + //Never use event writer directly as they are not checking for enabled/disabled situations. Always use overloads. + [NonEvent] + internal void TraceEvent(string message, T0 args0) + { + if (Log.IsTraceEnabled()) + { + TraceEvent(string.Format(message, args0)); + } + } + + [NonEvent] + internal void TraceEvent(string message) + { + if (Log.IsTraceEnabled()) + { + Trace(message); + } + } + + [NonEvent] + internal void TraceEvent(string message, T0 args0, T1 args1) + { + if (Log.IsTraceEnabled()) + { + Trace(string.Format(message, args0, args1)); + } + } + + [NonEvent] + internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2) + { + if (Log.IsTraceEnabled()) + { + Trace(string.Format(message, args0, args1, args2)); + } + } + + [NonEvent] + internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + if (Log.IsTraceEnabled()) + { + Trace(string.Format(message, args0, args1, args2, args3)); + } + } + + [NonEvent] + internal void TraceEvent(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 AdvanceTrace(string message) + { + 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 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) + { + if (Log.IsScopeEnabled()) + { + return ScopeEnter(string.Format(message, args0)); + } + return 0; + } + + [NonEvent] + internal long AdvanceScopeEnter(string message, T0 args0) + { + if (Log.IsAdvanceTraceOn()) + { + return ScopeEnter(string.Format(message, args0)); + } + return 0; + } + + [NonEvent] + internal long ScopeEnterEvent(string message) + { + if (Log.IsScopeEnabled()) + { + return ScopeEnter(message); + } + return 0; + } + + [NonEvent] + internal long ScopeEnterEvent(string message, T0 args0, T1 args1) + { + if (Log.IsScopeEnabled()) + { + return ScopeEnter(string.Format(message, args0, args1)); + } + return 0; + } + + [NonEvent] + internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) + { + if (Log.IsScopeEnabled()) + { + return ScopeEnter(string.Format(message, args0, args1, args2)); + } + return 0; + } + + [NonEvent] + internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + if (Log.IsScopeEnabled()) + { + return ScopeEnter(string.Format(message, args0, args1, args2, args3)); + } + return 0; + } + + [NonEvent] + internal long PoolerScopeEnterEvent(string message, T0 args0) + { + if (Log.IsPoolerScopeEnabled()) + { + return PoolerScopeEnter(string.Format(message, args0)); + } + return 0; + } + + [NonEvent] + internal long NotificationsScopeEnterEvent(string message, T0 args0) + { + if (Log.IsNotificationScopeEnabled()) + { + return NotificationsScopeEnter(string.Format(message, args0)); + } + return 0; + } + + [NonEvent] + internal long NotificationsScopeEnterEvent(string message, T0 args0, T1 args1) + { + if (Log.IsNotificationScopeEnabled()) + { + return NotificationsScopeEnter(string.Format(message, args0, args1)); + } + return 0; + } + + [NonEvent] + internal long NotificationsScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) + { + if (Log.IsNotificationScopeEnabled()) + { + return NotificationsScopeEnter(string.Format(message, args0, args1, args2)); + } + return 0; + } + + [NonEvent] + internal long NotificationsScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + if (Log.IsNotificationScopeEnabled()) + { + return NotificationsScopeEnter(string.Format(message, args0, args1, args2, args3)); + } + return 0; + } + + [NonEvent] + internal void PoolerTraceEvent(string message, T0 args0) + { + if (Log.IsPoolerTraceEnabled()) + { + PoolerTrace(string.Format(message, args0)); + } + } + + [NonEvent] + internal void PoolerTraceEvent(string message, T0 args0, T1 args1) + { + if (Log.IsPoolerTraceEnabled()) + { + PoolerTrace(string.Format(message, args0, args1)); + } + } + + [NonEvent] + internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2) + { + if (Log.IsPoolerTraceEnabled()) + { + PoolerTrace(string.Format(message, args0, args1, args2)); + } + } + + [NonEvent] + internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + if (Log.IsPoolerTraceEnabled()) + { + PoolerTrace(string.Format(message, args0, args1, args2, args3)); + } + } + + [NonEvent] + internal void CorrelationTraceEvent(string message, T0 args0) + { + if (Log.IsCorrelationEnabled()) + { + CorrelationTrace(string.Format(message, args0)); + } + } + + [NonEvent] + internal void CorrelationTraceEvent(string message, T0 args0, T1 args1) + { + if (Log.IsCorrelationEnabled()) + { + CorrelationTrace(string.Format(message, args0, args1)); + } + } + + [NonEvent] + internal void CorrelationTraceEvent(string message, T0 args0, T1 args1, T2 args2) + { + if (Log.IsCorrelationEnabled()) + { + CorrelationTrace(string.Format(message, args0, args1, args2)); + } + } + + [NonEvent] + internal void NotificationsTraceEvent(string message) + { + if (Log.IsNotificationTraceEnabled()) + { + NotificationsTrace(message); + } + } + + [NonEvent] + internal void NotificationsTraceEvent(string message, T0 args0) + { + if (Log.IsNotificationTraceEnabled()) + { + NotificationsTrace(string.Format(message, args0)); + } + } + + [NonEvent] + internal void NotificationsTraceEvent(string message, T0 args0, T1 args1) + { + if (Log.IsNotificationTraceEnabled()) + { + NotificationsTrace(string.Format(message, args0, args1)); + } + } + + [NonEvent] + internal void NotificationsTraceEvent(string message, T0 args0, T1 args1, T2 args2) + { + if (Log.IsNotificationTraceEnabled()) + { + NotificationsTrace(string.Format(message, args0, args1, args2)); + } + } + + [NonEvent] + internal void NotificationsTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + if (Log.IsNotificationTraceEnabled()) + { + NotificationsTrace(string.Format(message, args0, args1, args2, args3)); + } + } + + [NonEvent] + internal void TraceBinEvent(string message, T0 args0, T1 args1) + { + if (Log.IsTraceBinEnabled()) + { + TraceBin(string.Format(message, args0, args1)); + } + } + + [NonEvent] + internal void StateDumpEvent(string message, T0 args0, T1 args1) + { + if (Log.IsStateDumpEnabled()) + { + Trace(string.Format(message, args0, args1)); + } + } + + [NonEvent] + internal void ScopeLeaveEvent(long scopeId) + { + if (Log.IsScopeEnabled()) + { + ScopeLeave(scopeId); + } + } + + [NonEvent] + internal void NotificationsScopeLeaveEvent(long scopeId) + { + if (Log.IsNotificationScopeEnabled()) + { + ScopeLeave(scopeId); + } + } + + [NonEvent] + internal void PoolerScopeLeaveEvent(long scopeId) + { + if (Log.IsPoolerScopeEnabled()) + { + ScopeLeave(scopeId); + } + } + + [NonEvent] + internal void AdvanceScopeLeave(long scopeId) + { + if (Log.IsAdvanceTraceOn()) + { + ScopeLeave(scopeId); + } + } + #endregion + + #region Events + [Event(TraceEventId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] + internal void Trace(string message) + { + WriteEvent(TraceEventId, message); + } + + [Event(EnterScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] + internal long ScopeEnter(string message) + { + long scopeId = Interlocked.Increment(ref s_nextScopeId); + WriteEvent(EnterScopeId, message); + return scopeId; + } + + [Event(ExitScopeId, Level = EventLevel.Verbose, Keywords = Keywords.Scope)] + internal void ScopeLeave(long scopeId) + { + WriteEvent(ExitScopeId, scopeId); + } + + [Event(TraceBinId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] + internal void TraceBin(string message) + { + WriteEvent(TraceBinId, message); + } + + [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 = 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 = Interlocked.Increment(ref s_nextPoolerScopeId); + WriteEvent(PoolerScopeEnterId, message); + return scopeId; + } + + [Event(NotificationsTraceId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] + internal void NotificationsTrace(string message) + { + WriteEvent(NotificationsTraceId, message); + } + + [Event(PoolerTraceId, Level = EventLevel.Informational, Keywords = Keywords.PoolerTrace)] + 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). + 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 + // 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) + { + if (Log.IsSqlClientEnabled()) + { + WriteEvent(EndExecuteEventId, objectId, compositeState, sqlExceptionNumber); + } + } + #endregion + } +} 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..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 @@ -4,7 +4,6 @@ namespace Microsoft.Data.SqlClient { - /// public class SqlClientLogger { @@ -17,13 +16,13 @@ internal enum LogLevel /// public void LogInfo(string type, string method, string message) { - Bid.Trace($"{message}\n"); + SqlClientEventSource.Log.TraceEvent("{3}", type, method, LogLevel.Info, message); } /// public void LogError(string type, string method, string message) { - Bid.Trace($"{message}\n"); + SqlClientEventSource.Log.TraceEvent("{3}", type, method, LogLevel.Info, message); } /// @@ -34,7 +33,7 @@ public bool LogAssert(bool value, string type, string method, string message) return value; } - /// - public bool IsLoggingEnabled => Bid.TraceOn; + /// + public bool IsLoggingEnabled => SqlClientEventSource.Log.IsEnabled(); } } 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..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 @@ -345,10 +345,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.AdvanceTrace(" {0}#, rowsAffected={1}.", _command.ObjectID, rowsAffected); _command.InternalRecordsAffected = rowsAffected; // UNDONE: need to fire events back to user code, but this may be called @@ -360,41 +357,31 @@ internal override void StatementCompleted(int rowsAffected) internal override void BatchCompleted() { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#.\n", _command.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#.", _command.ObjectID); } 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); + SqlClientEventSource.Log.AdvanceTrace(" {0}# metaData.Length={1}.", _command.ObjectID, (null != metaData) ? metaData.Length : -1); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + { if (null != metaData) { 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.AdvanceTrace(" {0}#, metaData[{1}] is {2}{3}", _command.ObjectID, i, metaData[i].GetType().ToString(), metaData[i].TraceString()); } } } + 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) - { - Bid.Trace(" %d#, metaData[%d] is %ls%ls\n", - _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); } @@ -576,10 +563,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)); + SqlClientEventSource.Log.TraceEvent(" {0}#, {1}#", ObjectID, (null != value) ? value.ObjectID : -1); } } @@ -657,13 +642,12 @@ public SqlNotificationRequest Notification } set { - Bid.Trace(" %d#\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); _sqlDep = null; _notification = value; } } - internal SqlStatistics Statistics { get @@ -708,7 +692,7 @@ internal SqlStatistics Statistics } // TODO: Add objid here - Bid.Trace(" %d#\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); _transaction = value; } } @@ -743,12 +727,8 @@ 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.TraceEvent(" {0}#, String Value = '{1}'", ObjectID, value); + if (0 != ADP.SrcCompare(_commandText, value)) { PropertyChanging(); @@ -785,11 +765,12 @@ override public int CommandTimeout } set { - Bid.Trace(" %d#, %d\n", ObjectID, value); + SqlClientEventSource.Log.TraceEvent(" {0}#, {1}", ObjectID, value); if (value < 0) { throw ADP.InvalidCommandTimeout(value); } + if (value != _commandTimeout) { PropertyChanging(); @@ -829,7 +810,7 @@ override public CommandType CommandType } set { - Bid.Trace(" %d#, %d{ds.CommandType}\n", ObjectID, (int)value); + SqlClientEventSource.Log.TraceEvent(" {0}#, {1}{2}", ObjectID, (int)value, _commandType); if (_commandType != value) { switch (value) @@ -972,7 +953,7 @@ internal void OnStatementCompleted(int recordCount) { try { - Bid.Trace(" %d#, recordCount=%d\n", ObjectID, recordCount); + SqlClientEventSource.Log.TraceEvent(" {0}#, recordCount={1}", ObjectID, recordCount); handler(this, new StatementCompletedEventArgs(recordCount)); } catch (Exception e) @@ -1010,9 +991,9 @@ override public void Prepare() } SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); + statistics = SqlStatistics.StartTimer(Statistics); // only prepare if batch with parameters @@ -1113,7 +1094,7 @@ override public void Prepare() } SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } private void InternalPrepare() @@ -1177,7 +1158,7 @@ internal void Unprepare() } _cachedMetaData = null; - Bid.Trace(" %d#, Command unprepared.\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Command unprepared.", ObjectID); } // Cancel is supposed to be multi-thread safe. @@ -1187,10 +1168,8 @@ internal void Unprepare() /// override public void Cancel() { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); SqlStatistics statistics = null; try @@ -1309,7 +1288,7 @@ override public void Cancel() finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -1350,14 +1329,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; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + + 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); @@ -1376,7 +1355,7 @@ override public object ExecuteScalar() finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1421,9 +1400,10 @@ 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); + + 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 @@ -1443,7 +1423,7 @@ override public int ExecuteNonQuery() finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1459,8 +1439,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) _pendingCancel = false; SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1470,7 +1449,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -1486,7 +1465,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.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); SqlConnection.ExecutePermission.Demand(); return BeginExecuteNonQueryInternal(0, callback, stateObject, 0, inRetry: false); } @@ -1712,7 +1691,7 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) } finally { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } } @@ -1730,7 +1709,7 @@ private void ThrowIfReconnectionHasBeenCanceled() private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -1965,6 +1944,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))) @@ -1988,9 +1968,11 @@ 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"); - Bid.Trace(" %d#, Command executed as RPC.\n", 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) { @@ -2042,9 +2024,10 @@ public XmlReader ExecuteXmlReader() _pendingCancel = false; SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + + 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 @@ -2067,7 +2050,7 @@ public XmlReader ExecuteXmlReader() finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(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.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); 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.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } } private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); 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.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); 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); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -2381,23 +2363,23 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(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); + 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 { return ExecuteReader(behavior, ADP.ExecuteReader); } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -2412,7 +2394,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.CorrelationTraceEvent(" ObjectID{0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); SqlConnection.ExecutePermission.Demand(); return BeginExecuteReaderInternal(behavior, callback, stateObject, 0, inRetry: false); } @@ -2424,7 +2406,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; @@ -2494,13 +2475,13 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) } finally { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); } } private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2901,8 +2882,7 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string /// public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) { - - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -2987,8 +2967,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.CorrelationTraceEvent(" ObjectID {0}#, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current.ToString()); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3122,8 +3101,7 @@ public Task ExecuteXmlReaderAsync() /// public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken) { - - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3675,7 +3653,6 @@ private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, b bool processFinallyBlock = true; try { - Task reconnectTask = _activeConnection.ValidateAndReconnect(null, timeout); if (reconnectTask != null) @@ -3730,7 +3707,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.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"); @@ -3792,10 +3769,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.AdvanceTrace(" {0}#, innerConnection={1}#, transactionId=0x{2}, cmdBehavior={3}.", ObjectID, innerConnection.ObjectID, transactionId, (int)CommandBehavior.Default); if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { @@ -5274,9 +5248,10 @@ 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.TraceEvent(" {0}#, Command executed as SQLBATCH.", ObjectID); } string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior); + //If the query requires enclave computations, pass the enclavepackage in the SQLBatch TDS stream if (requiresEnclaveComputations) { @@ -5338,7 +5313,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.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. @@ -5361,7 +5336,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi optionSettings = GetSetOptionsString(cmdBehavior); if (returnStream) { - Bid.Trace(" %d#, Command executed as RPC.\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Command executed as RPC.", ObjectID); } // turn set options ON if (null != optionSettings) @@ -5455,11 +5430,7 @@ private SqlDataReader RunExecuteReaderSmi(CommandBehavior cmdBehavior, RunBehavi long transactionId; 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.AdvanceTrace(" {0}#, innerConnection={1}#, transactionId=0x{2}, commandBehavior={(int)cmdBehavior}.", ObjectID, innerConnection.ObjectID, transactionId); if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { @@ -5679,7 +5650,7 @@ private void NotifyDependency() public SqlCommand Clone() { SqlCommand clone = new SqlCommand(this); - Bid.Trace(" %d#, clone=%d#\n", ObjectID, clone.ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, clone={1}#", ObjectID, clone.ObjectID); return clone; } @@ -7466,9 +7437,9 @@ private SmiRequestExecutor SetUpSmiRequest(SqlInternalConnectionSmi innerConnect private void WriteBeginExecuteEvent() { - if (SqlEventSource.Log.IsEnabled() && Connection != null) + if (Connection != null) { - SqlEventSource.Log.BeginExecute(GetHashCode(), Connection.DataSource, Connection.Database, CommandText); + SqlClientEventSource.Log.BeginExecute(GetHashCode(), Connection.DataSource, Connection.Database, CommandText); } } @@ -7480,7 +7451,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.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 @@ -7496,7 +7467,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/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index d47f33ed67..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 @@ -129,9 +129,9 @@ 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.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); @@ -264,7 +264,7 @@ internal static void BuildStoredProcedureName(StringBuilder builder, string part internal void Clear() { - Bid.Trace(" %d#\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); DbCommand batchCommand = BatchCommand; if (null != batchCommand) { @@ -280,7 +280,7 @@ internal void Clear() internal void Dispose() { - Bid.Trace(" %d#\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#", ObjectID); SqlCommand command = _batchCommand; _commandList = null; _batchCommand = null; @@ -294,9 +294,8 @@ internal void Dispose() internal int ExecuteNonQuery() { SqlConnection.ExecutePermission.Demand(); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); try { if (Connection.IsContextConnection) @@ -316,7 +315,7 @@ internal int ExecuteNonQuery() } finally { - Bid.ScopeLeave(ref hscp); + 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 f7b88667d6..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 @@ -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; @@ -30,10 +29,10 @@ 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; using Microsoft.Data.Common; /// @@ -1102,9 +1101,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); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#, isolationLevel={1}", ObjectID, (int)isolationLevel); try { @@ -1120,7 +1117,7 @@ override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLeve } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -1129,10 +1126,7 @@ 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); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#, iso={1}, transactionName='{2}'", ObjectID, (int)iso, (ADP.IsEmpty(transactionName) ? "None" : transactionName)); try { @@ -1160,7 +1154,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); SqlStatistics.StopTimer(statistics); } } @@ -1170,16 +1164,18 @@ override public void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -1189,7 +1185,8 @@ override public void ChangeDatabase(string database) InnerConnection.ChangeDatabase(database); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -1244,7 +1241,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 +1258,9 @@ void CloseInnerConnection() /// override public void Close() { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); + try { SqlStatistics statistics = null; @@ -1277,7 +1273,8 @@ override public void Close() TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -1309,7 +1306,8 @@ override public void Close() } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -1344,7 +1342,9 @@ override public void Close() { SqlDebugContext sdc = _sdc; _sdc = null; - Bid.ScopeLeave(ref hscp); + + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + if (sdc != null) { sdc.Dispose(); @@ -1397,9 +1397,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); + 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 { @@ -1433,7 +1432,7 @@ override public void Open() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -1467,7 +1466,7 @@ private async Task ReconnectAsync(int timeout) { if (ctoken.IsCancellationRequested) { - Bid.Trace(" Orginal ClientConnectionID %ls - reconnection cancelled\n", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TraceEvent(" Orginal ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId.ToString()); return; } try @@ -1488,15 +1487,16 @@ private async Task ReconnectAsync(int timeout) _impersonateIdentity = null; ForceNewConnection = false; } - Bid.Trace(" Reconnection suceeded. ClientConnectionID %ls -> %ls \n", _originalConnectionId.ToString(), ClientConnectionId.ToString()); + + SqlClientEventSource.Log.TraceEvent(" Reconnection suceeded. ClientConnectionID {0} -> {1}", _originalConnectionId.ToString(), ClientConnectionId.ToString()); return; } catch (SqlException e) { - Bid.Trace(" Orginal ClientConnectionID %ls - reconnection attempt failed error %ls\n", _originalConnectionId.ToString(), e.Message); + SqlClientEventSource.Log.TraceEvent(" Orginal ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message); if (attempt == retryCount - 1) { - Bid.Trace(" Orginal ClientConnectionID %ls - give up reconnection\n", _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)) @@ -1560,10 +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; - Bid.Trace(" Connection ClientConnectionID %ls is invalid, reconnecting\n", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TraceEvent(" Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId.ToString()); _recoverySessionData = cData; + if (beforeDisconnect != null) { beforeDisconnect(); @@ -1654,12 +1656,11 @@ void CancelOpenAndWait() /// public override Task OpenAsync(CancellationToken cancellationToken) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls\n", ObjectID); + long scopeID = SqlClientEventSource.Log.PoolerScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); + try { - if (StatisticsEnabled) { if (null == _statistics) @@ -1733,7 +1734,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.PoolerScopeLeaveEvent(scopeID); } } @@ -1754,8 +1755,9 @@ public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource retryTask) { - Bid.Trace(" %d#\n", _parent.ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#", _parent.ObjectID); _registration.Dispose(); + try { SqlStatistics statistics = null; @@ -1867,7 +1869,8 @@ private bool TryOpenInner(TaskCompletionSource retry) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -1921,7 +1924,8 @@ private bool TryOpenInner(TaskCompletionSource retry) } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -2099,7 +2103,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action %d#, Connection broken.\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection broken.", ObjectID); Close(); } }; @@ -2108,7 +2112,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action %d#, Connection broken.\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection broken.", ObjectID); Close(); } } @@ -2213,12 +2217,12 @@ 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.TraceEvent(" {0}#, Message='{1}'", ObjectID, imeventValue); SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage]; + if (null != handler) { notified = true; @@ -2430,9 +2434,9 @@ 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"); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); + SqlClientEventSource.Log.CorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current.ToString()); + try { if (ADP.IsEmpty(connectionString)) @@ -2471,16 +2475,16 @@ public static void ChangePassword(string connectionString, string newPassword) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } /// public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, ""); - Bid.CorrelationTrace(" ActivityID %ls\n"); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); + SqlClientEventSource.Log.CorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current.ToString()); + try { if (ADP.IsEmpty(connectionString)) @@ -2542,7 +2546,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -2648,16 +2652,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 && SqlClientEventSource.Log.IsTraceEnabled()) { - 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.TraceEvent(" SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version.ToString(), TypeSystemAssemblyVersion.ToString()); } asmRef.Version = TypeSystemAssemblyVersion; } + try { return Assembly.Load(asmRef); 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..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 @@ -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.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 2e302fab60..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 @@ -55,7 +55,7 @@ internal void AliasCheck(string server) } else if (_alias != server) { - Bid.Trace(" alias change detected. Clearing PoolGroup\n"); + SqlClientEventSource.Log.TraceEvent(" alias change detected. Clearing PoolGroup"); base.PoolGroup.Clear(); _alias = server; } @@ -99,7 +99,8 @@ 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.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 b8f33b6d94..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,7 +142,7 @@ override public int UpdateBatchSize throw ADP.ArgumentOutOfRange("UpdateBatchSize"); } _updateBatchSize = value; - Bid.Trace(" %d#, %d\n", ObjectID, value); + SqlClientEventSource.Log.TraceEvent(" {0}#, {1}", ObjectID, value); } } @@ -249,7 +249,8 @@ 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.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); + return _commandSet.ExecuteNonQuery(); } @@ -272,7 +273,7 @@ override protected bool GetBatchedRecordsAffected(int commandIdentifier, out int /// override protected void InitializeBatching() { - Bid.Trace(" %d#\n", 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 645d0316f7..dc2f496ff7 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,8 @@ private void CleanPartialReadReliable() override public void Close() { SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1020,7 +1026,7 @@ override public void Close() finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -1039,7 +1045,8 @@ private bool TryCloseInternal(bool closeReader) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -1074,9 +1081,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 +1106,8 @@ private bool TryCloseInternal(bool closeReader) return true; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -1178,7 +1188,8 @@ private bool TryCloseInternal(bool closeReader) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -1204,7 +1215,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 +1670,8 @@ override public int GetProviderSpecificValues(object[] values) override public DataTable GetSchemaTable() { SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1677,7 +1689,7 @@ override public DataTable GetSchemaTable() finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -1839,7 +1851,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 { @@ -2048,7 +2061,8 @@ private bool TryGetBytesInternal(int i, long dataIndex, byte[] buffer, int buffe return true; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -2134,51 +2148,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 @@ -2473,7 +2489,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 { @@ -2569,7 +2586,8 @@ private long GetCharsFromPlpData(int i, long dataIndex, char[] buffer, int buffe return cch; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -3579,17 +3597,17 @@ override public bool NextResult() private bool TryNextResult(out bool more) { SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -3721,7 +3739,8 @@ private bool TryNextResult(out bool more) return true; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -3756,7 +3775,7 @@ private bool TryNextResult(out bool more) finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -3784,17 +3803,17 @@ override public bool Read() private bool TryReadInternal(bool setTimeout, out bool more) { SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -3932,9 +3951,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; } @@ -3945,7 +3966,8 @@ private bool TryReadInternal(bool setTimeout, out bool more) return true; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -3983,7 +4005,7 @@ private bool TryReadInternal(bool setTimeout, out bool more) finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -4011,7 +4033,8 @@ private bool TryReadColumn(int i, bool setTimeout, bool allowPartiallyReadColumn TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -4032,7 +4055,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 @@ -4109,13 +4133,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 @@ -4405,7 +4431,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 @@ -4443,7 +4470,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.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"); @@ -4755,8 +4782,7 @@ private void AssertReaderState(bool requireData, bool permitAsync, int? columnIn /// public override Task NextResultAsync(CancellationToken cancellationToken) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); try { @@ -4802,7 +4828,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) { if (t != null) { - Bid.Trace(" attempt retry %d#\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" attempt retry {0}#", ObjectID); PrepareForAsyncContinuation(); } @@ -4820,7 +4846,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -4884,7 +4910,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.TraceEvent(" attempt retry {0}#", ObjectID); PrepareForAsyncContinuation(); } @@ -5055,9 +5081,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); - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); try { if (IsClosed) @@ -5090,48 +5114,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 @@ -5175,7 +5201,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) { if (t != null) { - Bid.Trace(" attempt retry %d#\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" attempt retry {0}#", ObjectID); PrepareForAsyncContinuation(); } @@ -5214,7 +5240,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -5269,16 +5295,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 } } @@ -5393,13 +5421,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 @@ -5466,16 +5496,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..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 @@ -15,6 +15,8 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; using Microsoft.Data.SqlClient.Server; + + using Microsoft.Data.SqlTypes; namespace Microsoft.Data.SqlClient @@ -26,8 +28,6 @@ namespace Microsoft.Data.SqlClient // This is accomplished by having no public override constructors. internal sealed class SqlDataReaderSmi : SqlDataReader { - - // // IDBRecord properties // @@ -374,8 +374,7 @@ public override void Close() private void CloseInternal(bool closeConnection) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); bool processFinallyBlock = true; try { @@ -411,7 +410,7 @@ private void CloseInternal(bool closeConnection) Connection.Close(); } - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(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); - } + long scopeID = SqlClientEventSource.Log.AdvanceScopeEnter(" {0}#", ObjectID); try { _hasRows = false; @@ -471,10 +466,7 @@ internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) } finally { - if (Bid.AdvancedOn) - { - Bid.ScopeLeave(ref hscp); - } + SqlClientEventSource.Log.AdvanceScopeLeave(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); - } + long scopeID = SqlClientEventSource.Log.AdvanceScopeEnter(" {0}#", 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.AdvanceScopeLeave(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,16 +1315,16 @@ 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.AdvanceTrace(" {0}#, md.Length={1} nextEventIsRow={2}.", reader.ObjectID, mdLength, nextEventIsRow); + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) + { if (null != md) { 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.TraceEvent(" {0}#, metaData[{1}] is {2}{3}", reader.ObjectID, i, md[i].GetType().ToString(), md[i].TraceString()); } } } @@ -1347,57 +1334,40 @@ 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.AdvanceTrace(" {0}# (v2).", reader.ObjectID); this.reader.RowAvailable(row); } internal override void RowAvailable(ITypedGettersV3 row) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# (ITypedGettersV3).\n", reader.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# (ITypedGettersV3).", reader.ObjectID); this.reader.RowAvailable(row); } internal override void RowAvailable(SmiTypedGetterSetter rowData) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# (SmiTypedGetterSetter).\n", reader.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# (SmiTypedGetterSetter).", reader.ObjectID); this.reader.RowAvailable(rowData); } internal override void StatementCompleted(int recordsAffected) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# recordsAffected=%d.\n", 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. - base.StatementCompleted(recordsAffected); this.reader.StatementCompleted(); } internal override void BatchCompleted() { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#.\n", 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 // 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/SqlDelegatedTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs index 6e67948cea..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 @@ -8,6 +8,7 @@ using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Data.Common; + using SysTx = System.Transactions; namespace Microsoft.Data.SqlClient @@ -88,24 +89,26 @@ public void Initialize() // transaction. SqlInternalConnection connection = _connection; SqlConnection usersConnection = connection.Connection; - - Bid.Trace(" %d#, Connection %d#, delegating transaction.\n", ObjectID, connection.ObjectID); - + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection {1}#, delegating transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { #endif //DEBUG if (connection.IsEnlistedInTransaction) - { // defect first - Bid.Trace(" %d#, Connection %d#, was enlisted, now defecting.\n", ObjectID, connection.ObjectID); + { + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection {1}#, was enlisted, now defecting.", ObjectID, connection.ObjectID); + + // defect first connection.EnlistNull(); } @@ -123,7 +126,8 @@ public void Initialize() _active = true; } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -164,17 +168,17 @@ public Byte[] Promote() Exception promoteException; byte[] returnValue = null; SqlConnection usersConnection = connection.Connection; - - Bid.Trace(" %d#, Connection %d#, promoting transaction.\n", ObjectID, connection.ObjectID); - + SqlClientEventSource.Log.TraceEvent(" {0}#, Connection {1}#, promoting transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -227,7 +231,8 @@ public Byte[] Promote() } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -263,17 +268,17 @@ 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.TraceEvent(" {0}#, Connection {1}#, aborting transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -327,7 +332,8 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) enlistment.Aborted(); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -356,17 +362,17 @@ 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.TraceEvent(" {0}#, Connection {1}#, committing transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); + try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -455,7 +461,8 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -487,7 +494,7 @@ internal void TransactionEnded(SysTx.Transaction transaction) if (connection != null) { - Bid.Trace(" %d#, Connection %d#, transaction completed externally.\n", 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 77a79630b1..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 @@ -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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, options: '{1}', timeout: '{2}'", ObjectID, options, timeout); try { if (InOutOfProcHelper.InProc) @@ -341,7 +339,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -438,8 +436,8 @@ public event OnChangeEventHandler OnChange // EventHandlers to be fired when dependency is notified. add { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); + try { if (null != value) @@ -449,13 +447,14 @@ public event OnChangeEventHandler OnChange lock (_eventHandlerLock) { if (_dependencyFired) - { // If fired, fire the new event immediately. - Bid.NotificationsTrace(" Dependency already fired, firing new event.\n"); + { + // If fired, fire the new event immediately. + SqlClientEventSource.Log.NotificationsTrace(" Dependency already fired, firing new event."); 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."); EventContextPair pair = new EventContextPair(value, this); if (!_eventList.Contains(pair)) { @@ -476,13 +475,12 @@ public event OnChangeEventHandler OnChange } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } remove { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { if (null != value) @@ -500,7 +498,7 @@ public event OnChangeEventHandler OnChange } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } } @@ -517,8 +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. - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { if (command == null) @@ -530,7 +527,7 @@ public void AddCommandDependency(SqlCommand command) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -556,9 +553,11 @@ 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."); + #if DEBUG // Possibly expensive, limit to debug. - Bid.NotificationsTrace(" AppDomain.CurrentDomain.FriendlyName: %ls\n", AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.NotificationsTraceEvent(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); + #endif _AppDomain masterDomain = SNINativeMethodWrapper.GetDefaultAppDomain(); @@ -583,32 +582,33 @@ private static void ObtainProcessDispatcher() } else { - Bid.NotificationsTrace(" ERROR - ObjectHandle.Unwrap returned null!\n"); + SqlClientEventSource.Log.NotificationsTrace(" ERROR - ObjectHandle.Unwrap returned null!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyObtainProcessDispatcherFailureObjectHandle); } } else { - Bid.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!\n"); + SqlClientEventSource.Log.NotificationsTrace(" ERROR - AppDomain.CreateInstance returned null!"); 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!"); 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."); + #if DEBUG // Possibly expensive, limit to debug. - Bid.NotificationsTrace(" AppDomain.CurrentDomain.FriendlyName: %ls\n", 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. - Bid.NotificationsTrace(" processDispatcher obtained, ID: %d\n", _processDispatcher.ObjectID); + SqlClientEventSource.Log.NotificationsTraceEvent(" processDispatcher obtained, ID: {0}", _processDispatcher.ObjectID); } } @@ -655,8 +655,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); + 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 @@ -729,7 +728,8 @@ 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.NotificationsTraceEvent(" Start (defaults) returned: '{0}', with service: '{1}', server: '{2}', database: '{3}'", result, service, server, database); } finally { @@ -751,7 +751,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()."); } throw SQL.SqlDependencyDuplicateStart(); } @@ -764,7 +764,8 @@ 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.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. } @@ -778,7 +779,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.NotificationsTraceEvent(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); throw; } } @@ -787,7 +788,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -807,8 +808,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); + 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 @@ -918,7 +918,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -928,8 +928,8 @@ 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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + try { bool result = false; @@ -940,7 +940,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."); identityDatabaseHash = new Dictionary>(); _serverUserHash.Add(server, identityDatabaseHash); } @@ -953,7 +953,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."); databaseServiceList = new List(); identityDatabaseHash.Add(identityUser, databaseServiceList); } @@ -964,13 +964,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!databaseServiceList.Contains(databaseService)) { - Bid.NotificationsTrace(" Adding database.\n"); + SqlClientEventSource.Log.NotificationsTrace(" Adding database."); 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!."); } } @@ -978,14 +978,14 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + try { lock (_serverUserHash) @@ -1005,43 +1005,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."); 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."); 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."); _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!"); 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!"); 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!"); Debug.Assert(false, "Unexpected state - hash did not contain server!"); } } } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1049,8 +1049,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. - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " server: '%ls', failoverServer: '%ls', database: '%ls'", server, failoverServer, database); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" server: '{0}', failoverServer: '{1}', database: '{2}'", server, failoverServer, database); + try { string result; @@ -1060,18 +1060,19 @@ internal static string GetDefaultComposedOptions(string server, string failoverS if (!_serverUserHash.ContainsKey(server)) { if (0 == _serverUserHash.Count) - { // Special error for no calls to start. - Bid.NotificationsTrace(" ERROR - no start calls have been made, about to throw.\n"); + { + // Special error for no calls to start. + SqlClientEventSource.Log.NotificationsTrace(" ERROR - no start calls have been made, about to throw."); 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."); throw SQL.SqlDependencyNoMatchingServerStart(); } } @@ -1084,7 +1085,8 @@ 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."); throw SQL.SqlDependencyNoMatchingServerStart(); } else @@ -1129,20 +1131,21 @@ 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! - Bid.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! + 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!"); - Bid.NotificationsTrace(" resulting options: '%ls'.\n", result); + SqlClientEventSource.Log.NotificationsTraceEvent(" resulting options: '{0}'.", result); return result; } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1154,25 +1157,24 @@ 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); + 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. - Bid.NotificationsTrace(" Server not present in hashtable, adding server: '%ls'.\n", 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); - } } } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1186,8 +1188,7 @@ internal bool ContainsServer(string server) internal string ComputeHashAndAddToDispatcher(SqlCommand command) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, SqlCommand: %d#", 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. @@ -1202,19 +1203,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.NotificationsTraceEvent(" computed id string: '{0}'.", idString); return idString; } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { List eventList = null; @@ -1232,12 +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. - 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 +1251,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (eventList != null) { - Bid.NotificationsTrace(" Firing events.\n"); + SqlClientEventSource.Log.NotificationsTrace(" Firing events."); foreach (EventContextPair pair in eventList) { pair.Invoke(new SqlNotificationEventArgs(type, info, source)); @@ -1260,21 +1260,19 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } // This method is used by SqlCommand. internal void StartTimer(SqlNotificationRequest notificationRequest) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { if (_expirationTime == DateTime.MaxValue) { - Bid.NotificationsTrace(" We've timed out, executing logic.\n"); - + SqlClientEventSource.Log.NotificationsTrace(" We've timed out, executing logic."); int seconds = SQL.SqlDependencyServerTimeout; if (0 != _timeout) { @@ -1292,7 +1290,7 @@ internal void StartTimer(SqlNotificationRequest notificationRequest) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1303,9 +1301,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. + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, SqlCommand: {1}#", ObjectID, cmd.ObjectID); try { SqlConnection connection = cmd.Connection; @@ -1315,7 +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) { - Bid.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception.\n"); + SqlClientEventSource.Log.NotificationsTrace(" ERROR - throwing command has existing SqlNotificationRequest exception."); throw SQL.SqlCommandHasExistingSqlNotificationRequest(); } } @@ -1345,8 +1343,9 @@ 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. - Bid.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point.\n"); + { + // Keep logic just in case. + SqlClientEventSource.Log.NotificationsTrace(" ERROR - firing events, though it is unexpected we have events at this point."); needToInvalidate = true; // Delay invalidation until outside of lock. } } @@ -1360,15 +1359,15 @@ private void AddCommandInternal(SqlCommand cmd) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } } private string ComputeCommandHash(string connectionString, SqlCommand command) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, SqlCommand: %d#", 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, the command text and .ToString on all its parameter values. @@ -1425,13 +1424,12 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) } string result = builder.ToString(); - - Bid.NotificationsTrace(" ComputeCommandHash result: '%ls'.\n", result); + SqlClientEventSource.Log.NotificationsTraceEvent(" ComputeCommandHash result: '{0}'.", result); return result; } finally { - Bid.ScopeLeave(ref hscp); + 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 438315608f..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 @@ -76,12 +76,9 @@ internal int ObjectID // ----------- // Constructor // ----------- - internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, queue: '%ls'", ObjectID, hashHelper.Queue); - + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, queue: '{1}'", ObjectID, HashHelper?.Queue); bool setupCompleted = false; try @@ -104,7 +101,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.NotificationsTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif // Always use ConnectionStringBuilder since in default case it is different from the @@ -219,7 +216,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -279,8 +276,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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, AppDomainKey: '{1}'", ObjectID, appDomainKey); try { Debug.Assert(!ADP.IsEmpty(appDomainKey), "Unexpected empty appDomainKey!"); @@ -290,10 +286,11 @@ internal bool AppDomainUnload(string appDomainKey) lock (_appDomainKeyHash) { if (_appDomainKeyHash.ContainsKey(appDomainKey)) - { // Do nothing if AppDomain did not call Start! - Bid.NotificationsTrace(" _appDomainKeyHash contained AppDomainKey: '%ls'.\n", appDomainKey); + { + // Do nothing if AppDomain did not call Start! + SqlClientEventSource.Log.NotificationsTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}'.", appDomainKey); int value = _appDomainKeyHash[appDomainKey]; - Bid.NotificationsTrace(" _appDomainKeyHash for AppDomainKey: '%ls' count: '%d'.\n", 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; @@ -310,28 +307,26 @@ 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.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 { - Bid.NotificationsTrace(" _appDomainKeyHash did not contain AppDomainKey: '%ls'.\n", appDomainKey); + SqlClientEventSource.Log.NotificationsTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{0}'.", appDomainKey); } } - - Bid.NotificationsTrace(" Exiting, _stopped: '%d'.\n", _stopped); + SqlClientEventSource.Log.NotificationsTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{0}'.", _stopped); return _stopped; } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } private void AsynchronouslyQueryServiceBrokerQueue() { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { AsyncCallback callback = new AsyncCallback(AsyncResultCallback); @@ -339,14 +334,13 @@ private void AsynchronouslyQueryServiceBrokerQueue() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } private void AsyncResultCallback(IAsyncResult asyncResult) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { using (SqlDataReader reader = _com.EndExecuteReader(asyncResult)) @@ -372,8 +366,8 @@ private void AsyncResultCallback(IAsyncResult asyncResult) _errorState = true; throw; } + SqlClientEventSource.Log.NotificationsTrace(" Exception occurred."); - Bid.NotificationsTrace(" Exception occurred.\n"); if (!_stop) { // Only assert if not in cancel path. ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. @@ -392,14 +386,13 @@ private void AsyncResultCallback(IAsyncResult asyncResult) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } private void CreateQueueAndService(bool restart) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { SqlCommand com = new SqlCommand(); @@ -529,19 +522,18 @@ private void CreateQueueAndService(bool restart) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", 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.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. @@ -550,26 +542,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.NotificationsTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{0}', incremented count: '{1}'.", appDomainKey, _appDomainKeyHash[appDomainKey]); } 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.NotificationsTraceEvent(" _appDomainKeyHash did not contain AppDomainKey: '{0}', added to hashtable and value set to 1.", appDomainKey); } } } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } private void ProcessNotificationResults(SqlDataReader reader) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { Guid handle = Guid.Empty; // Conversation_handle. Always close this! @@ -579,16 +570,20 @@ private void ProcessNotificationResults(SqlDataReader reader) { while (reader.Read()) { - Bid.NotificationsTrace(" Row read.\n"); + SqlClientEventSource.Log.NotificationsTrace(" Row read."); #if DEBUG - for (int i=0; i column: %ls, value: %ls\n", reader.GetName(i), reader.GetValue(i).ToString()); + if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) + { + for (int i = 0; i < reader.FieldCount; i++) + { + SqlClientEventSource.Log.NotificationsTraceEvent(" column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i).ToString()); + } } #endif string msgType = reader.GetString(0); - Bid.NotificationsTrace(" msgType: '%ls'\n", msgType); + SqlClientEventSource.Log.NotificationsTraceEvent(" msgType: '{0}'", msgType); handle = reader.GetGuid(1); - // Bid.NotificationsTrace(" conversationHandle: '%p(GUID)'\n", 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)) @@ -600,7 +595,7 @@ private void ProcessNotificationResults(SqlDataReader reader) if (null != notification) { string key = notification.Key; - Bid.NotificationsTrace(" Key: '%ls'\n", key); + SqlClientEventSource.Log.NotificationsTraceEvent(" Key: '{0}'", key); int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash" if (index >= 0) @@ -629,25 +624,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!"); } } else { Debug.Assert(false, "Unexpected ID format received!"); - Bid.NotificationsTrace(" Unexpected ID format received!\n"); + SqlClientEventSource.Log.NotificationsTrace(" Unexpected ID format received!"); } } 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!"); } } 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!"); } } else @@ -655,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!"); - Bid.NotificationsTrace(" Unexpected message format received!\n"); + SqlClientEventSource.Log.NotificationsTrace(" Unexpected message format received!"); } } } @@ -687,7 +682,7 @@ private void ProcessNotificationResults(SqlDataReader reader) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -696,9 +691,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. + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { try @@ -860,14 +855,13 @@ private void Restart(object unused) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } internal bool Stop(string appDomainKey, out bool appDomainStop) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { appDomainStop = false; @@ -887,15 +881,15 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) int value = _appDomainKeyHash[appDomainKey]; Debug.Assert(value > 0, "Unexpected count for appDomainKey"); + SqlClientEventSource.Log.NotificationsTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}', pre-decrement Count: '{1}'.", appDomainKey, value); - Bid.NotificationsTrace(" _appDomainKeyHash contained AppDomainKey: '%ls', pre-decrement Count: '%d'.\n", appDomainKey, value); if (value > 0) { _appDomainKeyHash[appDomainKey] = value - 1; } else { - Bid.NotificationsTrace(" ERROR pre-decremented count <= 0!\n"); + SqlClientEventSource.Log.NotificationsTrace(" ERROR pre-decremented count <= 0!"); Debug.Assert(false, "Unexpected AppDomainKey count in Stop()"); } @@ -907,7 +901,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!"); Debug.Assert(false, "Unexpected state on Stop() - no AppDomainKey entry in hashtable!"); } } @@ -918,8 +912,9 @@ 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"); + // Lock to ensure Cancel() complete prior to other thread calling TearDown. + SqlClientEventSource.Log.NotificationsTrace(" Reached 0 count, cancelling and waiting."); + lock (this) { try @@ -962,8 +957,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.NotificationsTraceEvent(" forcing cleanup. elapsedSeconds: '{0}', _errorState: '{1}'.", retryStopwatch.Elapsed.Seconds, _errorState); Timer retryTimer = _retryTimer; _retryTimer = null; if (retryTimer != null) @@ -982,7 +976,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - Bid.NotificationsTrace(" _startCount not 0 after decrement. _startCount: '%d'.\n", _startCount); + SqlClientEventSource.Log.NotificationsTraceEvent(" _startCount not 0 after decrement. _startCount: '{0}'.", _startCount); } Debug.Assert(0 <= _startCount, "Invalid start count state"); @@ -991,14 +985,14 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } private void SynchronouslyQueryServiceBrokerQueue() { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); + try { using (SqlDataReader reader = _com.ExecuteReader()) @@ -1008,15 +1002,15 @@ private void SynchronouslyQueryServiceBrokerQueue() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } [SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")] private void TearDownAndDispose() { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); + try { lock (this) @@ -1089,7 +1083,7 @@ private void TearDownAndDispose() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } } @@ -1233,42 +1227,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.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) { - Bid.Trace(" Not all expected attributes in Message; messageAttributes = '%d'.\n", (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()) { - Bid.Trace(" unexpected Read failure on xml or unexpected structure of xml.\n"); + 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 ((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.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); 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.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); 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.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } @@ -1278,7 +1272,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.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } @@ -1289,7 +1283,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - Bid.Trace(" unexpected Read failure on xml or unexpected structure of xml.\n"); + SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } } @@ -1298,7 +1292,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - Bid.Trace(" unexpected Read failure on xml or unexpected structure of xml.\n"); + SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; // failure } } @@ -1478,20 +1472,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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { #if DEBUG // Possibly expensive, limit to debug. - Bid.NotificationsTrace(" %d#, AppDomain.CurrentDomain.FriendlyName: %ls\n", ObjectID, AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); #endif _connectionContainers = new Dictionary(); _sqlDependencyPerAppDomainDispatchers = new Dictionary(); } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1499,19 +1492,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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", 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.NotificationsTraceEvent(" {0}#, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); #endif } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1537,8 +1529,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS out string user, string queue) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, queue: %ls", _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. @@ -1571,7 +1562,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1583,8 +1574,7 @@ public override object InitializeLifetimeService() private void Invalidate(string server, SqlNotification sqlNotification) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, server: %ls", ObjectID, server); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, server: {1}", ObjectID, server); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1616,7 +1606,7 @@ private void Invalidate(string server, SqlNotification sqlNotification) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1633,8 +1623,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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { string appDomainKey = (string)state; @@ -1666,7 +1655,7 @@ private void AppDomainUnloading(object state) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1733,8 +1722,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); + 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!"); @@ -1761,7 +1749,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.NotificationsTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif bool started = false; @@ -1771,7 +1759,7 @@ private bool Start(string connectionString, { if (!_connectionContainers.ContainsKey(hashHelper)) { - Bid.NotificationsTrace(" %d#, hashtable miss, creating new container.\n", ObjectID); + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, hashtable miss, creating new container.", ObjectID); container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults); _connectionContainers.Add(hashHelper, container); started = true; @@ -1780,10 +1768,10 @@ private bool Start(string connectionString, else { container = _connectionContainers[hashHelper]; - Bid.NotificationsTrace(" %d#, hashtable hit, container: %d\n", ObjectID, container.ObjectID); + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, hashtable hit, container: {1}", ObjectID, container.ObjectID); if (container.InErrorState) { - Bid.NotificationsTrace(" %d#, container: %d is in error state!\n", 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 @@ -1798,16 +1786,15 @@ 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.NotificationsTraceEvent(" {0}#, default service: '{1}', server: '{2}', database: '{3}'", ObjectID, queueService, server, database); } - Bid.NotificationsTrace(" %d#, started: %d\n", ObjectID, started); - + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, started: {1}", ObjectID, started); return started; } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -1824,8 +1811,7 @@ internal bool Stop(string connectionString, string appDomainKey, out bool appDomainStop) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, queue: '%ls'", ObjectID, queueService); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, queue: '{1}'", ObjectID, queueService); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1843,7 +1829,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.NotificationsTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif bool stopped = false; @@ -1853,7 +1839,8 @@ 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.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; queueService = container.Queue; @@ -1865,16 +1852,16 @@ internal bool Stop(string connectionString, } else { - Bid.NotificationsTrace(" %d#, hashtable miss.\n", ObjectID); + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, hashtable miss.", ObjectID); } } - Bid.NotificationsTrace(" %d#, stopped: %d\n", ObjectID, stopped); + SqlClientEventSource.Log.NotificationsTraceEvent(" {0}#, stopped: {1}", ObjectID, stopped); return stopped; } finally { - Bid.ScopeLeave(ref hscp); + 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 d7d21960d3..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 @@ -92,8 +92,7 @@ internal int ObjectID private SqlDependencyPerAppDomainDispatcher() { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", ObjectID); try { _dependencyIdToDependencyHash = new Dictionary(); @@ -107,7 +106,7 @@ private SqlDependencyPerAppDomainDispatcher() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -125,8 +124,7 @@ public override object InitializeLifetimeService() private void UnloadEventHandler(object sender, EventArgs e) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#", ObjectID); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#", 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.NotificationsScopeLeaveEvent(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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, SqlDependency: {1}#", ObjectID, dep.ObjectID); try { lock (this) @@ -163,24 +160,23 @@ internal void AddDependencyEntry(SqlDependency dep) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, commandHash: '{1}', SqlDependency: {2}#", ObjectID, commandHash, 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"); + { + // 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."); } 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."); dependencyList.Add(dep); } else { - Bid.NotificationsTrace(" Dependency already present for commandHash.\n"); + SqlClientEventSource.Log.NotificationsTrace(" Dependency already present for commandHash."); } } else @@ -220,8 +216,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) SqlDependency.AppDomainKey, // must be first 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."); DependencyList dependencyList = new DependencyList(commandHash); dependencyList.Add(dep); @@ -243,7 +238,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } return notificationId; @@ -252,8 +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) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, commandHash: '%ls'", ObjectID, sqlNotification.Key); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, commandHash: '{1}'", ObjectID, sqlNotification.Key); try { List dependencyList = null; @@ -264,8 +258,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) if (null != dependencyList) { - Bid.NotificationsTrace(" commandHash found in hashtable.\n"); - + 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. @@ -277,7 +270,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } else { - Bid.NotificationsTrace(" commandHash NOT found in hashtable.\n"); + SqlClientEventSource.Log.NotificationsTrace(" commandHash NOT found in hashtable."); } } @@ -286,8 +279,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."); try { dependency.Invalidate(sqlNotification.Type, sqlNotification.Info, sqlNotification.Source); @@ -308,15 +300,14 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, server: '{1}'", ObjectID, server); try { List dependencies = new List(); @@ -363,15 +354,14 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, Key: '{1}'", ObjectID, id); try { if (null == id) @@ -393,7 +383,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."); } } @@ -401,22 +391,21 @@ internal SqlDependency LookupDependencyEntry(string id) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, id: '{1}'", ObjectID, id); try { lock (this) { if (_dependencyIdToDependencyHash.ContainsKey(id)) { - Bid.NotificationsTrace(" Entry found in hashtable - removing.\n"); + SqlClientEventSource.Log.NotificationsTrace(" Entry found in hashtable - removing."); _dependencyIdToDependencyHash.Remove(id); // if there are no more dependencies then we can dispose the timer. @@ -428,21 +417,20 @@ private void LookupDependencyEntryWithRemove(string id) } else { - Bid.NotificationsTrace(" Entry NOT found in hashtable.\n"); + SqlClientEventSource.Log.NotificationsTrace(" Entry NOT found in hashtable."); } } } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(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); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, commandHash: '{1}'", ObjectID, notificationId); try { DependencyList entry = null; @@ -451,7 +439,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."); // update the tables - do it inside finally block to avoid ThreadAbort exception interrupt this operation try @@ -465,7 +453,7 @@ private List LookupCommandEntryWithRemove(string notificationId) } else { - Bid.NotificationsTrace(" Entries NOT found in hashtable.\n"); + SqlClientEventSource.Log.NotificationsTrace(" Entries NOT found in hashtable."); } Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!"); @@ -475,15 +463,16 @@ private List LookupCommandEntryWithRemove(string notificationId) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(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); + + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" {0}#, SqlDependency: {1}#", ObjectID, dependency.ObjectID); + try { lock (this) @@ -496,7 +485,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.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 @@ -529,7 +518,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } @@ -539,8 +528,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende internal void StartTimer(SqlDependency dep) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " %d#, SqlDependency: %d#", 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 @@ -551,8 +539,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."); _timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */); // Save this as the earlier timeout to come. @@ -561,7 +548,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."); // Save this as the earlier timeout to come. _nextTimeout = dep.ExpirationTime; @@ -570,14 +557,13 @@ internal void StartTimer(SqlDependency dep) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(scopeID); } } private static void TimeoutTimerCallback(object state) { - IntPtr hscp; - Bid.NotificationsScopeEnter(out hscp, " AppDomainKey: '%ls'", SqlDependency.AppDomainKey); + long scopeID = SqlClientEventSource.Log.NotificationsScopeEnterEvent(" AppDomainKey: '{0}'", SqlDependency.AppDomainKey); try { SqlDependency[] dependencies; @@ -590,12 +576,13 @@ 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."); return; } if (SingletonInstance._nextTimeout > DateTime.UtcNow) { - Bid.NotificationsTrace(" No timeouts expired, exiting.\n"); + SqlClientEventSource.Log.NotificationsTrace(" No timeouts expired, exiting."); + // No dependency timed-out yet. return; } @@ -665,7 +652,7 @@ private static void TimeoutTimerCallback(object state) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.NotificationsScopeLeaveEvent(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..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,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.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 0ac838bab2..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 @@ -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.AdvanceTrace(" {0}# deactivating", ObjectID); 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 @@ -434,20 +435,12 @@ protected void Enlist(SysTx.Transaction tx) 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.AdvanceTrace(" {0}#, transaction {1}#.", ObjectID, tx.GetHashCode()); bool hasDelegatedTransaction = false; if (IsYukonOrNewer) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, attempting to delegate\n", base.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, attempting to delegate", ObjectID); // Promotable transactions are only supported on Yukon // servers or newer. @@ -513,20 +506,8 @@ private void EnlistNonNull(SysTx.Transaction tx) if (hasDelegatedTransaction) { - this.DelegatedTransaction = delegatedTransaction; - - if (Bid.AdvancedOn) - { - 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); - } + 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) @@ -559,11 +540,7 @@ private void EnlistNonNull(SysTx.Transaction tx) if (!hasDelegatedTransaction) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, delegation not possible, enlisting.\n", base.ObjectID); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}#, delegation not possible, enlisting.", ObjectID); byte[] cookie = null; if (_isGlobalTransaction) @@ -592,25 +569,12 @@ private void EnlistNonNull(SysTx.Transaction tx) // send cookie to server to finish enlistment PropagateTransactionCookie(cookie); - _isEnlistedInTransaction = true; - - if (Bid.AdvancedOn) - { - 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); - } + 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 - // 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 @@ -629,10 +593,7 @@ private void EnlistNonNull(SysTx.Transaction tx) internal void EnlistNull() { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, unenlisting.\n", base.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 @@ -645,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 (Bid.AdvancedOn) - { - Bid.Trace(" %d#, unenlisted.\n", base.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 @@ -704,7 +661,8 @@ override public void EnlistTransaction(SysTx.Transaction transaction) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -713,7 +671,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..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 @@ -12,7 +12,6 @@ namespace Microsoft.Data.SqlClient { - sealed internal class SqlInternalConnectionSmi : SqlInternalConnection { @@ -66,55 +65,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.AdvanceTrace(" {0}#, databaseName='{1}'.", _connection.ObjectID, databaseName); _connection.CurrentDatabase = databaseName; } internal override void TransactionCommitted(long transactionId) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transactionId=0x%I64x.\n", _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 (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transactionId=0x%I64x.\n", _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 (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transactionId=0x%I64x.\n", _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 (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transactionId=0x%I64x.\n", _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 (Bid.AdvancedOn) - { - Bid.Trace(" %d#, transactionId=0x%I64x.\n", _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); @@ -122,10 +103,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.AdvanceTrace(" {0}#, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionStarted(transactionId, false); // not distributed; } } @@ -141,11 +119,7 @@ internal SqlInternalConnectionSmi(SqlConnectionString connectionOptions, SmiCont Debug.Assert(null != _smiConnection, "null SmiContext.ContextConnection?"); _smiEventSink = new EventSink(this); - - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, constructed new SMI internal connection\n", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, constructed new SMI internal connection", ObjectID); } internal SmiContext InternalContext @@ -295,15 +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 (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.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) { @@ -311,28 +277,19 @@ 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.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 (Bid.AdvancedOn) - { - Bid.Trace(" %d#, no transaction.\n", base.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, no transaction.", ObjectID); } else { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, using current System.Transaction.\n", base.ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, using current System.Transaction.", ObjectID); base.Enlist(currentSystemTransaction); } } @@ -345,10 +302,7 @@ override protected void ChangeDatabaseInternal(string database) override protected void InternalDeactivate() { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Deactivating.\n", base.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. @@ -377,21 +331,13 @@ override protected void InternalDeactivate() override internal void DelegatedTransactionEnded() { base.DelegatedTransactionEnded(); - - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, cleaning up after Delegated Transaction Completion\n", base.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 (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Disconnecting Transaction %d#.\n", base.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"); @@ -415,17 +361,9 @@ 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 - ); - } + 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) { case TransactionRequest.Begin: @@ -479,17 +417,15 @@ 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.AdvanceTrace(" whereAbouts = {0}, Length = {1}", whereAbouts, (ushort)whereAbouts.Length); } + else + { + SqlClientEventSource.Log.AdvanceTrace(" whereAbouts=null"); + } + return whereAbouts; } @@ -513,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 (Bid.AdvancedOn) - { - Bid.Trace(" %d# context is out of scope\n", base.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... @@ -544,16 +477,14 @@ 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.AdvanceTrace(" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); + } + else + { + SqlClientEventSource.Log.AdvanceTrace(" null"); } // Propagate the transaction cookie to the server @@ -587,7 +518,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..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 @@ -20,6 +20,7 @@ using Microsoft.Identity.Client; using SysTx = System.Transactions; + namespace Microsoft.Data.SqlClient { internal class SessionStateRecord @@ -368,19 +369,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 +454,8 @@ internal SqlInternalConnectionTds( TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -483,7 +490,8 @@ internal SqlInternalConnectionTds( } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -508,10 +516,7 @@ internal SqlInternalConnectionTds( ThreadHasParserLockForClose = false; _parserLock.Release(); } - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, constructed new TDS internal connection\n", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, constructed new TDS internal connection", ObjectID); } // 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.AdvanceTrace(" {0}# disposing", ObjectID); 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.TraceEvent(" {0}#, Server did not acknowledge the federated authentication request", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged); } if (_federatedAuthenticationInfoRequested && !_federatedAuthenticationInfoReceived) { - Bid.Trace(" %d#, Server never sent the requested federated authentication info\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Server never sent the requested federated authentication info", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoNotReceived); } @@ -1403,11 +1405,7 @@ private void CompleteLogin(bool enlistOK) _parser.EnableMars(); _fConnectionOpen = true; // mark connection as open - - if (Bid.AdvancedOn) - { - Bid.Trace(" Post-Login Phase: Server connection obtained.\n"); - } + 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 @@ -1536,7 +1534,7 @@ private void Login(ServerInfo server, TimeoutTimer timeout, string newPassword, private void LoginFailure() { - Bid.Trace(" %d#\n", 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. @@ -1662,10 +1660,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.AdvanceTrace(" {0}#, host={1}", ObjectID, serverInfo.UserServerName); + int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. ResolveExtendedServerName(serverInfo, !redirectedUserInstance, connectionOptions); @@ -1770,7 +1766,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt if (_routingInfo != null) { - Bid.Trace(" Routed to %ls", serverInfo.ExtendedServerName); + SqlClientEventSource.Log.TraceEvent(" Routed to {0}", serverInfo.ExtendedServerName); if (routingAttempts > _maxNumberOfRedirectRoute) { @@ -1859,10 +1855,8 @@ 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.AdvanceTrace(" {0}#, sleeping {1}[milisec]", ObjectID, sleepInterval); + Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } @@ -1943,15 +1937,8 @@ 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={3}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName, failoverHost ?? "null"); - 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"); - } int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. long timeoutUnitInterval; @@ -2018,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 (Bid.AdvancedOn) - { - Bid.Trace(" %d#, new failover partner=%ls\n", ObjectID, ServerProvidedFailOverPartner); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); failoverServerInfo.SetDerivedNames(protocol, ServerProvidedFailOverPartner); } currentServerInfo = failoverServerInfo; @@ -2054,7 +2038,7 @@ TimeoutTimer timeout } routingAttempts++; - Bid.Trace(" Routed to %ls", _routingInfo.ServerName); + SqlClientEventSource.Log.TraceEvent(" Routed to {0}", _routingInfo.ServerName); if (_parser != null) _parser.Disconnect(); @@ -2123,10 +2107,7 @@ 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.AdvanceTrace(" {0}#, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } @@ -2201,12 +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 (Bid.AdvancedOn) - { - Bid.Trace(" %d#, timout=%I64d{msec}, server=", ObjectID, timeout.MillisecondsRemaining); - Bid.PutStr(serverInfo.ExtendedServerName); - Bid.Trace("\n"); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); _routingInfo = null; // forget routing information @@ -2301,24 +2277,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 @@ -2355,9 +2333,10 @@ internal bool GetSessionAndReconnectIfNeeded(SqlConnection parent, int timeout = internal void BreakConnection() { - var connection = Connection; - Bid.Trace(" %d#, Breaking connection.\n", 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(); @@ -2447,10 +2426,7 @@ internal void OnEnvChange(SqlEnvChange rec) break; case TdsEnums.ENV_ROUTING: - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Received routing info\n", 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); @@ -2494,9 +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."); - - Bid.Trace(" %d#, Generating federated authentication token\n", 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. @@ -2527,17 +2501,21 @@ 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.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 {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); 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 +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 (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.AdvanceTrace(" {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. @@ -2563,14 +2540,11 @@ 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.TraceEvent(" {0}#, The attempt to get a new access token succeeded under the locked mode.", ObjectID); } } - 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.AdvanceTrace(" {0}#, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); } } @@ -2630,13 +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()) { - 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.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 { - Bid.Trace(" %d#, Refreshing the context is already in progress by another thread.\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Refreshing the context is already in progress by another thread.", ObjectID); } if (authenticationContextLocked) @@ -2794,8 +2770,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) || _timeout.IsExpired || _timeout.MillisecondsRemaining <= sleepInterval) { - - Bid.Trace(" %s#\n", msalException.ErrorCode); + SqlClientEventSource.Log.TraceEvent(" {0}#", msalException.ErrorCode); // Error[0] SqlErrorCollection sqlErs = new SqlErrorCollection(); @@ -2814,8 +2789,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.AdvanceTrace(" {0}#, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); + SqlClientEventSource.Log.AdvanceTrace(" {0}#, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); Thread.Sleep(sleepInterval); sleepInterval *= 2; @@ -2831,9 +2806,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) DateTime expirationTime = DateTime.FromFileTimeUtc(fedAuthToken.expirationFileTime); _newDbConnectionPoolAuthenticationContext = new DbConnectionPoolAuthenticationContext(fedAuthToken.accessToken, expirationTime); } - - Bid.Trace(" %d#, Finished generating federated authentication token.\n", ObjectID); - + SqlClientEventSource.Log.TraceEvent(" {0}#, Finished generating federated authentication token.", ObjectID); return fedAuthToken; } @@ -2855,8 +2828,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 +2869,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.AdvanceTrace(" {0}#, Received feature extension acknowledgement for federated authentication", ObjectID); + if (!_federatedAuthenticationRequested) { - Bid.Trace(" %d#, Did not request federated authentication\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Did not request federated authentication", ObjectID); throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); } @@ -2914,14 +2886,15 @@ 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.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"); - Bid.Trace(" %d#, Attempting to use unknown federated authentication library\n", ObjectID); + + SqlClientEventSource.Log.TraceEvent(" {0}#, Attempting to use unknown federated authentication library", ObjectID); throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType); } _federatedAuthenticationAcknowledged = true; @@ -2938,11 +2911,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.TraceEvent(" {0}#, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); } - else { - Bid.Trace(" %d#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value. \n", ObjectID); + else + { + SqlClientEventSource.Log.TraceEvent(" {0}#, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); } #endif } @@ -2951,21 +2926,17 @@ 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.AdvanceTrace(" {0}#, Received feature extension acknowledgement for TCE", ObjectID); if (data.Length < 1) { - Bid.Trace(" %d#, Unknown version number for TCE\n", 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) { - Bid.Trace(" %d#, Invalid version number for TCE\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Invalid version number for TCE", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidVersion, supportedTceVersion); } @@ -2984,14 +2955,12 @@ 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.AdvanceTrace(" {0}#, Received feature extension acknowledgement for GlobalTransactions", ObjectID); if (data.Length < 1) { - Bid.Trace(" %d#, Unknown version number for GlobalTransactions\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Unknown version number for GlobalTransactions", ObjectID); + throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } @@ -3005,52 +2974,43 @@ 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.AdvanceTrace(" {0}#, Received feature extension acknowledgement for AzureSQLSupport", ObjectID); if (data.Length < 1) { - Bid.Trace(" %d#, Unknown token for AzureSQLSupport\n", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } IsAzureSQLConnection = true; // Bit 0 for RO/FP support - if ((data[0] & 1) == 1) + if ((data[0] & 1) == 1 && SqlClientEventSource.Log.IsTraceEnabled()) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, FailoverPartner enabled with Readonly intent for AzureSQL DB\n", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, FailoverPartner enabled with Readonly intent for AzureSQL DB", ObjectID); } break; } case TdsEnums.FEATUREEXT_DATACLASSIFICATION: { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, Received feature extension acknowledgement for DATACLASSIFICATION\n", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); if (data.Length < 1) { - Bid.Trace(" %d#, Unknown token for DATACLASSIFICATION\n", 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)) { - Bid.Trace(" %d#, Invalid version number for DATACLASSIFICATION\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Invalid version number for DATACLASSIFICATION", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.DataClassificationInvalidVersion, supportedDataClassificationVersion); } if (data.Length != 2) { - Bid.Trace(" %d#, Unknown token for DATACLASSIFICATION\n", ObjectID); + SqlClientEventSource.Log.TraceEvent(" {0}#, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte enabled = data[1]; @@ -3060,14 +3020,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.AdvanceTrace(" {0}#, Received feature extension acknowledgement for UTF8 support", ObjectID); if (data.Length < 1) { - Bid.Trace(" %d#, Unknown value for UTF8 support\n", 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/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..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 @@ -2,7 +2,6 @@ // 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; @@ -10,6 +9,7 @@ using System.Runtime.CompilerServices; using Microsoft.Data.Common; + namespace Microsoft.Data.SqlClient { /// @@ -142,10 +142,8 @@ override public void Commit() ZombieCheck(); SqlStatistics statistics = null; - IntPtr hscp; - - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - Bid.CorrelationTrace(" ObjectID%d#, ActivityID %ls", ObjectID); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -155,7 +153,8 @@ override public void Commit() TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -168,7 +167,8 @@ override public void Commit() _internalTransaction.Commit(); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -206,7 +206,7 @@ override public void Commit() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -223,7 +223,8 @@ protected override void Dispose(bool disposing) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -235,7 +236,8 @@ protected override void Dispose(bool disposing) } } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -266,10 +268,8 @@ 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.AdvanceTrace(" {0}# partial zombie no rollback required", ObjectID); + _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); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); + SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}#, ActivityID {1}", ObjectID, ActivityCorrelator.Current.ToString()); 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.ScopeLeaveEvent(scopeID); } } } @@ -341,9 +342,7 @@ public void Rollback(string transactionName) ZombieCheck(); SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d# transactionName='%ls'", ObjectID, transactionName); - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}# transactionName='{1}'", ObjectID, transactionName); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -352,7 +351,8 @@ public void Rollback(string transactionName) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -365,7 +365,8 @@ public void Rollback(string transactionName) _internalTransaction.Rollback(transactionName); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -391,7 +392,7 @@ public void Rollback(string transactionName) _isFromAPI = false; SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -403,8 +404,7 @@ public void Save(string savePointName) ZombieCheck(); SqlStatistics statistics = null; - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d# savePointName='%ls'", ObjectID, savePointName); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}# savePointName='{1}'", ObjectID, savePointName); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -414,7 +414,8 @@ public void Save(string savePointName) TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); - try { + try + { tdsReliabilitySection.Start(); #else { @@ -425,7 +426,8 @@ public void Save(string savePointName) _internalTransaction.Save(savePointName); } #if DEBUG - finally { + finally + { tdsReliabilitySection.Stop(); } #endif //DEBUG @@ -449,7 +451,7 @@ public void Save(string savePointName) finally { SqlStatistics.StopTimer(statistics); - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -465,12 +467,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.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 cb4fc848db..54e707380b 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,12 +427,10 @@ private bool IncludeTraceHeader { get { - return (_isDenali && Bid.TraceOn && Bid.IsOn(ActivityCorrelator.CorrelationTracePoints)); + return (_isDenali && SqlClientEventSource.Log.IsEnabled()); } - } - internal int IncrementNonTransactedOpenResultCount() { // IMPORTANT - this increments the connection wide open result count for all @@ -504,26 +502,27 @@ 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.TraceEvent(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication", "SEC"); } else { _sniSpnBuffer = null; if (authType == SqlAuthenticationMethod.ActiveDirectoryPassword) { - Bid.Trace(" Active Directory Password authentication\n"); + SqlClientEventSource.Log.TraceEvent(" Active Directory Password authentication", "SEC"); } else if (authType == SqlAuthenticationMethod.SqlPassword) { - Bid.Trace(" SQL Password authentication\n"); + + SqlClientEventSource.Log.TraceEvent(" SQL Password authentication", "SEC"); } else if (authType == SqlAuthenticationMethod.ActiveDirectoryInteractive) { - Bid.Trace(" Active Directory Interactive authentication\n"); + SqlClientEventSource.Log.TraceEvent(" Active Directory Interactive authentication", "SEC"); } else { - Bid.Trace(" SQL authentication\n"); + SqlClientEventSource.Log.TraceEvent(" SQL authentication", "SEC"); } } @@ -560,7 +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(); - Bid.Trace(" Login failure\n"); + SqlClientEventSource.Log.TraceEvent(" Login failure", "ERR|SEC"); ThrowExceptionAndWarning(_physicalStateObj); Debug.Fail("SNI returned status != success, but no error thrown?"); } @@ -590,21 +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 - Bid.Trace(" Sending prelogin handshake\n"); + 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; + SqlClientEventSource.Log.TraceEvent(" Consuming prelogin handshake", "SEC"); - Bid.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.TraceEvent(" Prelogin handshake unsuccessful. Reattempting prelogin handshake", "SEC"); _physicalStateObj.Dispose(); // Close previous connection // On Instance failure re-connect and flush SNI named instance cache. @@ -614,14 +613,15 @@ internal void Connect(ServerInfo serverInfo, if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); - Bid.Trace(" Login failure\n"); + SqlClientEventSource.Log.TraceEvent(" Login failure", "ERR|SEC"); + 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.TraceEvent(" Sending prelogin handshake", "SEC"); - Bid.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); @@ -630,11 +630,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.TraceEvent(" Prelogin handshake unsuccessful. Login failure", "ERR|SEC"); throw SQL.InstanceFailure(); } } - Bid.Trace(" Prelogin handshake successful\n"); + SqlClientEventSource.Log.TraceEvent(" Prelogin handshake successful", "SEC"); if (_fMARS && marsCapable) { @@ -726,10 +726,7 @@ 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.AdvanceTrace(" {0}# created session {1}", ObjectID, session.ObjectID); return session; } @@ -744,18 +741,12 @@ 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.AdvanceTrace(" {0}# getting session {1} from pool", ObjectID, session.ObjectID); } else { session = _physicalStateObj; - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# getting physical session %d\n", 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; @@ -969,7 +960,8 @@ 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.TraceEvent(" ClientConnectionID {0}, ActivityID {1}", _connHandler._clientConnectionId.ToString(), actId.ToString()); break; case (int)PreLoginOptions.FEDAUTHREQUIRED: @@ -1280,7 +1272,9 @@ 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.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]); } @@ -1321,15 +1315,8 @@ internal void Deactivate(bool connectionIsDoomed) { // Called when the connection that owns us is deactivated. - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# deactivating\n", ObjectID); - } - - if (Bid.IsOn(Bid.ApiGroup.StateDump)) - { - Bid.Trace(" %d#, %ls\n", ObjectID, TraceString()); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}# deactivating", ObjectID); + SqlClientEventSource.Log.StateDumpEvent(" {0}#, {1}", ObjectID, TraceString()); if (MARSOn) { @@ -1485,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.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!"); @@ -2084,7 +2071,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; @@ -2205,7 +2191,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.TraceEvent(" Potential multi-threaded misuse of connection, unexpected TDS token found {0}#", ObjectID); throw SQL.ParsingErrorToken(ParsingErrorState.InvalidTdsTokenReceived, token); // MDAC 82443 } @@ -2527,7 +2513,8 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead } case TdsEnums.SQLLOGINACK: { - Bid.Trace(" Received login acknowledgement token\n"); + SqlClientEventSource.Log.TraceEvent(" Received login acknowledgement token", "SEC"); + SqlLoginAck ack; if (!TryProcessLoginAck(stateObj, out ack)) { @@ -2549,7 +2536,8 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead { _connHandler._federatedAuthenticationInfoReceived = true; SqlFedAuthInfo info; - Bid.Trace(" Received federated authentication info token\n"); + SqlClientEventSource.Log.TraceEvent(" Received federated authentication info token", "SEC"); + if (!TryProcessFedAuthInfo(stateObj, tokenLength, out info)) { return false; @@ -2882,6 +2870,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); @@ -3206,7 +3195,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; @@ -3231,6 +3219,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. @@ -3278,6 +3267,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)) { @@ -3887,7 +3877,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 @@ -3995,16 +3984,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 (Bid.AdvancedOn) - { - Bid.Trace(" FEDAUTHINFO token stream length = {0}\n", 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 - Bid.Trace(" FEDAUTHINFO token stream length too short for CountOfInfoIDs.\n"); + SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen); } @@ -4012,15 +3997,13 @@ 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.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 (Bid.AdvancedOn) - { - Bid.Trace(" CountOfInfoIDs = {0}\n", optionsCount.ToString(CultureInfo.InvariantCulture)); - } + tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount + SqlClientEventSource.Log.AdvanceTrace(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); if (tokenLen > 0) { @@ -4029,14 +4012,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.AdvanceTrace(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); 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.TraceEvent(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}", tokenLen, totalRead); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadTokenStream); } @@ -4057,11 +4037,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 (Bid.AdvancedOn) - { - Bid.Trace(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}\n", 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 @@ -4073,7 +4049,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.TraceEvent(" FedAuthInfoDataOffset points to an invalid location.", "ERR"); throw SQL.ParsingErrorOffset(ParsingErrorState.FedAuthInfoInvalidOffset, unchecked((int)dataOffset)); } @@ -4085,19 +4061,15 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } catch (ArgumentOutOfRangeException e) { - Bid.Trace(" Failed to read FedAuthInfoData.\n"); + SqlClientEventSource.Log.TraceEvent(" Failed to read FedAuthInfoData.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadData, e); } catch (ArgumentException e) { - Bid.Trace(" FedAuthInfoData is not in unicode format.\n"); + SqlClientEventSource.Log.TraceEvent(" FedAuthInfoData is not in unicode format.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e); } - - if (Bid.AdvancedOn) - { - Bid.Trace(" FedAuthInfoData: {0}\n", data); - } + SqlClientEventSource.Log.AdvanceTrace(" FedAuthInfoData: {0}", data); // store data in tempFedAuthInfo switch ((TdsEnums.FedAuthInfoId)id) @@ -4109,26 +4081,22 @@ 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.AdvanceTrace(" Ignoring unknown federated authentication info option: {0}", id); break; } } } else { - Bid.Trace(" FEDAUTHINFO token stream is not long enough to contain the data it claims to.\n"); + SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream is not long enough to contain the data it claims to.", "ERR"); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForData, tokenLen); } - Bid.Trace(" Processed FEDAUTHINFO token stream: {0}\n", tempFedAuthInfo.ToString()); - - if (String.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || String.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) + 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 - Bid.Trace(" FEDAUTHINFO token stream does not contain both STSURL and SPN.\n"); + SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream does not contain both STSURL and SPN.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDoesNotContainStsurlAndSpn); } @@ -4219,6 +4187,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) @@ -4556,7 +4525,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.TraceEvent(" Incorrect ordinal received {0}, max tab size: {1}", index, cipherTable.Value.Size); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidOrdinalIntoCipherInfoTable, index); } } @@ -8823,10 +8792,7 @@ internal void TdsLogin(SqlLogin rec, } WriteInt(log7Flags, _physicalStateObj); - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, TDS Login7 flags = %d:\n", 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 @@ -8985,7 +8951,7 @@ internal void TdsLogin(SqlLogin rec, }; if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) { - Bid.Trace(" Sending federated authentication feature request\n"); + SqlClientEventSource.Log.TraceEvent(" Sending federated authentication feature request", "SEC"); Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null."); WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true); }; @@ -9058,8 +9024,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.TraceEvent(" Sending federated authentication token", "SEC"); _physicalStateObj._outputMessageType = TdsEnums.MT_FEDAUTH; @@ -9450,11 +9415,7 @@ internal SqlDataReader TdsExecuteTransactionManagerRequest( 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.TraceEvent(" Exception caught on ExecuteXXX: '{0}'", e.ToString()); if (stateObj.HasOpenResult) { // SQL BU DT 383773 - need to decrement openResultCount if operation failed. @@ -9487,8 +9448,7 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) _connHandler.ThreadHasParserLockForClose = originalThreadHasParserLock; } } - - Bid.Trace(" Exception rethrown. \n"); + 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) @@ -9544,7 +9504,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.TraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}#", ObjectID); } stateObj.SniContext = SniContext.Snix_Execute; @@ -9673,7 +9633,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.TraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}#", ObjectID); } stateObj.SniContext = SniContext.Snix_Execute; @@ -10536,12 +10496,8 @@ 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.AdvanceTrace(" {0}#, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); // // Write parameter metadata @@ -11597,7 +11553,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.NotificationsTraceEvent(" NotificationRequest: userData: '{0}', options: '{1}', timeout: '{2}'", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj); // Query notifications Type @@ -11624,7 +11580,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.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 8eb369c2c9..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 @@ -36,10 +36,7 @@ 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.AdvanceTrace(" {0}# created session pool for parser {1}", ObjectID, parser.ObjectID); } private bool IsDisposed @@ -63,10 +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. - - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d# deactivating cachedCount=%d\n", ObjectID, _cachedCount); - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}# deactivating cachedCount={1}", ObjectID, _cachedCount); try { lock (_cache) @@ -85,12 +79,7 @@ internal void Deactivate() if (session.IsOrphaned) { // 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.AdvanceTrace(" {0}# reclaiming session {1}", ObjectID, session.ObjectID); PutSession(session); } } @@ -101,7 +90,7 @@ internal void Deactivate() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -124,11 +113,7 @@ internal void BestEffortCleanup() internal void Dispose() { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# disposing cachedCount=%d\n", ObjectID, _cachedCount); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}# disposing cachedCount={1}", ObjectID, _cachedCount); lock (_cache) { // Dispose free sessions @@ -187,11 +172,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.AdvanceTrace(" {0}# adding session {1} to pool", ObjectID, session.ObjectID); _cache.Add(session); _cachedCount = _cache.Count; @@ -199,12 +180,7 @@ internal TdsParserStateObject GetSession(object owner) session.Activate(owner); } - - if (Bid.AdvancedOn) - { - Bid.Trace(" %d# using session %d\n", ObjectID, session.ObjectID); - } - + SqlClientEventSource.Log.AdvanceTrace(" {0}# using session {1}", ObjectID, session.ObjectID); return session; } @@ -226,10 +202,7 @@ 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.AdvanceTrace(" {0}# keeping session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); Debug.Assert(!session._pendingData, "pending data on a pooled session?"); _freeStateObjects[_freeStateObjectCount] = session; @@ -238,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 (Bid.AdvancedOn) - { - Bid.Trace(" %d# disposing session %d cachedCount=%d\n", 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 85e5e5dd4c..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 @@ -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 @@ -556,12 +559,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.TraceEvent(" {0}#, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount); + SqlClientEventSource.Log.TraceBinEvent(" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); return true; } @@ -791,7 +790,7 @@ private void ResetCancelAndProcessAttention() { tdsReliabilitySection.Start(); #endif //DEBUG - Parser.ProcessPendingAck(this); + Parser.ProcessPendingAck(this); #if DEBUG } finally @@ -914,17 +913,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.AdvanceTrace(" {0}#, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); if ((0 == remaining || release) && _gcHandle.IsAllocated) { - if (Bid.AdvancedOn) - { - Bid.Trace(" %d#, FREEING HANDLE!\n", ObjectID); - } + SqlClientEventSource.Log.AdvanceTrace(" {0}#, FREEING HANDLE!", ObjectID); _gcHandle.Free(); } @@ -1032,10 +1025,8 @@ 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.AdvanceTrace(" {0}#, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}"); return remaining; } @@ -1375,15 +1366,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 +1424,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 +2154,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.TraceEvent(" Async packet replay{0}", "INFO"); return true; } #if DEBUG - else { - if (_checkNetworkPacketRetryStacks) { + else + { + if (_checkNetworkPacketRetryStacks) + { _lastStack = new StackTrace(); } } @@ -2186,10 +2186,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 +2246,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 +2435,8 @@ internal void ReadSni(TaskCompletionSource completion) } #if DEBUG - if (_forcePendingReadsToWaitForUser) { + if (_forcePendingReadsToWaitForUser) + { _realNetworkPacketTaskSource = new TaskCompletionSource(); } #endif @@ -2500,7 +2504,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 +2581,8 @@ 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.TraceEvent(" received error {0} on idle connection", (int)error); + isAlive = false; if (throwOnException) { @@ -2789,14 +2795,8 @@ public void ProcessSniPacket(IntPtr packet, UInt32 error) #endif } } - SniReadStatisticsAndTracing(); - - if (Bid.AdvancedOn) - { - Bid.TraceBin(" Packet read", _inBuff, (UInt16)_inBytesRead); - } - + SqlClientEventSource.Log.AdvanceTraceBin(" Packet read", _inBuff, (ushort)_inBytesRead); AssertValidState(); } else @@ -2836,7 +2836,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 +2953,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.TraceEvent(" write async returned error code {0}", (int)sniError); try { AddError(_parser.ProcessSNIError(this)); @@ -2995,16 +2996,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 +3017,8 @@ public void WriteAsyncCallback(IntPtr key, IntPtr packet, UInt32 sniError) } } #if DEBUG - if (SqlCommand.DebugForceAsyncWriteDelay > 0) { + if (SqlCommand.DebugForceAsyncWriteDelay > 0) + { return; } #endif @@ -3399,30 +3405,37 @@ 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.TraceEvent(" write async returned error code {0}", (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; + } #endif else @@ -3446,7 +3459,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.TraceEvent(" write async returned error code {0}", (int)sniError); AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(callerHasConnectionLock); } @@ -3487,35 +3500,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.TraceEvent(" Send Attention ASync.", "Info"); + } + finally { - _parser.Connection.ThreadHasParserLockForClose = false; - _parser.Connection._parserLock.Release(); + if (releaseLock) + { + _parser.Connection.ThreadHasParserLockForClose = false; + _parser.Connection._parserLock.Release(); + } } - } #if DEBUG } @@ -3529,11 +3542,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.AdvanceTraceBin(" Packet sent", _outBuff, (ushort)_outBytesUsed); + SqlClientEventSource.Log.TraceEvent(" Attention sent to the server.", "Info"); AssertValidState(); } @@ -3652,7 +3662,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 @@ -3688,8 +3699,7 @@ private void SniWriteStatisticsAndTracing() statistics.SafeAdd(ref statistics._bytesSent, _outBytesUsed); statistics.RequestNetworkServerTimer(); } - - if (Bid.AdvancedOn) + if (SqlClientEventSource.Log.IsAdvanceTraceOn()) { // 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 @@ -3718,8 +3728,8 @@ private void SniWriteStatisticsAndTracing() _traceChangePasswordOffset = 0; _traceChangePasswordLength = 0; } - Bid.TraceBin(" Packet sent", _outBuff, (UInt16)_outBytesUsed); } + SqlClientEventSource.Log.AdvanceTraceBin(" Packet sent", _outBuff, (ushort)_outBytesUsed); } [Conditional("DEBUG")] @@ -3993,22 +4003,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 +4033,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 +4120,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..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 @@ -53,11 +53,7 @@ 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); + 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; @@ -272,8 +268,8 @@ internal void CloseFromConnection() SqlInternalConnection innerConnection = _innerConnection; Debug.Assert(innerConnection != null, "How can we be here if the connection is null?"); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Closing", ObjectID); - Bid.PoolerTrace(" %d#, Closing\n", ObjectID); bool processFinallyBlock = true; try { @@ -300,9 +296,7 @@ internal void CloseFromConnection() internal void Commit() { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { throw SQL.ConnectionLockedForBcpEvent(); @@ -346,7 +340,7 @@ internal void Commit() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -375,7 +369,8 @@ internal void Dispose() private /*protected override*/ void Dispose(bool disposing) { - Bid.PoolerTrace(" %d#, Disposing\n", ObjectID); + SqlClientEventSource.Log.PoolerTraceEvent(" {0}#, Disposing", ObjectID); + if (disposing) { if (null != _innerConnection) @@ -430,8 +425,7 @@ internal void InitParent(SqlTransaction transaction) internal void Rollback() { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#", ObjectID); + var scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { @@ -472,14 +466,13 @@ internal void Rollback() } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } internal void Rollback(string transactionName) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#, transactionName='%ls'", ObjectID, transactionName); + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#, transactionName='{transactionName}'", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { @@ -522,15 +515,13 @@ internal void Rollback(string transactionName) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } internal void Save(string savePointName) { - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d#, savePointName='%ls'", ObjectID, savePointName); - + long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}#, savePointName='{savePointName}'", ObjectID); _innerConnection.ValidateConnectionForExecute(null); try @@ -561,7 +552,7 @@ internal void Save(string savePointName) } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(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 deleted file mode 100644 index 2135c362e5..0000000000 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlEventSource.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. - -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); - } - } -} 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 982927ca66..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 @@ -12,6 +12,7 @@ using System.Diagnostics; using System.Runtime.Versioning; using Microsoft.Data.Common; +using Microsoft.Data.SqlClient; namespace Microsoft.Data.SqlTypes { @@ -64,10 +65,7 @@ public SqlFileStream Int64 allocationSize ) { - - IntPtr hscp; - Bid.ScopeEnter(out hscp, " %d# access=%d options=%d path='%ls' ", 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 { //----------------------------------------------------------------- @@ -92,7 +90,7 @@ Int64 allocationSize } finally { - Bid.ScopeLeave(ref hscp); + SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); } } @@ -715,8 +713,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.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, 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..74eac0d06d --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/EventSource/EventSourceTest.cs @@ -0,0 +1,61 @@ +// 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 Xunit; + +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 EventTraceTests() + { + GetIds(); + //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(DataTestUtility.TCPConnectionString)) + { + connection.Open(); + using (SqlCommand command = new SqlCommand("SELECT * From [Customers]", connection)) + { + command.ExecuteNonQuery(); + } + ids = TraceListener.IDs; + } + ids = TraceListener.IDs; + } + } + } + + [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp, "Not Implemented")] + public class TraceEventListener : EventListener + { + public List IDs = new List(); + protected override void OnEventSourceCreated(EventSource eventSource) + { + if (eventSource.Name.Equals("Microsoft.Data.SqlClient.EventSource")) + { + EnableEvents(eventSource, EventLevel.Informational, (EventKeywords)1); + } + } + + protected override void OnEventWritten(EventWrittenEventArgs eventData) + { + IDs.Add(eventData.EventId); + } + } +} 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 eb9afe1731..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,6 +56,7 @@ +