diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs index 74d812cf5d..396d43caa6 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs @@ -39,7 +39,7 @@ static private void TraceException(string trace, Exception e) Debug.Assert(null != e, "TraceException: null Exception"); if (null != e) { - SqlClientEventSource.Log.TraceEvent(trace, e); + SqlClientEventSource.Log.TryTraceEvent(trace, e); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index cfbdd659eb..1ee4cba196 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -49,7 +49,7 @@ protected DbConnectionFactory() public void ClearAllPools() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" connectionPoolGroups = _connectionPoolGroups; @@ -64,14 +64,14 @@ public void ClearAllPools() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } public void ClearPool(DbConnection connection) { ADP.CheckArgumentNull(connection, nameof(connection)); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", GetObjectId(connection)); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", GetObjectId(connection)); try { DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); @@ -82,7 +82,7 @@ public void ClearPool(DbConnection connection) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -90,7 +90,7 @@ public void ClearPool(DbConnectionPoolKey key) { Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, nameof(key) + "." + nameof(key.ConnectionString)); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" connectionString"); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" connectionString"); try { DbConnectionPoolGroup poolGroup; @@ -102,7 +102,7 @@ public void ClearPool(DbConnectionPoolKey key) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -126,7 +126,7 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne { newConnection.MakeNonPooledObject(owningConnection); } - SqlClientEventSource.Log.TraceEvent(" {0}, Non-pooled database connection created.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Non-pooled database connection created.", ObjectID); return newConnection; } @@ -140,7 +140,7 @@ internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbCo { newConnection.MakePooledConnection(pool); } - SqlClientEventSource.Log.TraceEvent(" {0}, Pooled database connection created.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Pooled database connection created.", ObjectID); return newConnection; } @@ -195,7 +195,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)) { - SqlClientEventSource.Log.TraceEvent(" {0}, DisabledPoolGroup={1}", ObjectID, connectionPoolGroup.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, DisabledPoolGroup={1}", ObjectID, connectionPoolGroup?.ObjectID); // reusing existing pool option in case user originally used SetConnectionPoolOptions DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions; @@ -303,7 +303,7 @@ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, D private void PruneConnectionPoolGroups(object state) { // when debugging this method, expect multiple threads at the same time - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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 @@ -323,7 +323,7 @@ private void PruneConnectionPoolGroups(object state) if (0 == pool.Count) { _poolsToRelease.Remove(pool); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, ReleasePool={1}", ObjectID, pool.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, ReleasePool={1}", ObjectID, pool.ObjectID); } } } @@ -347,7 +347,7 @@ private void PruneConnectionPoolGroups(object state) if (0 == poolsLeft) { _poolGroupsToRelease.Remove(poolGroup); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, ReleasePoolGroup={1}", ObjectID, poolGroup.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, ReleasePoolGroup={1}", ObjectID, poolGroup.ObjectID); } } } @@ -410,7 +410,7 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { Debug.Assert(null != poolGroup, "null poolGroup?"); - SqlClientEventSource.Log.TraceEvent(" {0}, poolGroup={1}", ObjectID, poolGroup.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, poolGroup={1}", ObjectID, poolGroup.ObjectID); lock (_poolGroupsToRelease) { diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index fdb2042b54..0e92ed4f00 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -225,7 +225,7 @@ internal void DeactivateConnection() { // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Deactivating", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Deactivating", ObjectID); #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); @@ -249,14 +249,14 @@ internal void DeactivateConnection() protected internal void DoNotPoolThisConnection() { _cannotBePooled = true; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Marking pooled object as non-poolable so it will be disposed", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Marking pooled object as non-poolable so it will be disposed", ObjectID); } /// Ensure that this connection cannot be put back into the pool. protected internal void DoomThisConnection() { _connectionIsDoomed = true; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Dooming", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Dooming", ObjectID); } // Reset connection doomed status so it can be re-connected and pooled. @@ -383,7 +383,7 @@ internal void PrePush(object expectedOwner) throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time } - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Preparing to push into pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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% } @@ -412,7 +412,7 @@ internal void PostPop(object newOwner) } _owningObject.Target = newOwner; _pooledCount--; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Preparing to pop from pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs index 4c8e9adec6..5801057092 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -229,7 +229,7 @@ private bool MarkPoolGroupAsActive() if (PoolGroupStateIdle == _state) { _state = PoolGroupStateActive; - SqlClientEventSource.Log.TraceEvent(" {0}, Active", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Active", ObjectID); } return (PoolGroupStateActive == _state); } @@ -281,12 +281,12 @@ internal bool Prune() if (PoolGroupStateActive == _state) { _state = PoolGroupStateIdle; - SqlClientEventSource.Log.TraceEvent(" {0}, Idle", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Idle", ObjectID); } else if (PoolGroupStateIdle == _state) { _state = PoolGroupStateDisabled; - SqlClientEventSource.Log.TraceEvent(" {0}, Disabled", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Disabled", ObjectID); } } return (PoolGroupStateDisabled == _state); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs index e7613a4616..4d929e4031 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs @@ -31,8 +31,8 @@ internal static class ExceptionBuilder Debug.Assert(null != e, "TraceException: null Exception"); if (null != e) { - SqlClientEventSource.Log.AdvancedTraceEvent(trace, e.Message); - SqlClientEventSource.Log.AdvancedTraceEvent(" Environment StackTrace = '{0}'", Environment.StackTrace); + SqlClientEventSource.Log.TryAdvancedTraceEvent(trace, e.Message); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Environment StackTrace = '{0}'", Environment.StackTrace); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index eed3ff6970..d620caa34a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -129,7 +129,7 @@ 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); + SqlClientEventSource.Log.TryTraceEvent(" {0}, GetConnection failed because a pool timeout occurred.", ObjectID); // If GetConnection failed while the pool is running, the pool timeout occurred. throw ADP.PooledOpenTimeout(); } @@ -147,7 +147,7 @@ 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); + SqlClientEventSource.Log.TryTraceEvent(" {0}, GetConnection failed because a pool timeout occurred and all retries were exhausted.", ObjectID); // exhausted all retries or timed out - give up throw ADP.PooledOpenTimeout(); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index 7f959eb1c9..232aef3c77 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -105,7 +105,7 @@ protected internal Transaction EnlistedTransaction if (null != value) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Enlisting.", ObjectID, value.GetHashCode()); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Enlisting.", ObjectID, value.GetHashCode()); TransactionOutcomeEnlist(value); } } @@ -211,7 +211,7 @@ internal void ActivateConnection(Transaction transaction) { // Internal method called from the connection pooler so we don't expose // the Activate method publicly. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Activating", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Activating", ObjectID); #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); @@ -261,7 +261,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac //////////////////////////////////////////////////////////////// Debug.Assert(null != owningObject, "null owningObject"); Debug.Assert(null != connectionFactory, "null connectionFactory"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0} Closing.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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 @@ -336,7 +336,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. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Delegated Transaction Completed.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Delegated Transaction Completed.", ObjectID); if (1 == _pooledCount) { @@ -428,7 +428,7 @@ internal void DetachCurrentTransactionIfEnded() // Detach transaction from connection. internal void DetachTransaction(Transaction transaction, bool isExplicitlyReleasing) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction Completed. (pooledCount={1})", ObjectID, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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 @@ -468,7 +468,7 @@ internal void CleanupConnectionOnTransactionCompletion(Transaction transaction) void TransactionCompletedEvent(object sender, TransactionEventArgs e) { Transaction transaction = e.Transaction; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); CleanupTransactionOnCompletion(transaction); CleanupConnectionOnTransactionCompletion(transaction); } @@ -481,18 +481,18 @@ private void TransactionOutcomeEnlist(Transaction transaction) internal void SetInStasis() { _isInStasis = true; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID); } private void TerminateStasis(bool returningToPool) { if (returningToPool) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed. Returning to general pool.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed. Returning to general pool.", ObjectID); } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed/leaked. Disposing.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed/leaked. Disposing.", ObjectID); } _isInStasis = false; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index 90ada93ff3..d0921da04c 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -74,7 +74,7 @@ internal TransactedConnectionPool(DbConnectionPool pool) _pool = pool; _transactedCxns = new Dictionary(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Constructed for connection pool {1}", ObjectID, _pool.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Constructed for connection pool {1}", ObjectID, _pool.ObjectID); } internal int ObjectID @@ -133,7 +133,7 @@ internal DbConnectionInternal GetTransactedObject(Transaction transaction) if (null != transactedObject) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } return transactedObject; } @@ -160,7 +160,7 @@ internal void PutTransactedObject(Transaction transaction, DbConnectionInternal lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); connections.Add(transactedObject); } } @@ -195,13 +195,13 @@ internal void PutTransactedObject(Transaction transaction, DbConnectionInternal lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); connections.Add(transactedObject); } } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Adding List to transacted pool.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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); @@ -229,13 +229,13 @@ internal void PutTransactedObject(Transaction transaction, DbConnectionInternal } } } - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Added.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Added.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } } internal void TransactionEnded(Transaction transaction, DbConnectionInternal transactedObject) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); TransactedConnectionList connections; int entry = -1; @@ -269,7 +269,7 @@ internal void TransactionEnded(Transaction transaction, DbConnectionInternal tra // safely remove the list from the transacted pool. if (0 >= connections.Count) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Removing List from transacted pool.", ObjectID, transaction.GetHashCode()); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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 @@ -285,7 +285,7 @@ internal void TransactionEnded(Transaction transaction, DbConnectionInternal tra } else { - 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); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transacted pool not yet created prior to transaction completing. Connection may be leaked.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } } @@ -443,7 +443,7 @@ internal WaitHandle[] GetHandles(bool withCreate) _poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback _state = State.Running; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Constructed.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Constructed.", ObjectID); //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls // StartBackgroundCallbacks after pool is actually in the collection @@ -586,7 +586,7 @@ private void CleanupCallback(object state) // // With this logic, objects are pruned from the pool if unused for // at least one period but not more than two periods. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}", ObjectID); // Destroy free objects that put us above MinPoolSize from old stack. while (Count > MinPoolSize) @@ -658,7 +658,7 @@ private void CleanupCallback(object state) break; Debug.Assert(obj != null, "null connection is not expected"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, ChangeStacks={1}", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, ChangeStacks={1}", ObjectID, obj.ObjectID); Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); Debug.Assert(obj.CanBePooled, "pooled object is not poolable"); @@ -673,7 +673,7 @@ private void CleanupCallback(object state) internal void Clear() { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Clearing.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Clearing.", ObjectID); DbConnectionInternal obj; // First, quickly doom everything. @@ -707,7 +707,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(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Cleared.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Cleared.", ObjectID); } private Timer CreateCleanupTimer() => @@ -758,7 +758,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio } } } - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Added to pool.", ObjectID, newObj != null ? newObj?.ObjectID.ToString() ?? "null" : "null"); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Added to pool.", ObjectID, newObj?.ObjectID); // Reset the error wait: _errorWait = ERROR_WAIT_DEFAULT; @@ -816,7 +816,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio private void DeactivateObject(DbConnectionInternal obj) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Deactivating.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Deactivating.", ObjectID, obj.ObjectID); obj.DeactivateConnection(); bool returnToGeneralPool = false; @@ -951,11 +951,11 @@ internal void DestroyObject(DbConnectionInternal obj) // again. if (obj.IsTxRootWaitingForTxEnd) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Has Delegated Transaction, waiting to Dispose.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Has Delegated Transaction, waiting to Dispose.", ObjectID, obj.ObjectID); } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Removing from pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Removing from pool.", ObjectID, obj.ObjectID); bool removed = false; lock (_objectList) { @@ -966,16 +966,16 @@ internal void DestroyObject(DbConnectionInternal obj) if (removed) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Removed from pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Removed from pool.", ObjectID, obj.ObjectID); } obj.Dispose(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Disposed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Disposed.", ObjectID, obj.ObjectID); } } private void ErrorCallback(object state) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Resetting Error handling.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Resetting Error handling.", ObjectID); _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); @@ -1106,7 +1106,7 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource {0}, DbConnectionInternal State != Running.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, DbConnectionInternal State != Running.", ObjectID); connection = null; return true; } @@ -1146,7 +1146,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj { DbConnectionInternal obj = null; Transaction transaction = null; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Getting connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Getting connection.", ObjectID); // If automatic transaction enlistment is required, then we try to // get the connection from the transacted connection pool first. @@ -1181,19 +1181,19 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj switch (waitResult) { case WaitHandle.WaitTimeout: - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Wait timed out.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Wait timed out.", ObjectID); Interlocked.Decrement(ref _waitCount); connection = null; return false; case ERROR_HANDLE: // Throw the error that PoolCreateRequest stashed. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Errors are set.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Errors are set.", ObjectID); Interlocked.Decrement(ref _waitCount); throw TryCloneCachedException(); case CREATION_HANDLE: - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Creating new connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Creating new connection.", ObjectID); try { obj = UserCreateRequest(owningObject, userOptions); @@ -1243,7 +1243,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj if ((obj != null) && (!obj.IsConnectionAlive())) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); obj = null; // Setting to null in case creating a new object fails @@ -1253,7 +1253,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj { try { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Creating new connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Creating new connection.", ObjectID); obj = UserCreateRequest(owningObject, userOptions); } finally @@ -1264,7 +1264,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj else { // Timeout waiting for creation semaphore - return null - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Wait timed out.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Wait timed out.", ObjectID); connection = null; return false; } @@ -1273,7 +1273,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj break; default: - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, WaitForMultipleObjects={1}", ObjectID, waitResult); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, WaitForMultipleObjects={1}", ObjectID, waitResult); Interlocked.Decrement(ref _waitCount); throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult); } @@ -1287,7 +1287,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj } // Do not use this pooled connection if access token is about to expire soon before we can connect. - if(null != obj && obj.IsAccessTokenExpired) + if (null != obj && obj.IsAccessTokenExpired) { DestroyObject(obj); obj = null; @@ -1332,7 +1332,7 @@ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal o /// A new inner connection that is attached to the internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, replacing connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, replacing connection.", ObjectID); DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); if (newConnection != null) @@ -1373,7 +1373,7 @@ private DbConnectionInternal GetFromGeneralPool() if (null != obj) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Popped from general pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Popped from general pool.", ObjectID, obj.ObjectID); } return (obj); } @@ -1389,7 +1389,7 @@ private DbConnectionInternal GetFromTransactedPool(out Transaction transaction) if (null != obj) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Popped from transacted pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Popped from transacted pool.", ObjectID, obj.ObjectID); if (obj.IsTransactionRoot) { @@ -1399,14 +1399,14 @@ private DbConnectionInternal GetFromTransactedPool(out Transaction transaction) } catch { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); throw; } } else if (!obj.IsConnectionAlive()) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); obj = null; } @@ -1419,7 +1419,7 @@ private void PoolCreateRequest(object state) { // called by pooler to ensure pool requests are currently being satisfied - // creation mutex has not been obtained - long scopeID = SqlClientEventSource.Log.PoolerScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryPoolerScopeEnterEvent(" {0}", ObjectID); try { if (State.Running == _state) @@ -1503,7 +1503,7 @@ private void PoolCreateRequest(object state) } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, PoolCreateRequest called WaitForSingleObject failed {1}", ObjectID, waitResult); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, PoolCreateRequest called WaitForSingleObject failed {1}", ObjectID, waitResult); } } catch (Exception e) @@ -1516,7 +1516,7 @@ private void PoolCreateRequest(object state) // Now that CreateObject can throw, we need to catch the exception and discard it. // There is no further action we can take beyond tracing. The error will be // thrown to the user the next time they request a connection. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, PoolCreateRequest called CreateConnection which threw an exception: {1}", ObjectID, e); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, PoolCreateRequest called CreateConnection which threw an exception: {1}", ObjectID, e); } finally { @@ -1532,7 +1532,7 @@ private void PoolCreateRequest(object state) } finally { - SqlClientEventSource.Log.PoolerScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryPoolerScopeLeaveEvent(scopeID); } } @@ -1540,7 +1540,7 @@ internal void PutNewObject(DbConnectionInternal obj) { Debug.Assert(null != obj, "why are we adding a null object to the pool?"); // Debug.Assert(obj.CanBePooled, "non-poolable object in pool"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Pushing to general pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Pushing to general pool.", ObjectID, obj.ObjectID); _stackNew.Push(obj); _waitHandles.PoolSemaphore.Release(1); @@ -1584,7 +1584,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. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Transaction has ended.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Transaction has ended.", ObjectID, obj.ObjectID); if (_state == State.Running && obj.CanBePooled) { @@ -1609,7 +1609,7 @@ private void QueuePoolCreateRequest() private bool ReclaimEmancipatedObjects() { bool emancipatedObjectFound = false; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}", ObjectID); List reclaimedObjects = new List(); int count; @@ -1661,7 +1661,7 @@ private bool ReclaimEmancipatedObjects() for (int i = 0; i < count; ++i) { DbConnectionInternal obj = reclaimedObjects[i]; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Reclaiming.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Reclaiming.", ObjectID, obj.ObjectID); emancipatedObjectFound = true; obj.DetachCurrentTransactionIfEnded(); @@ -1672,7 +1672,7 @@ private bool ReclaimEmancipatedObjects() internal void Startup() { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, CleanupWait={1}", ObjectID, _cleanupWait); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, CleanupWait={1}", ObjectID, _cleanupWait); _cleanupTimer = CreateCleanupTimer(); if (NeedToReplenish) { @@ -1682,7 +1682,7 @@ internal void Startup() internal void Shutdown() { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}", ObjectID); _state = State.ShuttingDown; // deactivate timer callbacks @@ -1704,7 +1704,7 @@ internal void TransactionEnded(Transaction transaction, DbConnectionInternal tra Debug.Assert(null != transactedObject, "null transactedObject?"); // 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); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Common.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Common.cs index 834fa09628..f072900b6e 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Common.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Common.cs @@ -38,7 +38,7 @@ private static LocalDBFormatMessageDelegate LocalDBFormatMessage { // SNI checks for LocalDBFormatMessage during DLL loading, so it is practically impossible to get this error. int hResult = Marshal.GetLastWin32Error(); - SqlClientEventSource.Log.TraceEvent(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); + SqlClientEventSource.Log.TryTraceEvent(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); throw CreateLocalDBException(errorMessage: Strings.LocalDB_MethodNotFound); } s_localDBFormatMessage = Marshal.GetDelegateForFunctionPointer(functionAddr); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs index d4b3a73133..6334e5873d 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs @@ -24,7 +24,7 @@ private static IntPtr UserInstanceDLLHandle SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle); if(s_userInstanceDLLHandle != IntPtr.Zero) { - SqlClientEventSource.Log.TraceEvent(" LocalDB - handle obtained"); + SqlClientEventSource.Log.TryTraceEvent(" LocalDB - handle obtained"); } else { diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Windows.cs index bd3ce43eb2..e77b93f5f0 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Windows.cs @@ -64,26 +64,26 @@ internal static uint MapLocalDBErrorStateToCode(LocalDBErrorState errorState) switch (errorState) { case LocalDBErrorState.NO_INSTALLATION: - SqlClientEventSource.Log.SNITraceEvent(" LocalDB is not installed. Error State ={0}", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" LocalDB is not installed. Error State ={0}", errorState); return SNICommon.LocalDBNoInstallation; case LocalDBErrorState.INVALID_CONFIG: - SqlClientEventSource.Log.SNITraceEvent(" Invalid configuration. Error State ={0}", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" Invalid configuration. Error State ={0}", errorState); return SNICommon.LocalDBInvalidConfig; case LocalDBErrorState.NO_SQLUSERINSTANCEDLL_PATH: - SqlClientEventSource.Log.SNITraceEvent(" No SQL user instance path. Error State ={0}", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" No SQL user instance path. Error State ={0}", errorState); return SNICommon.LocalDBNoSqlUserInstanceDllPath; case LocalDBErrorState.INVALID_SQLUSERINSTANCEDLL_PATH: - SqlClientEventSource.Log.SNITraceEvent(" Invalid SQL user instance path. Error State ={0}", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" Invalid SQL user instance path. Error State ={0}", errorState); return SNICommon.LocalDBInvalidSqlUserInstanceDllPath; case LocalDBErrorState.NONE: return 0; default: - SqlClientEventSource.Log.SNITraceEvent(" Invalid configuration. Error State ={0}", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" Invalid configuration. Error State ={0}", errorState); return SNICommon.LocalDBInvalidConfig; } } @@ -93,7 +93,7 @@ internal static uint MapLocalDBErrorStateToCode(LocalDBErrorState errorState) /// private bool LoadUserInstanceDll() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { // Check in a non thread-safe way if the handle is already set for performance. @@ -118,7 +118,7 @@ private bool LoadUserInstanceDll() if (dllPath == null) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, MapLocalDBErrorStateToCode(registryQueryErrorState), string.Empty); - SqlClientEventSource.Log.SNITraceEvent("User instance DLL path is null."); + SqlClientEventSource.Log.TrySNITraceEvent("User instance DLL path is null."); return false; } @@ -126,7 +126,7 @@ private bool LoadUserInstanceDll() if (string.IsNullOrWhiteSpace(dllPath)) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBInvalidSqlUserInstanceDllPath, string.Empty); - SqlClientEventSource.Log.SNITraceEvent(" User instance DLL path is invalid. DLL path ={0}", dllPath); + SqlClientEventSource.Log.TrySNITraceEvent(" User instance DLL path is invalid. DLL path ={0}", dllPath); return false; } @@ -136,7 +136,7 @@ private bool LoadUserInstanceDll() if (libraryHandle.IsInvalid) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBFailedToLoadDll, string.Empty); - SqlClientEventSource.Log.SNITraceEvent(" Library Handle is invalid. Could not load the dll."); + SqlClientEventSource.Log.TrySNITraceEvent(" Library Handle is invalid. Could not load the dll."); libraryHandle.Dispose(); return false; } @@ -147,7 +147,7 @@ private bool LoadUserInstanceDll() if (_startInstanceHandle == IntPtr.Zero) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBBadRuntime, string.Empty); - SqlClientEventSource.Log.SNITraceEvent(" Was not able to load the PROC from DLL. Bad Runtime."); + SqlClientEventSource.Log.TrySNITraceEvent(" Was not able to load the PROC from DLL. Bad Runtime."); libraryHandle.Dispose(); return false; } @@ -164,13 +164,13 @@ private bool LoadUserInstanceDll() } _sqlUserInstanceLibraryHandle = libraryHandle; - SqlClientEventSource.Log.SNITraceEvent(" User Instance DLL was loaded successfully."); + SqlClientEventSource.Log.TrySNITraceEvent(" User Instance DLL was loaded successfully."); return true; } } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -181,7 +181,7 @@ private bool LoadUserInstanceDll() /// private string GetUserInstanceDllPath(out LocalDBErrorState errorState) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(" GetUserInstanceDllPath"); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(" GetUserInstanceDllPath"); try { string dllPath = null; @@ -190,7 +190,7 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) if (key == null) { errorState = LocalDBErrorState.NO_INSTALLATION; - SqlClientEventSource.Log.SNITraceEvent(" not installed. Error state ={0}.", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" not installed. Error state ={0}.", errorState); return null; } @@ -205,7 +205,7 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) if (!Version.TryParse(subKey, out currentKeyVersion)) { errorState = LocalDBErrorState.INVALID_CONFIG; - SqlClientEventSource.Log.SNITraceEvent(" Invalid Configuration. state ={0}.", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" Invalid Configuration. state ={0}.", errorState); return null; } @@ -219,7 +219,7 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) if (latestVersion.Equals(zeroVersion)) { errorState = LocalDBErrorState.INVALID_CONFIG; - SqlClientEventSource.Log.SNITraceEvent(" Invalid Configuration. state ={0}.", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" Invalid Configuration. state ={0}.", errorState); return null; } @@ -232,7 +232,7 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) if (instanceAPIPathRegistryObject == null) { errorState = LocalDBErrorState.NO_SQLUSERINSTANCEDLL_PATH; - SqlClientEventSource.Log.SNITraceEvent(" No SQL user instance DLL. Instance API Path Registry Object Error. state ={0}.", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" No SQL user instance DLL. Instance API Path Registry Object Error. state ={0}.", errorState); return null; } @@ -241,7 +241,7 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) if (valueKind != RegistryValueKind.String) { errorState = LocalDBErrorState.INVALID_SQLUSERINSTANCEDLL_PATH; - SqlClientEventSource.Log.SNITraceEvent(" No SQL user instance DLL. state ={0}. Registry value kind error.", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" No SQL user instance DLL. state ={0}. Registry value kind error.", errorState); return null; } @@ -254,7 +254,7 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs index 94ed2bece1..475660aa2b 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs @@ -136,18 +136,18 @@ internal class SNICommon /// True if certificate is valid internal static bool ValidateSslServerCertificate(string targetServerName, object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { if (policyErrors == SslPolicyErrors.None) { - SqlClientEventSource.Log.SNITraceEvent(" SSL Server certificate validated."); + SqlClientEventSource.Log.TrySNITraceEvent(" SSL Server certificate validated."); return true; } if ((policyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) { - SqlClientEventSource.Log.SNITraceEvent(" SSL Remote certificate name mismatched."); + SqlClientEventSource.Log.TrySNITraceEvent(" SSL Remote certificate name mismatched."); string certServerName = cert.Subject.Substring(cert.Subject.IndexOf('=') + 1); // Verify that target server name matches subject in the certificate @@ -189,7 +189,7 @@ internal static bool ValidateSslServerCertificate(string targetServerName, objec } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -203,7 +203,7 @@ internal static bool ValidateSslServerCertificate(string targetServerName, objec /// internal static uint ReportSNIError(SNIProviders provider, uint nativeError, uint sniError, string errorMessage) { - SqlClientEventSource.Log.SNITraceEvent(" Provider ={0}, native Error ={1}, SNI Error ={2}, Error Message ={3}", provider, nativeError, sniError, errorMessage); + SqlClientEventSource.Log.TrySNITraceEvent(" Provider ={0}, native Error ={1}, SNI Error ={2}, Error Message ={3}", provider, nativeError, sniError, errorMessage); return ReportSNIError(new SNIError(provider, nativeError, sniError, errorMessage)); } @@ -216,7 +216,7 @@ internal static uint ReportSNIError(SNIProviders provider, uint nativeError, uin /// internal static uint ReportSNIError(SNIProviders provider, uint sniError, Exception sniException) { - SqlClientEventSource.Log.SNITraceEvent(" Provider ={0}, SNI Error ={1}, Exception ={2}", provider, sniError, sniException.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" Provider ={0}, SNI Error ={1}, Exception ={2}", provider, sniError, sniException.Message); return ReportSNIError(new SNIError(provider, sniError, sniException)); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNILoadHandle.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNILoadHandle.cs index 2488e8a8a6..6e885462e5 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNILoadHandle.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNILoadHandle.cs @@ -30,7 +30,7 @@ public SNIError LastError set { - SqlClientEventSource.Log.SNITraceEvent(" Last Error Value = {0}", value); + SqlClientEventSource.Log.TrySNITraceEvent(" Last Error Value = {0}", value); _lastError.Value = value; } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsConnection.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsConnection.cs index 5877508942..555f368241 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsConnection.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsConnection.cs @@ -64,22 +64,22 @@ public SNIMarsHandle CreateMarsSession(object callbackObject, bool async) /// public uint StartReceive() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(" StartReceive"); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(" StartReceive"); try { SNIPacket packet = null; if (ReceiveAsync(ref packet) == TdsEnums.SNI_SUCCESS_IO_PENDING) { - SqlClientEventSource.Log.SNITraceEvent(" Success IO pending."); + SqlClientEventSource.Log.TrySNITraceEvent(" Success IO pending."); return TdsEnums.SNI_SUCCESS_IO_PENDING; } - SqlClientEventSource.Log.SNITraceEvent(" Connection not useable."); + SqlClientEventSource.Log.TrySNITraceEvent(" Connection not useable."); return SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnNotUsableError, string.Empty); } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -90,7 +90,7 @@ public uint StartReceive() /// SNI error code public uint Send(SNIPacket packet) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(" Send"); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(" Send"); try { lock (this) @@ -100,7 +100,7 @@ public uint Send(SNIPacket packet) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -112,7 +112,7 @@ public uint Send(SNIPacket packet) /// SNI error code public uint SendAsync(SNIPacket packet, SNIAsyncCallback callback) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(" SendAsync"); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(" SendAsync"); try { lock (this) @@ -122,7 +122,7 @@ public uint SendAsync(SNIPacket packet, SNIAsyncCallback callback) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -133,7 +133,7 @@ public uint SendAsync(SNIPacket packet, SNIAsyncCallback callback) /// SNI error code public uint ReceiveAsync(ref SNIPacket packet) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(" SendAsync"); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(" SendAsync"); try { if (packet != null) @@ -149,7 +149,7 @@ public uint ReceiveAsync(ref SNIPacket packet) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -159,7 +159,7 @@ public uint ReceiveAsync(ref SNIPacket packet) /// SNI error status public uint CheckConnection() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (this) @@ -169,7 +169,7 @@ public uint CheckConnection() } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -181,7 +181,7 @@ public void HandleReceiveError(SNIPacket packet) Debug.Assert(Monitor.IsEntered(this), "HandleReceiveError was called without being locked."); if (!Monitor.IsEntered(this)) { - SqlClientEventSource.Log.SNITraceEvent(" HandleReceiveError was called without being locked."); + SqlClientEventSource.Log.TrySNITraceEvent(" HandleReceiveError was called without being locked."); } foreach (SNIMarsHandle handle in _sessions.Values) { @@ -211,7 +211,7 @@ public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) /// SNI error code public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { SNISMUXHeader currentHeader = null; @@ -223,7 +223,7 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) lock (this) { HandleReceiveError(packet); - SqlClientEventSource.Log.SNITraceEvent(" not successful."); + SqlClientEventSource.Log.TrySNITraceEvent(" not successful."); return; } } @@ -249,7 +249,7 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING) { - SqlClientEventSource.Log.SNITraceEvent(" not successful."); + SqlClientEventSource.Log.TrySNITraceEvent(" not successful."); return; } @@ -351,7 +351,7 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -360,14 +360,14 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) /// public uint EnableSsl(uint options) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { return _lowerHandle.EnableSsl(options); } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -376,14 +376,14 @@ public uint EnableSsl(uint options) /// public void DisableSsl() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { _lowerHandle.DisableSsl(); } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -403,14 +403,14 @@ public void ReturnPacket(SNIPacket packet) /// public void KillConnection() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { _lowerHandle.KillConnection(); } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } #endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsHandle.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsHandle.cs index 8c35907a8f..5f339f00a2 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsHandle.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsHandle.cs @@ -54,19 +54,19 @@ internal sealed class SNIMarsHandle : SNIHandle /// public override void Dispose() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { SendControlPacket(SNISMUXFlags.SMUX_FIN); } catch (Exception e) { - SqlClientEventSource.Log.SNITraceEvent(" internal exception error = {0}, Member Name={1}", e.Message, e.GetType().Name); + SqlClientEventSource.Log.TrySNITraceEvent(" internal exception error = {0}, Member Name={1}", e.Message, e.GetType().Name); SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e); } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -93,7 +93,7 @@ public SNIMarsHandle(SNIMarsConnection connection, ushort sessionId, object call /// SMUX header flags private void SendControlPacket(SNISMUXFlags flags) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { SNIPacket packet = RentPacket(headerSize: SNISMUXHeader.HEADER_LENGTH, dataSize: 0); @@ -110,7 +110,7 @@ private void SendControlPacket(SNISMUXFlags flags) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -151,7 +151,7 @@ private SNIPacket SetPacketSMUXHeader(SNIPacket packet) public override uint Send(SNIPacket packet) { Debug.Assert(packet.ReservedHeaderSize == SNISMUXHeader.HEADER_LENGTH, "mars handle attempting to send muxed packet without mux reservation in Send"); - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { while (true) @@ -181,7 +181,7 @@ public override uint Send(SNIPacket packet) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -194,14 +194,14 @@ public override uint Send(SNIPacket packet) private uint InternalSendAsync(SNIPacket packet, SNIAsyncCallback callback) { Debug.Assert(packet.ReservedHeaderSize == SNISMUXHeader.HEADER_LENGTH, "mars handle attempting to send muxed packet without mux reservation in InternalSendAsync"); - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (this) { if (_sequenceNumber >= _sendHighwater) { - SqlClientEventSource.Log.SNITraceEvent(" SNI Queue is full"); + SqlClientEventSource.Log.TrySNITraceEvent(" SNI Queue is full"); return TdsEnums.SNI_QUEUE_FULL; } @@ -212,7 +212,7 @@ private uint InternalSendAsync(SNIPacket packet, SNIAsyncCallback callback) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -222,7 +222,7 @@ private uint InternalSendAsync(SNIPacket packet, SNIAsyncCallback callback) /// SNI error code private uint SendPendingPackets() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); SNIMarsQueuedPacket packet = null; try { @@ -239,7 +239,7 @@ private uint SendPendingPackets() if (result != TdsEnums.SNI_SUCCESS && result != TdsEnums.SNI_SUCCESS_IO_PENDING) { - SqlClientEventSource.Log.SNITraceEvent(" InternalSendAsync result is not SNI_SUCCESS and is not SNI_SUCCESS_IO_PENDING"); + SqlClientEventSource.Log.TrySNITraceEvent(" InternalSendAsync result is not SNI_SUCCESS and is not SNI_SUCCESS_IO_PENDING"); return result; } @@ -260,7 +260,7 @@ private uint SendPendingPackets() } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -272,7 +272,7 @@ private uint SendPendingPackets() /// SNI error code public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = null) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (this) @@ -285,7 +285,7 @@ public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = nul } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -296,7 +296,7 @@ public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = nul /// SNI error code public override uint ReceiveAsync(ref SNIPacket packet) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (_receivedPacketQueue) @@ -332,7 +332,7 @@ public override uint ReceiveAsync(ref SNIPacket packet) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -341,7 +341,7 @@ public override uint ReceiveAsync(ref SNIPacket packet) /// public void HandleReceiveError(SNIPacket packet) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { // SNIMarsHandle should only receive calls to this function from the SNIMarsConnection aggregator class @@ -358,7 +358,7 @@ public void HandleReceiveError(SNIPacket packet) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -369,7 +369,7 @@ public void HandleReceiveError(SNIPacket packet) /// SNI error code public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (this) @@ -382,7 +382,7 @@ public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -392,7 +392,7 @@ public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) /// Send highwater mark public void HandleAck(uint highwater) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (this) @@ -406,7 +406,7 @@ public void HandleAck(uint highwater) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -417,7 +417,7 @@ public void HandleAck(uint highwater) /// SMUX header public void HandleReceiveComplete(SNIPacket packet, SNISMUXHeader header) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (this) @@ -454,7 +454,7 @@ public void HandleReceiveComplete(SNIPacket packet, SNISMUXHeader header) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -486,7 +486,7 @@ private void SendAckIfNecessary() /// SNI error code public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { packet = null; @@ -537,7 +537,7 @@ public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNINpHandle.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNINpHandle.cs index 362d4397d2..692aa9b7fe 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNINpHandle.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNINpHandle.cs @@ -40,8 +40,8 @@ internal sealed class SNINpHandle : SNIPhysicalHandle public SNINpHandle(string serverName, string pipeName, long timerExpire, object callbackObject) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(" Constructor"); - SqlClientEventSource.Log.SNITraceEvent(" Constructor. server name = {0}, pipe name = {1}", serverName, pipeName); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(" Constructor"); + SqlClientEventSource.Log.TrySNITraceEvent(" Constructor. server name = {0}, pipe name = {1}", serverName, pipeName); try { _sendSync = new object(); @@ -73,14 +73,14 @@ public SNINpHandle(string serverName, string pipeName, long timerExpire, object { SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, te); _status = TdsEnums.SNI_ERROR; - SqlClientEventSource.Log.SNITraceEvent(" Timed out. Exception = {0}", te.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" Timed out. Exception = {0}", te.Message); return; } catch (IOException ioe) { SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, ioe); _status = TdsEnums.SNI_ERROR; - SqlClientEventSource.Log.SNITraceEvent(" IOException = {0}", ioe.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" IOException = {0}", ioe.Message); return; } @@ -88,7 +88,7 @@ public SNINpHandle(string serverName, string pipeName, long timerExpire, object { SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.ConnOpenFailedError, string.Empty); _status = TdsEnums.SNI_ERROR; - SqlClientEventSource.Log.SNITraceEvent(" Pipe stream is not connected or cannot write or read to/from it."); + SqlClientEventSource.Log.TrySNITraceEvent(" Pipe stream is not connected or cannot write or read to/from it."); return; } @@ -100,7 +100,7 @@ public SNINpHandle(string serverName, string pipeName, long timerExpire, object } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -137,12 +137,12 @@ public override int ProtocolVersion public override uint CheckConnection() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { if (!_stream.CanWrite || !_stream.CanRead) { - SqlClientEventSource.Log.SNITraceEvent(" cannot write or read to/from the stream"); + SqlClientEventSource.Log.TrySNITraceEvent(" cannot write or read to/from the stream"); return TdsEnums.SNI_ERROR; } else @@ -152,7 +152,7 @@ public override uint CheckConnection() } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -185,7 +185,7 @@ public override void Dispose() public override uint Receive(out SNIPacket packet, int timeout) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { SNIPacket errorPacket; @@ -202,7 +202,7 @@ public override uint Receive(out SNIPacket packet, int timeout) errorPacket = packet; packet = null; var e = new Win32Exception(); - SqlClientEventSource.Log.SNITraceEvent(" packet length is 0."); + SqlClientEventSource.Log.TrySNITraceEvent(" packet length is 0."); return ReportErrorAndReleasePacket(errorPacket, (uint)e.NativeErrorCode, 0, e.Message); } } @@ -210,14 +210,14 @@ public override uint Receive(out SNIPacket packet, int timeout) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.SNITraceEvent(" ObjectDisposedException message = {0}.", ode.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" ObjectDisposedException message = {0}.", ode.Message); return ReportErrorAndReleasePacket(errorPacket, ode); } catch (IOException ioe) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.SNITraceEvent(" IOException message = {0}.", ioe.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" IOException message = {0}.", ioe.Message); return ReportErrorAndReleasePacket(errorPacket, ioe); } return TdsEnums.SNI_SUCCESS; @@ -225,13 +225,13 @@ public override uint Receive(out SNIPacket packet, int timeout) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } public override uint ReceiveAsync(ref SNIPacket packet) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { SNIPacket errorPacket; @@ -246,26 +246,26 @@ public override uint ReceiveAsync(ref SNIPacket packet) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.SNITraceEvent(" ObjectDisposedException message = {0}.", ode.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" ObjectDisposedException message = {0}.", ode.Message); return ReportErrorAndReleasePacket(errorPacket, ode); } catch (IOException ioe) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.SNITraceEvent(" IOException message = {0}.", ioe.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" IOException message = {0}.", ioe.Message); return ReportErrorAndReleasePacket(errorPacket, ioe); } } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } public override uint Send(SNIPacket packet) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { bool releaseLock = false; @@ -297,12 +297,12 @@ public override uint Send(SNIPacket packet) } catch (ObjectDisposedException ode) { - SqlClientEventSource.Log.SNITraceEvent(" ObjectDisposedException message = {0}.", ode.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" ObjectDisposedException message = {0}.", ode.Message); return ReportErrorAndReleasePacket(packet, ode); } catch (IOException ioe) { - SqlClientEventSource.Log.SNITraceEvent(" IOException message = {0}.", ioe.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" IOException message = {0}.", ioe.Message); return ReportErrorAndReleasePacket(packet, ioe); } @@ -318,13 +318,13 @@ public override uint Send(SNIPacket packet) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = null) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { SNIAsyncCallback cb = callback ?? _sendCallback; @@ -333,7 +333,7 @@ public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = nul } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -345,7 +345,7 @@ public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyn public override uint EnableSsl(uint options) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { _validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0; @@ -356,12 +356,12 @@ public override uint EnableSsl(uint options) } catch (AuthenticationException aue) { - SqlClientEventSource.Log.SNITraceEvent(" AuthenticationException message = {0}.", aue.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" AuthenticationException message = {0}.", aue.Message); return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, aue); } catch (InvalidOperationException ioe) { - SqlClientEventSource.Log.SNITraceEvent("InvalidOperationException message = {0}.", ioe.Message); + SqlClientEventSource.Log.TrySNITraceEvent("InvalidOperationException message = {0}.", ioe.Message); return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, ioe); } _stream = _sslStream; @@ -369,7 +369,7 @@ public override uint EnableSsl(uint options) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -393,7 +393,7 @@ public override void DisableSsl() /// true if valid private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { if (!_validateCert) @@ -405,7 +405,7 @@ private bool ValidateServerCertificate(object sender, X509Certificate cert, X509 } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SSRP.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SSRP.cs index f444236b70..e4359e2c42 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SSRP.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SSRP.cs @@ -26,7 +26,7 @@ internal static int GetPortByInstanceName(string browserHostName, string instanc { Debug.Assert(!string.IsNullOrWhiteSpace(browserHostName), "browserHostName should not be null, empty, or whitespace"); Debug.Assert(!string.IsNullOrWhiteSpace(instanceName), "instanceName should not be null, empty, or whitespace"); - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { byte[] instanceInfoRequest = CreateInstanceInfoRequest(instanceName); @@ -37,7 +37,7 @@ internal static int GetPortByInstanceName(string browserHostName, string instanc } catch (SocketException se) { - SqlClientEventSource.Log.SNITraceEvent(" SocketException Message = {0}", se.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" SocketException Message = {0}", se.Message); throw new Exception(SQLMessage.SqlServerBrowserNotAccessible(), se); } @@ -61,7 +61,7 @@ internal static int GetPortByInstanceName(string browserHostName, string instanc } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -73,7 +73,7 @@ internal static int GetPortByInstanceName(string browserHostName, string instanc private static byte[] CreateInstanceInfoRequest(string instanceName) { Debug.Assert(!string.IsNullOrWhiteSpace(instanceName), "instanceName should not be null, empty, or whitespace"); - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { const byte ClntUcastInst = 0x04; @@ -88,7 +88,7 @@ private static byte[] CreateInstanceInfoRequest(string instanceName) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.NetCoreApp.cs index 52be62e901..bf7c1632d1 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.NetCoreApp.cs @@ -31,7 +31,7 @@ static SqlAuthenticationProviderManager() catch (ConfigurationErrorsException e) { // Don't throw an error for invalid config files - SqlClientEventSource.Log.TraceEvent("Unable to load custom SqlAuthenticationProviders or SqlClientAuthenticationProviders. ConfigurationManager failed to load due to configuration errors: {0}", e); + SqlClientEventSource.Log.TryTraceEvent("Unable to load custom SqlAuthenticationProviders or SqlClientAuthenticationProviders. ConfigurationManager failed to load due to configuration errors: {0}", e); } Instance = new SqlAuthenticationProviderManager(configurationSection); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index 75b5fb04a3..8b8f689d0c 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs @@ -553,8 +553,8 @@ private string CreateInitialQuery() private Task CreateAndExecuteInitialQueryAsync(out BulkCopySimpleResultSet result) { string TDSCommand = CreateInitialQuery(); - SqlClientEventSource.Log.TraceEvent(" Initial Query: '{0}'", TDSCommand); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryTraceEvent(" Initial Query: '{0}'", TDSCommand); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); if (executeTask == null) @@ -852,7 +852,7 @@ private string TryGetOrderHintText(HashSet destColumnNames) private Task SubmitUpdateBulkCommand(string TDSCommand) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); if (executeTask == null) @@ -2359,7 +2359,7 @@ private void CheckAndRaiseNotification() // It's also the user's chance to cause an exception. _stateObj.BcpLock = true; abortOperation = FireRowsCopiedEvent(_rowsCopied); - SqlClientEventSource.Log.TraceEvent("", "INFO"); + SqlClientEventSource.Log.TryTraceEvent(""); // In case the target connection is closed accidentally. if (ConnectionState.Open != _connection.State) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs deleted file mode 100644 index 880cd3a670..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ /dev/null @@ -1,949 +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.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(); - - #region Event IDs - // Initialized static Scope IDs - private static long s_nextScopeId = 0; - private static long s_nextNotificationScopeId = 0; - private static long s_nextPoolerScopeId = 0; - private static long s_nextSNIScopeId = 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; - - /// - /// Defines EventId for Trace() events - /// - private const int TraceEventId = 3; - - /// - /// Defines EventId for ScopeEnter() events - /// - private const int ScopeEnterId = 4; - - /// - /// Defines EventId for ScopeLeave() events - /// - private const int ScopeExitId = 5; - - /// - /// Defines EventId for notificationScopeEnter() events - /// - private const int NotificationScopeEnterId = 6; - - /// - /// Defines EventId for notificationScopeLeave() events - /// - private const int NotificationScopeExitId = 7; - - /// - /// Defines EventId for notificationScopeTrace() events - /// - private const int NotificationTraceId = 8; - - /// - /// Defines EventId for PoolerScopeEnter() events - /// - private const int PoolerScopeEnterId = 9; - - /// - /// Defines EventId for PoolerScopeLeave() events - /// - private const int PoolerScopeExitId = 10; - - /// - /// Defines EventId for PoolerTrace() events - /// - private const int PoolerTraceId = 11; - - /// - /// Defines EventId for AdvancedTrace() events - /// - private const int AdvancedTraceId = 12; - - /// - /// Defines EventId for AdvancedScopeEnter() events - /// - private const int AdvancedScopeEnterId = 13; - - /// - /// Defines EventId for AdvancedScopeLeave() events - /// - private const int AdvancedScopeExitId = 14; - - /// - /// Defines EventId for AdvancedTraceBin() events - /// - private const int AdvancedTraceBinId = 15; - - /// - /// Defines EventId for AdvancedTraceError() events - /// - private const int AdvancedTraceErrorId = 16; - - /// - /// Defines EventId for CorrelationTrace() events - /// - private const int CorrelationTraceId = 17; - - /// - /// Defines EventId for StateDump() events - /// - private const int StateDumpEventId = 18; - - /// - /// Defines EventId for SNITrace() events - /// - private const int SNITraceEventId = 19; - - /// - /// Defines EventId for SNIEnterScope() events - /// - private const int SNIScopeEnterId = 20; - - /// - /// Defines EventId for SNIExitScope() events - /// - private const int SNIScopeExitId = 21; - #endregion - - /// - /// 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 - { - /// - /// Captures Start/Stop events before and after command execution. - /// - internal const EventKeywords ExecutionTrace = (EventKeywords)1; - - /// - /// Captures basic application flow trace events. - /// - internal const EventKeywords Trace = (EventKeywords)2; - - /// - /// Captures basic application scope entering and exiting events. - /// - internal const EventKeywords Scope = (EventKeywords)4; - - /// - /// Captures `SqlNotification` flow trace events. - /// - internal const EventKeywords NotificationTrace = (EventKeywords)8; - - /// - /// Captures `SqlNotification` scope entering and exiting events. - /// - internal const EventKeywords NotificationScope = (EventKeywords)16; - - /// - /// Captures connection pooling flow trace events. - /// - internal const EventKeywords PoolerTrace = (EventKeywords)32; - - /// - /// Captures connection pooling scope trace events. - /// - internal const EventKeywords PoolerScope = (EventKeywords)64; - - /// - /// Captures advanced flow trace events. - /// - internal const EventKeywords AdvancedTrace = (EventKeywords)128; - - /// - /// Captures advanced flow trace events with additional information. - /// - internal const EventKeywords AdvancedTraceBin = (EventKeywords)256; - - /// - /// Captures correlation flow trace events. - /// - internal const EventKeywords CorrelationTrace = (EventKeywords)512; - - /// - /// Captures full state dump of `SqlConnection` - /// - internal const EventKeywords StateDump = (EventKeywords)1024; - - /// - /// Captures application flow traces from Managed networking implementation - /// - internal const EventKeywords SNITrace = (EventKeywords)2048; - - /// - /// Captures scope trace events from Managed networking implementation - /// - internal const EventKeywords SNIScope = (EventKeywords)4096; - } - #endregion - - #region Tasks - /// - /// Tasks supported by SqlClient's EventSource implementation - /// - public static class Tasks - { - /// - /// Task that tracks SqlCommand execution. - /// - public const EventTask ExecuteCommand = (EventTask)1; - } - #endregion - - #region Enable/Disable Events - [NonEvent] - internal bool IsExecutionTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.ExecutionTrace); - - [NonEvent] - internal bool IsTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Trace); - - [NonEvent] - internal bool IsScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Scope); - - [NonEvent] - internal bool IsNotificationTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationTrace); - - [NonEvent] - internal bool IsNotificationScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationScope); - - [NonEvent] - internal bool IsPoolerTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerTrace); - - [NonEvent] - internal bool IsPoolerScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerScope); - - [NonEvent] - internal bool IsAdvancedTraceOn() => Log.IsEnabled(EventLevel.Verbose, Keywords.AdvancedTrace); - - [NonEvent] - internal bool IsCorrelationEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.CorrelationTrace); - - [NonEvent] - internal bool IsStateDumpEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.StateDump); - - [NonEvent] - internal bool IsSNITraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.SNITrace); - - [NonEvent] - internal bool IsSNIScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.SNIScope); - #endregion - - #region overloads - //Never use event writer directly as they are not checking for enabled/disabled situations. Always use overloads. - - #region Trace - [NonEvent] - internal void TraceEvent(string message) - { - if (Log.IsTraceEnabled()) - { - Trace(message); - } - } - - [NonEvent] - internal void TraceEvent(string message, T0 args0) - { - if (Log.IsTraceEnabled()) - { - Trace(string.Format(message, args0?.ToString() ?? "Null")); - } - } - - [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1) - { - if (Log.IsTraceEnabled()) - { - Trace(string.Format(message, args0?.ToString() ?? "Null", args1?.ToString() ?? "Null")); - } - } - - [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)); - } - } - #endregion - - #region Scope - [NonEvent] - internal long ScopeEnterEvent(string message) - { - if (Log.IsScopeEnabled()) - { - return ScopeEnter(message); - } - return 0; - } - - [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0) - { - if (Log.IsScopeEnabled()) - { - return ScopeEnter(string.Format(message, args0)); - } - 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 void ScopeLeaveEvent(long scopeId) - { - if (Log.IsScopeEnabled()) - { - ScopeLeave(scopeId); - } - } - #endregion - - #region Notification Trace - [NonEvent] - internal void NotificationTraceEvent(string message) - { - if (Log.IsNotificationTraceEnabled()) - { - NotificationTrace(message); - } - } - - [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0) - { - if (Log.IsNotificationTraceEnabled()) - { - NotificationTrace(string.Format(message, args0)); - } - } - - [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0, T1 args1) - { - if (Log.IsNotificationTraceEnabled()) - { - NotificationTrace(string.Format(message, args0, args1)); - } - } - - [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsNotificationTraceEnabled()) - { - NotificationTrace(string.Format(message, args0, args1, args2)); - } - } - - [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsNotificationTraceEnabled()) - { - NotificationTrace(string.Format(message, args0, args1, args2, args3)); - } - } - #endregion - - #region Notification Scope - [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0) - { - if (Log.IsNotificationScopeEnabled()) - { - return NotificationScopeEnter(string.Format(message, args0)); - } - return 0; - } - - [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0, T1 args1) - { - if (Log.IsNotificationScopeEnabled()) - { - return NotificationScopeEnter(string.Format(message, args0, args1)); - } - return 0; - } - - [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsNotificationScopeEnabled()) - { - return NotificationScopeEnter(string.Format(message, args0, args1, args2)); - } - return 0; - } - - [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsNotificationScopeEnabled()) - { - return NotificationScopeEnter(string.Format(message, args0, args1, args2, args3)); - } - return 0; - } - - [NonEvent] - internal void NotificationScopeLeaveEvent(long scopeId) - { - if (Log.IsNotificationScopeEnabled()) - { - NotificationScopeLeave(scopeId); - } - } - #endregion - - #region Pooler Trace - [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)); - } - } - #endregion - - #region Pooler Scope - [NonEvent] - internal long PoolerScopeEnterEvent(string message, T0 args0) - { - if (Log.IsPoolerScopeEnabled()) - { - return PoolerScopeEnter(string.Format(message, args0)); - } - return 0; - } - - [NonEvent] - internal void PoolerScopeLeaveEvent(long scopeId) - { - if (Log.IsPoolerScopeEnabled()) - { - PoolerScopeLeave(scopeId); - } - } - #endregion - - #region AdvancedTrace - [NonEvent] - internal void AdvancedTraceEvent(string message) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(message); - } - } - - [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(string.Format(message, args0)); - } - } - - [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(string.Format(message, args0, args1)); - } - } - - [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(string.Format(message, args0, args1, args2)); - } - } - - [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(string.Format(message, args0, args1, args2, args3)); - } - } - - [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(string.Format(message, args0, args1, args2, args3, args4, args5)); - } - } - - [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5, T6 args6, T7 args7) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(string.Format(message, args0, args1, args2, args3, args4, args5, args6, args7)); - } - } - - [NonEvent] - internal long AdvancedScopeEnterEvent(string message, T0 args0) - { - if (Log.IsAdvancedTraceOn()) - { - return AdvancedScopeEnter(string.Format(message, args0)); - } - return 0; - } - - [NonEvent] - internal void AdvanceScopeLeave(long scopeId) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedScopeLeave(scopeId); - } - } - - [NonEvent] - internal void AdvancedTraceBinEvent(string message, T0 args0, T1 args1) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTraceBin(string.Format(message, args0, args1)); - } - } - - [NonEvent] - internal void AdvancedTraceErrorEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTraceError(string.Format(message, args0, args1, args2, args3, args4)); - } - } - #endregion - - #region Correlation Trace - [NonEvent] - internal void CorrelationTraceEvent(string message, T0 args0) - { - if (Log.IsCorrelationEnabled()) - { - CorrelationTrace(string.Format(message, args0?.ToString() ?? "Null")); - } - } - - [NonEvent] - internal void CorrelationTraceEvent(string message, T0 args0, T1 args1) - { - if (Log.IsCorrelationEnabled()) - { - CorrelationTrace(string.Format(message, args0?.ToString() ?? "Null", args1?.ToString() ?? "Null")); - } - } - - [NonEvent] - internal void CorrelationTraceEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsCorrelationEnabled()) - { - CorrelationTrace(string.Format(message, args0?.ToString() ?? "Null", args1?.ToString() ?? "Null", args2?.ToString() ?? "Null")); - } - } - #endregion - - #region State Dump - [NonEvent] - internal void StateDumpEvent(string message, T0 args0, T1 args1) - { - if (Log.IsStateDumpEnabled()) - { - StateDump(string.Format(message, args0, args1)); - } - } - #endregion - - #region SNI Trace - [NonEvent] - internal void SNITraceEvent(string message) - { - if (Log.IsSNITraceEnabled()) - { - SNITrace(string.Format(message)); - } - } - - [NonEvent] - internal void SNITraceEvent(string message, T0 args0) - { - if (Log.IsSNITraceEnabled()) - { - SNITrace(string.Format(message, args0)); - } - } - - [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1) - { - if (Log.IsSNITraceEnabled()) - { - SNITrace(string.Format(message, args0, args1)); - } - } - - [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsSNITraceEnabled()) - { - SNITrace(string.Format(message, args0, args1, args2)); - } - } - - [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsSNITraceEnabled()) - { - SNITrace(string.Format(message, args0, args1, args2, args3)); - } - } - - [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4) - { - if (Log.IsSNITraceEnabled()) - { - SNITrace(string.Format(message, args0, args1, args2, args3, args4)); - } - } - #endregion - - #region SNI Scope - [NonEvent] - internal long SNIScopeEnterEvent(string message) - { - if (Log.IsSNIScopeEnabled()) - { - return SNIScopeEnter(message); - } - return 0; - } - - [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0) - { - if (Log.IsSNIScopeEnabled()) - { - return SNIScopeEnter(string.Format(message, args0)); - } - return 0; - } - - [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0, T1 args1) - { - if (Log.IsSNIScopeEnabled()) - { - return SNIScopeEnter(string.Format(message, args0, args1)); - } - return 0; - } - - [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsSNIScopeEnabled()) - { - return SNIScopeEnter(string.Format(message, args0, args1, args2)); - } - return 0; - } - - [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsSNIScopeEnabled()) - { - return SNIScopeEnter(string.Format(message, args0, args1, args2, args3)); - } - return 0; - } - - [NonEvent] - internal void SNIScopeLeaveEvent(long scopeId) - { - if (Log.IsSNIScopeEnabled()) - { - SNIScopeLeave(scopeId); - } - } - #endregion - - #endregion - - #region Write Events - [Event(BeginExecuteEventId, Keywords = Keywords.ExecutionTrace, Task = Tasks.ExecuteCommand, Opcode = EventOpcode.Start)] - internal void BeginExecute(int objectId, string dataSource, string database, string commandText) - { - if (Log.IsExecutionTraceEnabled()) - { - WriteEvent(BeginExecuteEventId, objectId, dataSource, database, commandText); - } - } - - [Event(EndExecuteEventId, Keywords = Keywords.ExecutionTrace, Task = Tasks.ExecuteCommand, Opcode = EventOpcode.Stop)] - internal void EndExecute(int objectId, int compositeState, int sqlExceptionNumber) - { - if (Log.IsExecutionTraceEnabled()) - { - WriteEvent(EndExecuteEventId, objectId, compositeState, sqlExceptionNumber); - } - } - - [Event(TraceEventId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] - internal void Trace(string message) - { - WriteEvent(TraceEventId, message); - } - - [Event(ScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.Scope)] - internal long ScopeEnter(string message) - { - long scopeId = Interlocked.Increment(ref s_nextScopeId); - WriteEvent(ScopeEnterId, message); - return scopeId; - } - - [Event(ScopeExitId, Level = EventLevel.Informational, Opcode = EventOpcode.Stop, Keywords = Keywords.Scope)] - internal void ScopeLeave(long scopeId) - { - WriteEvent(ScopeExitId, scopeId); - } - - [Event(NotificationTraceId, Level = EventLevel.Informational, Keywords = Keywords.NotificationTrace)] - internal void NotificationTrace(string message) - { - WriteEvent(NotificationTraceId, message); - } - - [Event(NotificationScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.NotificationScope)] - internal long NotificationScopeEnter(string message) - { - long scopeId = Interlocked.Increment(ref s_nextNotificationScopeId); - WriteEvent(NotificationScopeEnterId, message); - return scopeId; - } - - [Event(NotificationScopeExitId, Level = EventLevel.Informational, Opcode = EventOpcode.Stop, Keywords = Keywords.NotificationScope)] - internal void NotificationScopeLeave(long scopeId) - { - WriteEvent(NotificationScopeExitId, scopeId); - } - - [Event(PoolerTraceId, Level = EventLevel.Informational, Keywords = Keywords.PoolerTrace)] - internal void PoolerTrace(string message) - { - WriteEvent(PoolerTraceId, message); - } - - [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(PoolerScopeExitId, Level = EventLevel.Informational, Opcode = EventOpcode.Stop, Keywords = Keywords.PoolerScope)] - internal void PoolerScopeLeave(long scopeId) - { - WriteEvent(PoolerScopeExitId, scopeId); - } - - [Event(AdvancedTraceId, Level = EventLevel.Verbose, Keywords = Keywords.AdvancedTrace)] - internal void AdvancedTrace(string message) - { - WriteEvent(AdvancedTraceId, message); - } - - [Event(AdvancedScopeEnterId, Level = EventLevel.Verbose, Opcode = EventOpcode.Start, Keywords = Keywords.AdvancedTrace)] - internal long AdvancedScopeEnter(string message) - { - long scopeId = Interlocked.Increment(ref s_nextScopeId); - WriteEvent(AdvancedScopeEnterId, message); - return scopeId; - } - - [Event(AdvancedScopeExitId, Level = EventLevel.Verbose, Opcode = EventOpcode.Stop, Keywords = Keywords.AdvancedTrace)] - internal void AdvancedScopeLeave(long scopeId) - { - WriteEvent(AdvancedScopeExitId, scopeId); - } - - [Event(AdvancedTraceBinId, Level = EventLevel.Verbose, Keywords = Keywords.AdvancedTraceBin)] - internal void AdvancedTraceBin(string message) - { - WriteEvent(AdvancedTraceBinId, message); - } - - [Event(AdvancedTraceErrorId, Level = EventLevel.Error, Keywords = Keywords.AdvancedTrace)] - internal void AdvancedTraceError(string message) - { - WriteEvent(AdvancedTraceErrorId, message); - } - - [Event(CorrelationTraceId, Level = EventLevel.Informational, Keywords = Keywords.CorrelationTrace, Opcode = EventOpcode.Start)] - internal void CorrelationTrace(string message) - { - WriteEvent(CorrelationTraceId, message); - } - - [Event(StateDumpEventId, Level = EventLevel.Verbose, Keywords = Keywords.StateDump)] - internal void StateDump(string message) - { - WriteEvent(StateDumpEventId, message); - } - - [Event(SNITraceEventId, Level = EventLevel.Informational, Keywords = Keywords.SNITrace)] - internal void SNITrace(string message) - { - WriteEvent(SNITraceEventId, message); - } - - [Event(SNIScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.SNIScope)] - internal long SNIScopeEnter(string message) - { - long scopeId = Interlocked.Increment(ref s_nextSNIScopeId); - WriteEvent(SNIScopeEnterId, message); - return scopeId; - } - - [Event(SNIScopeExitId, Level = EventLevel.Informational, Opcode = EventOpcode.Stop, Keywords = Keywords.SNIScope)] - internal void SNIScopeLeave(long scopeId) - { - WriteEvent(SNIScopeExitId, scopeId); - } - #endregion - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs index aeedc3a346..526459baca 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -448,9 +448,8 @@ private SqlCommand(SqlCommand from) : this() } } } - _activeConnection = value; - SqlClientEventSource.Log.TraceEvent(" {0}, {1}", ObjectID, (null != value) ? value.ObjectID : -1); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value?.ObjectID); } } @@ -484,7 +483,7 @@ public SqlNotificationRequest Notification } set { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); _sqlDep = null; _notification = value; } @@ -528,7 +527,7 @@ internal SqlStatistics Statistics throw SQL.CannotModifyPropertyAsyncOperationInProgress(); } } - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); _transaction = value; } } @@ -556,7 +555,7 @@ override public string CommandText } set { - SqlClientEventSource.Log.TraceEvent(" {0}, String Value = '{1}'", ObjectID, value); + SqlClientEventSource.Log.TryTraceEvent(" {0}, String Value = '{1}'", ObjectID, value); if (_commandText != value) { PropertyChanging(); @@ -577,7 +576,7 @@ override public int CommandTimeout } set { - SqlClientEventSource.Log.TraceEvent(" {0}, {1}", ObjectID, value); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value); if (value < 0) { throw ADP.InvalidCommandTimeout(value); @@ -610,7 +609,7 @@ override public CommandType CommandType } set { - SqlClientEventSource.Log.TraceEvent(" {0}, {1}{2}", ObjectID, (int)value, _commandType); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}{2}", ObjectID, (int)value, _commandType); if (_commandType != value) { switch (value) @@ -715,7 +714,7 @@ internal void OnStatementCompleted(int recordCount) { try { - SqlClientEventSource.Log.TraceEvent(" {0}, recordCount={1}", ObjectID, recordCount); + SqlClientEventSource.Log.TryTraceEvent(" {0}, recordCount={1}", ObjectID, recordCount); handler(this, new StatementCompletedEventArgs(recordCount)); } catch (Exception e) @@ -742,8 +741,8 @@ override public void Prepare() _pendingCancel = false; SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -807,7 +806,7 @@ override public void Prepare() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -857,7 +856,7 @@ internal void Unprepare() } _cachedMetaData = null; - SqlClientEventSource.Log.TraceEvent(" {0}, Command unprepared.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command unprepared.", ObjectID); } // Cancel is supposed to be multi-thread safe. @@ -867,8 +866,8 @@ internal void Unprepare() /// override public void Cancel() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); SqlStatistics statistics = null; try { @@ -945,7 +944,7 @@ override public void Cancel() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -983,8 +982,8 @@ override public object ExecuteScalar() SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Exception e = null; bool success = false; @@ -1013,7 +1012,7 @@ override public object ExecuteScalar() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); if (e != null) { @@ -1067,8 +1066,8 @@ override public int ExecuteNonQuery() SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Exception e = null; try { @@ -1084,7 +1083,7 @@ override public int ExecuteNonQuery() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); if (e != null) { _diagnosticListener.WriteCommandError(operationId, this, _transaction, e); @@ -1106,7 +1105,7 @@ public IAsyncResult BeginExecuteNonQuery() /// public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); return BeginExecuteNonQueryInternal(0, callback, stateObject, 0, inRetry: false); } @@ -1303,7 +1302,7 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); } } @@ -1322,7 +1321,7 @@ private void ThrowIfReconnectionHasBeenCanceled() /// public int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -1522,7 +1521,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, bo { // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as RPC.", ObjectID); SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, completion, timeout, out task, out usedCache, asyncWrite, inRetry, methodName); if (null != reader) @@ -1556,8 +1555,8 @@ public XmlReader ExecuteXmlReader() Guid operationId = _diagnosticListener.WriteCommandBefore(this, _transaction); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); int? sqlExceptionNumber = null; Exception e = null; @@ -1585,7 +1584,7 @@ public XmlReader ExecuteXmlReader() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); if (e != null) { @@ -1608,7 +1607,7 @@ public IAsyncResult BeginExecuteXmlReader() /// public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); return BeginExecuteXmlReaderInternal(CommandBehavior.SequentialAccess, callback, stateObject, 0, inRetry: false); } @@ -1731,13 +1730,13 @@ public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); } } private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -1842,14 +1841,14 @@ private XmlReader CompleteXmlReader(SqlDataReader ds, bool isAsync = false) /// public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); return BeginExecuteReaderInternal(behavior, callback, stateObject, 0, inRetry: false); } /// override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); return ExecuteReader(behavior); } @@ -1857,8 +1856,8 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) new public SqlDataReader ExecuteReader() { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1867,7 +1866,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1925,13 +1924,13 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); } } internal SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2202,16 +2201,16 @@ string endMethod } private void CreateLocalCompletionTask( - CommandBehavior behavior, - object stateObject, - int timeout, + CommandBehavior behavior, + object stateObject, + int timeout, bool usedCache, - bool asyncWrite, - TaskCompletionSource globalCompletion, - TaskCompletionSource localCompletion, + bool asyncWrite, + TaskCompletionSource globalCompletion, + TaskCompletionSource localCompletion, Func endFunc, - Func retryFunc, - string endMethod, + Func retryFunc, + string endMethod, long firstAttemptStart ) { @@ -2288,7 +2287,7 @@ long firstAttemptStart if (ShouldUseEnclaveBasedWorkflow && this.enclavePackage != null) { - EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + EnclaveSessionParameters enclaveSessionParameters = new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, enclaveSessionParameters, this.enclavePackage.EnclaveSession); } @@ -2372,7 +2371,7 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, bool is /// public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Guid operationId = _diagnosticListener.WriteCommandBefore(this, _transaction); TaskCompletionSource source = new TaskCompletionSource(); @@ -2459,7 +2458,7 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b /// new public Task ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); Guid operationId = default(Guid); if (!_parentOperationStarted) { @@ -2493,14 +2492,14 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b { context = new ExecuteReaderAsyncCallContext(); } - context.Set(this, source, registration,behavior, operationId); + context.Set(this, source, registration, behavior, operationId); Task.Factory.FromAsync( - beginMethod: s_beginExecuteReaderAsync, + beginMethod: s_beginExecuteReaderAsync, endMethod: s_endExecuteReaderAsync, state: context ).ContinueWith( - continuationAction: s_cleanupExecuteReaderAsync, + continuationAction: s_cleanupExecuteReaderAsync, TaskScheduler.Default ); } @@ -2617,7 +2616,7 @@ public Task ExecuteXmlReaderAsync() /// public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Guid operationId = _diagnosticListener.WriteCommandBefore(this, _transaction); TaskCompletionSource source = new TaskCompletionSource(); @@ -3159,7 +3158,7 @@ private Task RunExecuteNonQueryTds(string methodName, bool isAsync, int timeout, // no parameters are sent over // no data reader is returned // use this overload for "batch SQL" tds token type - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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"); @@ -3613,9 +3612,9 @@ private void PrepareForTransparentEncryption(CommandBehavior cmdBehavior, bool r { SqlConnectionAttestationProtocol attestationProtocol = this._activeConnection.AttestationProtocol; string enclaveType = this._activeConnection.Parser.EnclaveType; - - EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); - + + EnclaveSessionParameters enclaveSessionParameters = new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + SqlEnclaveSession sqlEnclaveSession = null; EnclaveDelegate.Instance.GetEnclaveSession(attestationProtocol, enclaveType, enclaveSessionParameters, true, out sqlEnclaveSession, out customData, out customDataLength); if (sqlEnclaveSession == null) @@ -4141,7 +4140,7 @@ private void ReadDescribeEncryptionParameterResults(SqlDataReader ds, ReadOnlyDi SqlConnectionAttestationProtocol attestationProtocol = this._activeConnection.AttestationProtocol; string enclaveType = this._activeConnection.Parser.EnclaveType; - EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + EnclaveSessionParameters enclaveSessionParameters = new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.CreateEnclaveSession(attestationProtocol, enclaveType, enclaveSessionParameters, attestationInfo, enclaveAttestationParameters, customData, customDataLength); enclaveAttestationParameters = null; @@ -4256,7 +4255,7 @@ internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior if (ShouldUseEnclaveBasedWorkflow && this.enclavePackage != null) { - EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + EnclaveSessionParameters enclaveSessionParameters = new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, enclaveSessionParameters, this.enclavePackage.EnclaveSession); } @@ -4300,7 +4299,7 @@ internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior if (ShouldUseEnclaveBasedWorkflow && this.enclavePackage != null) { - EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + EnclaveSessionParameters enclaveSessionParameters = new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, enclaveSessionParameters, this.enclavePackage.EnclaveSession); } @@ -4407,7 +4406,7 @@ private void GenerateEnclavePackage() try { - EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + EnclaveSessionParameters enclaveSessionParameters = new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); this.enclavePackage = EnclaveDelegate.Instance.GenerateEnclavePackage(attestationProtocol, keysToBeSentToEnclave, this.CommandText, enclaveType, enclaveSessionParameters); } @@ -4511,7 +4510,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi if (returnStream) { - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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 @@ -4572,7 +4571,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi rpc.options = TdsEnums.RPC_NOMETADATA; if (returnStream) { - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as RPC.", ObjectID); } Debug.Assert(_rpcArrayOf1[0] == rpc); @@ -4590,7 +4589,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi optionSettings = GetSetOptionsString(cmdBehavior); if (returnStream) { - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as RPC.", ObjectID); } // turn set options ON @@ -6255,7 +6254,7 @@ private void NotifyDependency() public SqlCommand Clone() { SqlCommand clone = new SqlCommand(this); - SqlClientEventSource.Log.TraceEvent(" {0}, clone={1}", ObjectID, clone.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, clone={1}", ObjectID, clone.ObjectID); return clone; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index 18c1938401..39916feaae 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -116,7 +116,7 @@ internal int ObjectID internal void Append(SqlCommand command) { ADP.CheckArgumentNull(command, nameof(command)); - SqlClientEventSource.Log.TraceEvent(" {0}, command={1}, parameterCount={2}", ObjectID, command.ObjectID, command.Parameters.Count); + SqlClientEventSource.Log.TryTraceEvent(" {0}, command={1}, parameterCount={2}", ObjectID, command.ObjectID, command.Parameters.Count); string cmdText = command.CommandText; if (string.IsNullOrEmpty(cmdText)) { @@ -248,7 +248,7 @@ internal static void BuildStoredProcedureName(StringBuilder builder, string part internal void Clear() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); DbCommand batchCommand = BatchCommand; if (null != batchCommand) { @@ -264,7 +264,7 @@ internal void Clear() internal void Dispose() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); SqlCommand command = _batchCommand; _commandList = null; _batchCommand = null; @@ -278,7 +278,7 @@ internal void Dispose() internal int ExecuteNonQuery() { ValidateCommandBehavior(nameof(ExecuteNonQuery), CommandBehavior.Default); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { @@ -295,7 +295,7 @@ internal int ExecuteNonQuery() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs index b82137f669..c1fa77b989 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -898,7 +898,7 @@ public SqlTransaction BeginTransaction(string transactionName) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, isolationLevel={1}", ObjectID, (int)isolationLevel); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, isolationLevel={1}", ObjectID, (int)isolationLevel); try { DbTransaction transaction = BeginTransaction(isolationLevel); @@ -913,7 +913,7 @@ override protected DbTransaction BeginDbTransaction(System.Data.IsolationLevel i } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -922,7 +922,7 @@ public SqlTransaction BeginTransaction(System.Data.IsolationLevel iso, string tr { WaitForPendingReconnection(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, iso={1}, transactionName='{2}'", ObjectID, (int)iso, (string.IsNullOrEmpty(transactionName) ? "None" : transactionName)); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, iso={1}, transactionName='{2}'", ObjectID, (int)iso, transactionName); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -947,7 +947,7 @@ public SqlTransaction BeginTransaction(System.Data.IsolationLevel iso, string tr finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -956,7 +956,7 @@ public override void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1001,8 +1001,8 @@ private void CloseInnerConnection() /// public override void Close() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { ConnectionState previousState = State; @@ -1080,7 +1080,7 @@ public override void Close() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1121,8 +1121,8 @@ public override void Open() /// public void Open(SqlConnectionOverrides overrides) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this); @@ -1162,7 +1162,7 @@ public void Open(SqlConnectionOverrides overrides) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1196,7 +1196,7 @@ private async Task ReconnectAsync(int timeout) { if (ctoken.IsCancellationRequested) { - SqlClientEventSource.Log.TraceEvent(" Original ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Original ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId); return; } try @@ -1215,15 +1215,15 @@ private async Task ReconnectAsync(int timeout) { ForceNewConnection = false; } - SqlClientEventSource.Log.TraceEvent(" Reconnection succeeded. ClientConnectionID {0} -> {1}", _originalConnectionId.ToString(), ClientConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Reconnection succeeded. ClientConnectionID {0} -> {1}", _originalConnectionId, ClientConnectionId); return; } catch (SqlException e) { - SqlClientEventSource.Log.TraceEvent(" Original ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message); + SqlClientEventSource.Log.TryTraceEvent(" Original ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message); if (attempt == retryCount - 1) { - SqlClientEventSource.Log.TraceEvent(" Original ClientConnectionID {0} - give up reconnection", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Original ClientConnectionID {0} - give up reconnection", _originalConnectionId); throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) @@ -1296,7 +1296,7 @@ internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; - SqlClientEventSource.Log.TraceEvent(" Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId); _recoverySessionData = cData; if (beforeDisconnect != null) { @@ -1389,8 +1389,8 @@ private void CancelOpenAndWait() /// public override Task OpenAsync(CancellationToken cancellationToken) { - long scopeID = SqlClientEventSource.Log.PoolerScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryPoolerScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this); @@ -1410,7 +1410,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlErrorOpenConnection)) { result.Task.ContinueWith( - continuationAction: s_openAsyncComplete, + continuationAction: s_openAsyncComplete, state: operationId, // connection is passed in TaskCompletionSource async state scheduler: TaskScheduler.Default ); @@ -1467,7 +1467,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.PoolerScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryPoolerScopeLeaveEvent(scopeID); } } @@ -1525,7 +1525,7 @@ public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource retryTask) { - SqlClientEventSource.Log.TraceEvent(" {0}", _parent.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", _parent.ObjectID); _registration.Dispose(); try { @@ -1788,7 +1788,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {0}, Connection broken.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection broken.", ObjectID); Close(); } }; @@ -1797,7 +1797,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {0}, Connection broken.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection broken.", ObjectID); Close(); } } @@ -1848,7 +1848,7 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent) internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) { - SqlClientEventSource.Log.TraceEvent(" {0}, Message='{1}'", ObjectID, (null != imevent) ? imevent.Message : ""); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Message='{1}'", ObjectID, imevent.Message); SqlInfoMessageEventHandler handler = InfoMessage; if (null != handler) { @@ -1874,8 +1874,8 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) /// public static void ChangePassword(string connectionString, string newPassword) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); - SqlClientEventSource.Log.CorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(""); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); try { if (string.IsNullOrEmpty(connectionString)) @@ -1907,15 +1907,15 @@ public static void ChangePassword(string connectionString, string newPassword) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } /// public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); - SqlClientEventSource.Log.CorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(""); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); try { if (string.IsNullOrEmpty(connectionString)) @@ -1968,7 +1968,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -2011,7 +2011,7 @@ internal Task RegisterForConnectionCloseNotification(Task outerTask, ob connection.RemoveWeakReference(obj); return task; - }, + }, state: Tuple.Create(this, value), scheduler: TaskScheduler.Default ).Unwrap(); @@ -2094,7 +2094,7 @@ private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) { if (asmRef.Version != TypeSystemAssemblyVersion && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.TraceEvent(" SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version.ToString(), TypeSystemAssemblyVersion.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version, TypeSystemAssemblyVersion); } asmRef.Version = TypeSystemAssemblyVersion; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs index 0f0ce90477..42b9e7a6d1 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs @@ -182,7 +182,7 @@ override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions { connectionTimeout *= 10; } - SqlClientEventSource.Log.TraceEvent("Set connection pool CreateTimeout={0} when {1} is in use.", connectionTimeout, opt.Authentication); + SqlClientEventSource.Log.TryTraceEvent("Set connection pool CreateTimeout={0} when {1} is in use.", connectionTimeout, opt.Authentication); } poolingOptions = new DbConnectionPoolGroupOptions( opt.IntegratedSecurity, diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs index 1a6f944a6c..cf9ab34507 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs @@ -60,7 +60,7 @@ internal DbConnectionOptions ConnectionOptions private string ConnectionString_Get() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions connectionOptions = UserConnectionOptions; return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); @@ -86,8 +86,10 @@ private void ConnectionString_Set(DbConnectionPoolKey key) { throw ADP.OpenConnectionPropertySet(nameof(ConnectionString), connectionInternal.State); } - string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); - SqlClientEventSource.Log.TraceEvent(" {0}, '{1}'", ObjectID, cstr); + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + SqlClientEventSource.Log.TraceEvent(" {0}, '{1}'", ObjectID, connectionOptions?.UsersConnectionStringForTrace()); + } } internal DbConnectionInternal InnerConnection @@ -135,11 +137,11 @@ internal void Abort(Exception e) // will end the reliable try... if (e is OutOfMemoryException) { - SqlClientEventSource.Log.TraceEvent(" {0}, Aborting operation due to asynchronous exception: {'OutOfMemory'}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Aborting operation due to asynchronous exception: {'OutOfMemory'}", ObjectID); } else { - SqlClientEventSource.Log.TraceEvent(" {0}, Aborting operation due to asynchronous exception: {1}", ObjectID, e); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Aborting operation due to asynchronous exception: {1}", ObjectID, e); } } @@ -151,7 +153,7 @@ internal void AddWeakReference(object value, int tag) /// override protected DbCommand CreateDbCommand() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { DbCommand command = null; @@ -162,7 +164,7 @@ override protected DbCommand CreateDbCommand() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -184,7 +186,7 @@ override protected void Dispose(bool disposing) /// public override void EnlistTransaction(Transaction transaction) { - SqlClientEventSource.Log.TraceEvent(" {0}, Connection enlisting in a transaction.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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/netcore/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs index 874c44287f..aeaa3fd36e 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs @@ -53,7 +53,7 @@ internal void AliasCheck(string server) } else if (_alias != server) { - SqlClientEventSource.Log.TraceEvent(" alias change detected. Clearing PoolGroup"); + SqlClientEventSource.Log.TryTraceEvent(" alias change detected. Clearing PoolGroup"); base.PoolGroup.Clear(); _alias = server; } @@ -66,7 +66,7 @@ internal void FailoverCheck(SqlInternalConnection connection, bool actualUseFail { if (UseFailoverPartner != actualUseFailoverPartner) { - SqlClientEventSource.Log.TraceEvent(" Failover detected. failover partner='{0}'. Clearing PoolGroup", actualFailoverPartner); + SqlClientEventSource.Log.TryTraceEvent(" Failover detected. failover partner='{0}'. Clearing PoolGroup", actualFailoverPartner); base.PoolGroup.Clear(); _useFailoverPartner = actualUseFailoverPartner; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index 63c11bc371..3852c375b3 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -127,7 +127,7 @@ public override int UpdateBatchSize throw ADP.ArgumentOutOfRange(nameof(UpdateBatchSize)); } _updateBatchSize = value; - SqlClientEventSource.Log.TraceEvent(" {0}, {1}", ObjectID, value); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value); } } @@ -149,7 +149,7 @@ protected override void ClearBatch() protected override int ExecuteBatch() { Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); return _commandSet.ExecuteNonQuery(); } @@ -172,7 +172,7 @@ protected override bool GetBatchedRecordsAffected(int commandIdentifier, out int /// protected override void InitializeBatching() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); _commandSet = new SqlCommandSet(); SqlCommand command = SelectCommand; if (null == command) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs index dd7d898f85..83fa69a74f 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -844,7 +844,7 @@ protected override void Dispose(bool disposing) /// public override void Close() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); SqlStatistics statistics = null; try { @@ -927,7 +927,7 @@ public override void Close() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1442,7 +1442,7 @@ override public int GetProviderSpecificValues(object[] values) public override DataTable GetSchemaTable() { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1459,7 +1459,7 @@ public override DataTable GetSchemaTable() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -3243,7 +3243,7 @@ override public bool NextResult() private bool TryNextResult(out bool more) { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -3374,7 +3374,7 @@ private bool TryNextResult(out bool more) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -3404,7 +3404,7 @@ override public bool Read() private bool TryReadInternal(bool setTimeout, out bool more) { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -3557,7 +3557,7 @@ private bool TryReadInternal(bool setTimeout, out bool more) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -3935,7 +3935,7 @@ private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateO // broken connection, so check state first. if (parser.State == TdsParserState.OpenLoggedIn) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID '{1}'", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID '{1}'", ObjectID, ActivityCorrelator.Current); 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"); @@ -4240,7 +4240,7 @@ private void AssertReaderState(bool requireData, bool permitAsync, int? columnIn /// public override Task NextResultAsync(CancellationToken cancellationToken) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { TaskCompletionSource source = new TaskCompletionSource(); @@ -4281,7 +4281,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -4290,7 +4290,7 @@ private static Task NextResultAsyncExecute(Task task, object state) HasNextResultAsyncCallContext context = (HasNextResultAsyncCallContext)state; if (task != null) { - SqlClientEventSource.Log.TraceEvent(" attempt retry {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" attempt retry {0}", ObjectID); context._reader.PrepareForAsyncContinuation(); } @@ -4575,7 +4575,7 @@ out bytesRead /// public override Task ReadAsync(CancellationToken cancellationToken) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { if (IsClosed) @@ -4709,7 +4709,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs index 214076d7b0..d806dc814a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs @@ -80,13 +80,13 @@ public void Initialize() // transaction. SqlInternalConnection connection = _connection; SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, delegating transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, delegating transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try { if (connection.IsEnlistedInTransaction) { - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, was enlisted, now defecting.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, was enlisted, now defecting.", ObjectID, connection.ObjectID); // defect first connection.EnlistNull(); @@ -143,7 +143,7 @@ public byte[] Promote() if (null != connection) { SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, promoting transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, promoting transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try { @@ -215,13 +215,13 @@ public byte[] Promote() else { // The transaction was aborted externally, since it's already doomed above, we only log the same. - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, aborted during promotion.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, aborted during promotion.", ObjectID, connection.ObjectID); } } else { // The transaction was aborted externally, doom the connection to make sure it's eventually rolled back and log the same. - SqlClientEventSource.Log.TraceEvent(" {0}, Connection null, aborted before promoting.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection null, aborted before promoting.", ObjectID); } return returnValue; } @@ -235,7 +235,7 @@ public void Rollback(SinglePhaseEnlistment enlistment) if (null != connection) { SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, rolling back transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, rolling back transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try { @@ -304,7 +304,7 @@ public void Rollback(SinglePhaseEnlistment enlistment) { // The transaction was aborted, report that to SysTx and log the same. enlistment.Aborted(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection null, aborted before rollback.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection null, aborted before rollback.", ObjectID); } } @@ -317,7 +317,7 @@ public void SinglePhaseCommit(SinglePhaseEnlistment enlistment) if (null != connection) { SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, committing transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, committing transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try { @@ -421,7 +421,7 @@ public void SinglePhaseCommit(SinglePhaseEnlistment enlistment) { // The transaction was aborted before we could commit, report that to SysTx and log the same. enlistment.Aborted(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection null, aborted before commit.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection null, aborted before commit.", ObjectID); } } @@ -435,7 +435,7 @@ internal void TransactionEnded(Transaction transaction) if (connection != null) { - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, transaction completed externally.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, transaction completed externally.", ObjectID, connection.ObjectID); lock (connection) { if (_atomicTransaction.Equals(transaction)) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependency.cs index 6ed472f518..23c8ad767c 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -245,7 +245,7 @@ public SqlDependency(SqlCommand command) : this(command, null, SQL.SqlDependency /// public SqlDependency(SqlCommand command, string options, int timeout) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, options: '{1}', timeout: '{2}'", ObjectID, options, timeout); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, options: '{1}', timeout: '{2}'", ObjectID, options, timeout); try { if (timeout < 0) @@ -264,7 +264,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -294,7 +294,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) // EventHandlers to be fired when dependency is notified. add { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { if (null != value) @@ -329,12 +329,12 @@ public SqlDependency(SqlCommand command, string options, int timeout) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } remove { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { if (null != value) @@ -352,7 +352,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } @@ -362,7 +362,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) public void AddCommandDependency(SqlCommand command) { // Adds command to dependency collection so we automatically create the SqlNotificationsRequest object - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { // and listen for a notification for the added commands. @@ -375,7 +375,7 @@ public void AddCommandDependency(SqlCommand command) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -396,7 +396,7 @@ public static bool Start(string connectionString, string queue) internal static bool Start(string connectionString, string queue, bool useDefaults) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); try { if (string.IsNullOrEmpty(connectionString)) @@ -455,7 +455,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul SqlDependencyPerAppDomainDispatcher.SingletonInstance, out errorOccurred, out appDomainStart); - SqlClientEventSource.Log.NotificationTraceEvent(" Start (defaults) returned: '{0}', with service: '{1}', server: '{2}', database: '{3}'", result, service, server, database); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Start (defaults) returned: '{0}', with service: '{1}', server: '{2}', database: '{3}'", result, service, server, database); } finally { @@ -477,7 +477,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - SqlClientEventSource.Log.NotificationTraceEvent(" Exception occurred from Stop() after duplicate was found on Start()."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception occurred from Stop() after duplicate was found on Start()."); } throw SQL.SqlDependencyDuplicateStart(); } @@ -491,7 +491,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul queue, s_appDomainKey, SqlDependencyPerAppDomainDispatcher.SingletonInstance); - SqlClientEventSource.Log.NotificationTraceEvent(" Start (user provided queue) returned: '{0}'", result); + SqlClientEventSource.Log.TryNotificationTraceEvent(" 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. @@ -505,7 +505,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - SqlClientEventSource.Log.NotificationTraceEvent(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); throw; } } @@ -514,7 +514,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -532,7 +532,7 @@ public static bool Stop(string connectionString, string queue) internal static bool Stop(string connectionString, string queue, bool useDefaults, bool startFailed) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); try { if (string.IsNullOrEmpty(connectionString)) @@ -628,7 +628,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -636,7 +636,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault private static bool AddToServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); try { bool result = false; @@ -647,7 +647,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!s_serverUserHash.ContainsKey(server)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Hash did not contain server, adding."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Hash did not contain server, adding."); identityDatabaseHash = new Dictionary>(); s_serverUserHash.Add(server, identityDatabaseHash); } @@ -660,7 +660,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!identityDatabaseHash.ContainsKey(identityUser)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Hash contained server but not user, adding user."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Hash contained server but not user, adding user."); databaseServiceList = new List(); identityDatabaseHash.Add(identityUser, databaseServiceList); } @@ -671,13 +671,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!databaseServiceList.Contains(databaseService)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Adding database."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Adding database."); databaseServiceList.Add(databaseService); result = true; } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash already contained server, user, and database - we will throw!."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash already contained server, user, and database - we will throw!."); } } @@ -685,13 +685,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private static void RemoveFromServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); try { lock (s_serverUserHash) @@ -711,43 +711,43 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair int index = databaseServiceList.IndexOf(databaseService); if (index >= 0) { - SqlClientEventSource.Log.NotificationTraceEvent(" Hash contained server, user, and database - removing database."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Hash contained server, user, and database - removing database."); databaseServiceList.RemoveAt(index); if (databaseServiceList.Count == 0) { - SqlClientEventSource.Log.NotificationTraceEvent(" databaseServiceList count 0, removing the list for this server and user."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" databaseServiceList count 0, removing the list for this server and user."); identityDatabaseHash.Remove(identityUser); if (identityDatabaseHash.Count == 0) { - SqlClientEventSource.Log.NotificationTraceEvent(" identityDatabaseHash count 0, removing the hash for this server."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" identityDatabaseHash count 0, removing the hash for this server."); s_serverUserHash.Remove(server); } } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash contained server and user but not database!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash contained server and user but not database!"); Debug.Fail("Unexpected state - hash did not contain database!"); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash contained server but not user!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash contained server but not user!"); Debug.Fail("Unexpected state - hash did not contain user!"); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash did not contain server!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash did not contain server!"); Debug.Fail("Unexpected state - hash did not contain server!"); } } } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -755,7 +755,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { // Server must be an exact match, but user and database only needs to match exactly if there is more than one // for the given user or database passed. That is ambiguous and we must fail. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" server: '{0}', failoverServer: '{1}', database: '{2}'", server, failoverServer, database); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" server: '{0}', failoverServer: '{1}', database: '{2}'", server, failoverServer, database); try { string result; @@ -767,17 +767,17 @@ internal static string GetDefaultComposedOptions(string server, string failoverS if (0 == s_serverUserHash.Count) { // Special error for no calls to start. - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - no start calls have been made, about to throw."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - no start calls have been made, about to throw."); throw SQL.SqlDepDefaultOptionsButNoStart(); } else if (!string.IsNullOrEmpty(failoverServer) && s_serverUserHash.ContainsKey(failoverServer)) { - SqlClientEventSource.Log.NotificationTraceEvent(" using failover server instead\n"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" using failover server instead\n"); server = failoverServer; } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - not listening to this server, about to throw."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - not listening to this server, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } } @@ -790,7 +790,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { if (identityDatabaseHash.Count > 1) { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - not listening for this user, " + + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - not listening for this user, " + "but listening to more than one other user, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } @@ -839,19 +839,19 @@ internal static string GetDefaultComposedOptions(string server, string failoverS else { // More than one database for given server, ambiguous - fail the default case! - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); throw SQL.SqlDependencyNoMatchingServerDatabaseStart(); } } } Debug.Assert(!string.IsNullOrEmpty(result), "GetDefaultComposedOptions should never return null or empty string!"); - SqlClientEventSource.Log.NotificationTraceEvent(" resulting options: '{0}'.", result); + SqlClientEventSource.Log.TryNotificationTraceEvent(" resulting options: '{0}'.", result); return result; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -861,7 +861,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS // use this list for a reverse lookup based on server. internal void AddToServerList(string server) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); try { lock (_serverList) @@ -877,7 +877,7 @@ internal void AddToServerList(string server) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -891,7 +891,7 @@ internal bool ContainsServer(string server) internal string ComputeHashAndAddToDispatcher(SqlCommand command) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, command.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {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. @@ -903,18 +903,18 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) string commandHash = ComputeCommandHash(command.Connection.ConnectionString, command); // calculate the string representation of command string idString = SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddCommandEntry(commandHash, this); // Add to map. - SqlClientEventSource.Log.NotificationTraceEvent(" computed id string: '{0}'.", idString); + SqlClientEventSource.Log.TryNotificationTraceEvent(" computed id string: '{0}'.", idString); return idString; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { List eventList = null; @@ -928,7 +928,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (ExpirationTime >= DateTime.UtcNow) { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - notification received twice - we should never enter this state!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - notification received twice - we should never enter this state!"); Debug.Fail("Received notification twice - we should never enter this state!"); } else @@ -937,7 +937,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql // raises Timeout event but before removing this event from the list. If notification is received from // server in this case, we will hit this code path. // It is safe to ignore this race condition because no event is sent to user and no leak happens. - SqlClientEventSource.Log.NotificationTraceEvent(" ignore notification received after timeout!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ignore notification received after timeout!"); } } else @@ -951,7 +951,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (eventList != null) { - SqlClientEventSource.Log.NotificationTraceEvent(" Firing events."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Firing events."); foreach (EventContextPair pair in eventList) { pair.Invoke(new SqlNotificationEventArgs(type, info, source)); @@ -960,14 +960,14 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is used by SqlCommand. internal void StartTimer(SqlNotificationRequest notificationRequest) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { if (_expirationTime == DateTime.MaxValue) @@ -989,7 +989,7 @@ internal void StartTimer(SqlNotificationRequest notificationRequest) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1000,7 +1000,7 @@ private void AddCommandInternal(SqlCommand cmd) if (cmd != null) { // Don't bother with EventSource if command null. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, cmd.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, cmd.ObjectID); try { SqlConnection connection = cmd.Connection; @@ -1010,7 +1010,7 @@ private void AddCommandInternal(SqlCommand cmd) // Fail if cmd has notification that is not already associated with this dependency. if (cmd._sqlDep == null || cmd._sqlDep != this) { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - throwing command has existing SqlNotificationRequest exception."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - throwing command has existing SqlNotificationRequest exception."); throw SQL.SqlCommandHasExistingSqlNotificationRequest(); } } @@ -1044,7 +1044,7 @@ private void AddCommandInternal(SqlCommand cmd) if (0 == _eventList.Count) { // Keep logic just in case. - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - firing events, though it is unexpected we have events at this point."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - firing events, though it is unexpected we have events at this point."); needToInvalidate = true; // Delay invalidation until outside of lock. } } @@ -1058,14 +1058,14 @@ private void AddCommandInternal(SqlCommand cmd) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } private string ComputeCommandHash(string connectionString, SqlCommand command) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, command.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {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. @@ -1121,12 +1121,12 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) } string result = builder.ToString(); - SqlClientEventSource.Log.NotificationTraceEvent(" ComputeCommandHash result: '{0}'.", result); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ComputeCommandHash result: '{0}'.", result); return result; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index 1b2a03cd15..3fdcdebbec 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -55,7 +55,7 @@ private class SqlConnectionContainer internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, HashHelper?.Queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, HashHelper?.Queue); bool setupCompleted = false; try { @@ -76,7 +76,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str } #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(_hashHelper.ConnectionStringBuilder.ConnectionString); - SqlClientEventSource.Log.NotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif // Always use ConnectionStringBuilder since in default case it is different from the @@ -175,7 +175,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -207,7 +207,7 @@ internal string Database // SqlDependencyProcessDispatcher.QueueAppDomainUnload on AppDomain.Unload. internal bool AppDomainUnload(string appDomainKey) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, AppDomainKey: '{1}'", ObjectID, appDomainKey); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, AppDomainKey: '{1}'", ObjectID, appDomainKey); try { Debug.Assert(!string.IsNullOrEmpty(appDomainKey), "Unexpected empty appDomainKey!"); @@ -219,9 +219,9 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { // Do nothing if AppDomain did not call Start! - SqlClientEventSource.Log.NotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}'.", appDomainKey); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}'.", appDomainKey); int value = _appDomainKeyHash[appDomainKey]; - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{0}' count: '{1}'.", appDomainKey, value); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{0}' count: '{1}'.", appDomainKey, value); Debug.Assert(value > 0, "Why is value 0 or less?"); bool ignored = false; @@ -238,26 +238,26 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{0}' entry not removed from hash. Count: {1}'", appDomainKey, _appDomainKeyHash[appDomainKey]); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{0}' entry not removed from hash. Count: {1}'", appDomainKey, _appDomainKeyHash[appDomainKey]); } } else { - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{0}'.", appDomainKey); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{0}'.", appDomainKey); } } - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{0}'.", _stopped); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{0}'.", _stopped); return _stopped; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void AsynchronouslyQueryServiceBrokerQueue() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { AsyncCallback callback = new AsyncCallback(AsyncResultCallback); @@ -265,13 +265,13 @@ private void AsynchronouslyQueryServiceBrokerQueue() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void AsyncResultCallback(IAsyncResult asyncResult) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { using (SqlDataReader reader = _com.EndExecuteReader(asyncResult)) @@ -297,7 +297,7 @@ private void AsyncResultCallback(IAsyncResult asyncResult) _errorState = true; throw; } - SqlClientEventSource.Log.NotificationTraceEvent(" Exception occurred."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception occurred."); if (!_stop) { // Only assert if not in cancel path. @@ -317,13 +317,13 @@ private void AsyncResultCallback(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void CreateQueueAndService(bool restart) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { SqlCommand com = new SqlCommand() @@ -457,18 +457,18 @@ private void CreateQueueAndService(bool restart) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { appDomainStart = false; // Reset out param. int result = Interlocked.Increment(ref _startCount); // Add to refCount. - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> {0}, incremented _startCount: {1}", s_staticInstance.ObjectID, result); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> {0}, incremented _startCount: {1}", s_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. @@ -477,25 +477,25 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { _appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1; - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{0}', incremented count: '{1}'.", appDomainKey, _appDomainKeyHash[appDomainKey]); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{0}', incremented count: '{1}'.", appDomainKey, _appDomainKeyHash[appDomainKey]); } else { _appDomainKeyHash[appDomainKey] = 1; appDomainStart = true; - SqlClientEventSource.Log.NotificationTraceEvent(" _appDomainKeyHash did not contain AppDomainKey: '{0}', added to hashtable and value set to 1.", appDomainKey); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _appDomainKeyHash did not contain AppDomainKey: '{0}', added to hashtable and value set to 1.", appDomainKey); } } } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void ProcessNotificationResults(SqlDataReader reader) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); Guid handle = Guid.Empty; // Conversation_handle. Always close this! try { @@ -503,18 +503,18 @@ private void ProcessNotificationResults(SqlDataReader reader) { while (reader.Read()) { - SqlClientEventSource.Log.NotificationTraceEvent(" Row read."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Row read."); #if DEBUG if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) { for (int i = 0; i < reader.FieldCount; i++) { - SqlClientEventSource.Log.NotificationTraceEvent(" column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i).ToString()); + SqlClientEventSource.Log.NotificationTraceEvent(" column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i)); } } #endif string msgType = reader.GetString(0); - SqlClientEventSource.Log.NotificationTraceEvent(" msgType: '{0}'", msgType); + SqlClientEventSource.Log.TryNotificationTraceEvent(" msgType: '{0}'", msgType); handle = reader.GetGuid(1); // Only process QueryNotification messages. @@ -527,7 +527,7 @@ private void ProcessNotificationResults(SqlDataReader reader) if (null != notification) { string key = notification.Key; - SqlClientEventSource.Log.NotificationTraceEvent(" Key: '{0}'", key); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Key: '{0}'", key); int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash" if (index >= 0) @@ -556,31 +556,31 @@ private void ProcessNotificationResults(SqlDataReader reader) else { Debug.Fail("Received notification but do not have an associated PerAppDomainDispatcher!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Received notification but do not have an associated PerAppDomainDispatcher!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Received notification but do not have an associated PerAppDomainDispatcher!"); } } else { Debug.Fail("Unexpected ID format received!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Unexpected ID format received!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Unexpected ID format received!"); } } else { Debug.Fail("Null notification returned from ProcessMessage!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Null notification returned from ProcessMessage!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Null notification returned from ProcessMessage!"); } } else { Debug.Fail("Null payload for QN notification type!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Null payload for QN notification type!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Null payload for QN notification type!"); } } else { handle = Guid.Empty; - SqlClientEventSource.Log.NotificationTraceEvent(" Unexpected message format received!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Unexpected message format received!"); } } } @@ -608,13 +608,13 @@ private void ProcessNotificationResults(SqlDataReader reader) } Debug.Assert(_com.Parameters.Count == 2, "Unexpected number of parameters!"); } - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void Restart(object unused) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { // Unused arg required by TimerCallback. @@ -762,13 +762,13 @@ private void Restart(object unused) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } internal bool Stop(string appDomainKey, out bool appDomainStop) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { appDomainStop = false; @@ -786,7 +786,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) int value = _appDomainKeyHash[appDomainKey]; Debug.Assert(value > 0, "Unexpected count for appDomainKey"); - SqlClientEventSource.Log.NotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}', pre-decrement Count: '{1}'.", appDomainKey, value); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}', pre-decrement Count: '{1}'.", appDomainKey, value); if (value > 0) { @@ -794,7 +794,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR pre-decremented count <= 0!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR pre-decremented count <= 0!"); Debug.Fail("Unexpected AppDomainKey count in Stop()"); } @@ -806,7 +806,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR appDomainKey not null and not found in hash!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR appDomainKey not null and not found in hash!"); Debug.Fail("Unexpected state on Stop() - no AppDomainKey entry in hashtable!"); } } @@ -819,7 +819,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) { // If we've reached refCount 0, destroy. // Lock to ensure Cancel() complete prior to other thread calling TearDown. - SqlClientEventSource.Log.NotificationTraceEvent(" Reached 0 count, cancelling and waiting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Reached 0 count, cancelling and waiting."); lock (this) { @@ -862,7 +862,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) // TearDownAndDispose in the maximum retry period case as well as in the _errorState case. if (_errorState || retryStopwatch.Elapsed.Seconds >= 30) { - SqlClientEventSource.Log.NotificationTraceEvent(" forcing cleanup. elapsedSeconds: '{0}', _errorState: '{1}'.", retryStopwatch.Elapsed.Seconds, _errorState); + SqlClientEventSource.Log.TryNotificationTraceEvent(" forcing cleanup. elapsedSeconds: '{0}', _errorState: '{1}'.", retryStopwatch.Elapsed.Seconds, _errorState); Timer retryTimer = _retryTimer; _retryTimer = null; if (retryTimer != null) @@ -881,7 +881,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" _startCount not 0 after decrement. _startCount: '{0}'.", _startCount); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _startCount not 0 after decrement. _startCount: '{0}'.", _startCount); } Debug.Assert(0 <= _startCount, "Invalid start count state"); @@ -890,13 +890,13 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void SynchronouslyQueryServiceBrokerQueue() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { using (SqlDataReader reader = _com.ExecuteReader()) @@ -906,14 +906,14 @@ private void SynchronouslyQueryServiceBrokerQueue() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } [SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")] private void TearDownAndDispose() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { lock (this) @@ -981,7 +981,7 @@ private void TearDownAndDispose() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } @@ -1116,42 +1116,42 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) catch (ArgumentException e) { ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace. - SqlClientEventSource.Log.TraceEvent(" Exception thrown - Enum.Parse failed to parse the value '{0}' of the attribute '{1}'.", xmlReader.Value, xmlReader.LocalName); + SqlClientEventSource.Log.TryTraceEvent(" Exception thrown - Enum.Parse failed to parse the value '{0}' of the attribute '{1}'.", xmlReader.Value, xmlReader.LocalName); return null; } } if (MessageAttributes.All != messageAttributes) { - SqlClientEventSource.Log.TraceEvent(" Not all expected attributes in Message; messageAttributes = '{0}'.", (int)messageAttributes); + SqlClientEventSource.Log.TryTraceEvent(" Not all expected attributes in Message; messageAttributes = '{0}'.", (int)messageAttributes); return null; } // Proceed to the "Message" node. if (!xmlReader.Read()) { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" 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))) { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Proceed to the Text Node. if (!xmlReader.Read()) { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Verify state after Read(). if (xmlReader.NodeType != XmlNodeType.Text) { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } @@ -1161,7 +1161,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the Text Node. if (!xmlMessageReader.Read()) { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } @@ -1172,7 +1172,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } } @@ -1181,7 +1181,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; // failure } } @@ -1310,19 +1310,19 @@ public override int GetHashCode() private SqlDependencyProcessDispatcher(object dummyVariable) { Debug.Assert(null == s_staticInstance, "Real constructor called with static instance already created!"); - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); #endif _connectionContainers = new Dictionary(); _sqlDependencyPerAppDomainDispatchers = new Dictionary(); } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1331,17 +1331,17 @@ private SqlDependencyProcessDispatcher(object dummyVariable) public SqlDependencyProcessDispatcher() { // Empty constructor and object - dummy to obtain singleton. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); #endif } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1358,7 +1358,7 @@ public SqlDependencyProcessDispatcher() out string user, string queue) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: {1}", s_staticInstance.ObjectID, queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: {1}", s_staticInstance.ObjectID, queue); try { // Force certain connection string properties to be used by SqlDependencyProcessDispatcher. @@ -1392,7 +1392,7 @@ public SqlDependencyProcessDispatcher() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1404,7 +1404,7 @@ public override object InitializeLifetimeService() private void Invalidate(string server, SqlNotification sqlNotification) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, server: {1}", ObjectID, server); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, server: {1}", ObjectID, server); try { Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1436,7 +1436,7 @@ private void Invalidate(string server, SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1451,7 +1451,7 @@ internal void QueueAppDomainUnloading(string appDomainKey) // This method is only called by queued work-items from the method above. private void AppDomainUnloading(object state) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { string appDomainKey = (string)state; @@ -1483,7 +1483,7 @@ private void AppDomainUnloading(object state) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1553,7 +1553,7 @@ private void AppDomainUnloading(object state) bool useDefaults) { Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!"); - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: '{1}', appDomainKey: '{2}', perAppDomainDispatcher ID: '{3}'", ObjectID, queueService, appDomainKey, dispatcher.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: '{1}', appDomainKey: '{2}', perAppDomainDispatcher ID: '{3}'", ObjectID, queueService, appDomainKey, dispatcher.ObjectID); try { server = null; // Reset out params. @@ -1578,7 +1578,7 @@ private void AppDomainUnloading(object state) queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - SqlClientEventSource.Log.NotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif bool started = false; @@ -1588,7 +1588,7 @@ private void AppDomainUnloading(object state) { if (!_connectionContainers.ContainsKey(hashHelper)) { - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable miss, creating new container.", ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable miss, creating new container.", ObjectID); container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults); _connectionContainers.Add(hashHelper, container); started = true; @@ -1597,10 +1597,10 @@ private void AppDomainUnloading(object state) else { container = _connectionContainers[hashHelper]; - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); if (container.InErrorState) { - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, container: {1} is in error state!", ObjectID, container.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, container: {1} is in error state!", ObjectID, container.ObjectID); errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start(). } else @@ -1615,14 +1615,14 @@ private void AppDomainUnloading(object state) server = container.Server; database = container.Database; queueService = container.Queue; - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, default service: '{1}', server: '{2}', database: '{3}'", ObjectID, queueService, server, database); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, default service: '{1}', server: '{2}', database: '{3}'", ObjectID, queueService, server, database); } - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, started: {1}", ObjectID, started); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, started: {1}", ObjectID, started); return started; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1638,7 +1638,7 @@ private void AppDomainUnloading(object state) string appDomainKey, out bool appDomainStop) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, queueService); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, queueService); Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!"); try { @@ -1655,7 +1655,7 @@ private void AppDomainUnloading(object state) queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - SqlClientEventSource.Log.NotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif bool stopped = false; @@ -1665,7 +1665,7 @@ private void AppDomainUnloading(object state) if (_connectionContainers.ContainsKey(hashHelper)) { SqlConnectionContainer container = _connectionContainers[hashHelper]; - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {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; @@ -1678,15 +1678,15 @@ private void AppDomainUnloading(object state) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable miss.", ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable miss.", ObjectID); } } - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, stopped: {1}", ObjectID, stopped); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, stopped: {1}", ObjectID, stopped); return stopped; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.AppDomain.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.AppDomain.cs index 65bc264f21..0ebb461cc7 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.AppDomain.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.AppDomain.cs @@ -19,7 +19,7 @@ private void SubscribeToAppDomainUnload() private void UnloadEventHandler(object sender, EventArgs e) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { // Make non-blocking call to ProcessDispatcher to ThreadPool.QueueUserWorkItem to complete @@ -31,7 +31,7 @@ private void UnloadEventHandler(object sender, EventArgs e) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs index 98f474ea2b..e4f2a4446a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs @@ -80,7 +80,7 @@ internal DependencyList(string commandHash) private SqlDependencyPerAppDomainDispatcher() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { _dependencyIdToDependencyHash = new Dictionary(); @@ -97,7 +97,7 @@ private SqlDependencyPerAppDomainDispatcher() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -113,7 +113,7 @@ public override object InitializeLifetimeService() // This method is called upon SqlDependency constructor. internal void AddDependencyEntry(SqlDependency dep) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); try { lock (_instanceLock) @@ -123,14 +123,14 @@ internal void AddDependencyEntry(SqlDependency dep) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is called upon Execute of a command associated with a SqlDependency object. internal string AddCommandEntry(string commandHash, SqlDependency dep) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, commandHash: '{1}', SqlDependency: {2}", ObjectID, commandHash, dep.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, commandHash: '{1}', SqlDependency: {2}", ObjectID, commandHash, dep.ObjectID); string notificationId = string.Empty; try { @@ -139,7 +139,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) if (!_dependencyIdToDependencyHash.ContainsKey(dep.Id)) { // Determine if depId->dep hashtable contains dependency. If not, it's been invalidated. - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency not present in depId->dep hash, must have been invalidated."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency not present in depId->dep hash, must have been invalidated."); } else { @@ -160,12 +160,12 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // join the new dependency to the list if (!dependencyList.Contains(dep)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency not present for commandHash, adding."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency not present for commandHash, adding."); dependencyList.Add(dep); } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency already present for commandHash."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency already present for commandHash."); } } else @@ -179,7 +179,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) SqlDependency.AppDomainKey, // must be first Guid.NewGuid().ToString("D", System.Globalization.CultureInfo.InvariantCulture) ); - SqlClientEventSource.Log.NotificationTraceEvent(" Creating new Dependencies list for commandHash."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Creating new Dependencies list for commandHash."); DependencyList dependencyList = new DependencyList(commandHash); dependencyList.Add(dep); @@ -196,14 +196,14 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is called by the ProcessDispatcher upon a notification for this AppDomain. internal void InvalidateCommandID(SqlNotification sqlNotification) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, sqlNotification.Key); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, sqlNotification.Key); try { List dependencyList = null; @@ -214,7 +214,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) if (null != dependencyList) { - SqlClientEventSource.Log.NotificationTraceEvent(" commandHash found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" commandHash found in hashtable."); foreach (SqlDependency dependency in dependencyList) { // Ensure we remove from process static app domain hash for dependency initiated invalidates. @@ -226,7 +226,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" commandHash NOT found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" commandHash NOT found in hashtable."); } } @@ -235,7 +235,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) // After removal from hashtables, invalidate. foreach (SqlDependency dependency in dependencyList) { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency found in commandHash dependency ArrayList - calling invalidate."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency found in commandHash dependency ArrayList - calling invalidate."); try { dependency.Invalidate(sqlNotification.Type, sqlNotification.Info, sqlNotification.Source); @@ -256,14 +256,14 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(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) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); try { List dependencies = new List(); @@ -310,14 +310,14 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is called by SqlCommand to enable ASP.NET scenarios - map from ID to Dependency. internal SqlDependency LookupDependencyEntry(string id) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, Key: '{1}'", ObjectID, id); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, Key: '{1}'", ObjectID, id); try { if (null == id) @@ -339,7 +339,7 @@ internal SqlDependency LookupDependencyEntry(string id) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - dependency ID mismatch - not throwing."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - dependency ID mismatch - not throwing."); } } @@ -347,21 +347,21 @@ internal SqlDependency LookupDependencyEntry(string id) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // Remove the dependency from the hashtable with the passed id. private void LookupDependencyEntryWithRemove(string id) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, id: '{1}'", ObjectID, id); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, id: '{1}'", ObjectID, id); try { lock (_instanceLock) { if (_dependencyIdToDependencyHash.ContainsKey(id)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Entry found in hashtable - removing."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entry found in hashtable - removing."); _dependencyIdToDependencyHash.Remove(id); // if there are no more dependencies then we can dispose the timer. @@ -373,20 +373,20 @@ private void LookupDependencyEntryWithRemove(string id) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Entry NOT found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entry NOT found in hashtable."); } } } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // Find and return arraylist, and remove passed hash value. private List LookupCommandEntryWithRemove(string notificationId) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, notificationId); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, notificationId); try { DependencyList entry = null; @@ -395,7 +395,7 @@ private List LookupCommandEntryWithRemove(string notificationId) { if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Entries found in hashtable - removing."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entries found in hashtable - removing."); // update the tables _notificationIdToDependenciesHash.Remove(notificationId); @@ -404,7 +404,7 @@ private List LookupCommandEntryWithRemove(string notificationId) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Entries NOT found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entries NOT found in hashtable."); } Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!"); @@ -414,14 +414,14 @@ private List LookupCommandEntryWithRemove(string notificationId) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // Remove from commandToDependenciesHash all references to the passed dependency. private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency dependency) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dependency.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dependency.ObjectID); try { lock (_instanceLock) @@ -434,7 +434,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende DependencyList dependencies = entry.Value; if (dependencies.Remove(dependency)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Removed SqlDependency: {0}, with ID: '{1}'.", dependency.ObjectID, dependency.Id); + SqlClientEventSource.Log.TryNotificationTraceEvent(" 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 @@ -461,7 +461,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -469,7 +469,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende internal void StartTimer(SqlDependency dep) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); try { // If this dependency expires sooner than the current next timeout, change @@ -480,7 +480,7 @@ internal void StartTimer(SqlDependency dep) // Enable the timer if needed (disable when empty, enable on the first addition). if (!_sqlDependencyTimeOutTimerStarted) { - SqlClientEventSource.Log.NotificationTraceEvent(" Timer not yet started, starting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Timer not yet started, starting."); _timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */); // Save this as the earlier timeout to come. @@ -489,7 +489,7 @@ internal void StartTimer(SqlDependency dep) } else if (_nextTimeout > dep.ExpirationTime) { - SqlClientEventSource.Log.NotificationTraceEvent(" Timer already started, resetting time."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Timer already started, resetting time."); // Save this as the earlier timeout to come. _nextTimeout = dep.ExpirationTime; @@ -498,13 +498,13 @@ internal void StartTimer(SqlDependency dep) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private static void TimeoutTimerCallback(object state) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" AppDomainKey: '{0}'", SqlDependency.AppDomainKey); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" AppDomainKey: '{0}'", SqlDependency.AppDomainKey); try { SqlDependency[] dependencies; @@ -516,14 +516,14 @@ private static void TimeoutTimerCallback(object state) { if (0 == SingletonInstance._dependencyIdToDependencyHash.Count) { - SqlClientEventSource.Log.NotificationTraceEvent(" No dependencies, exiting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" No dependencies, exiting."); // Nothing to check. return; } if (SingletonInstance._nextTimeout > DateTime.UtcNow) { - SqlClientEventSource.Log.NotificationTraceEvent(" No timeouts expired, exiting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" No timeouts expired, exiting."); // No dependency timed-out yet. return; @@ -594,7 +594,7 @@ private static void TimeoutTimerCallback(object state) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs index 05c1dd75b5..5d9f130578 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs @@ -28,7 +28,7 @@ internal SqlError(int infoNumber, byte errorState, byte errorClass, string serve Exception = exception; if (errorClass != 0) { - 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); + SqlClientEventSource.Log.TryTraceEvent(" infoNumber={0}, errorState={1}, errorClass={2}, errorMessage='{3}', procedure='{4}', lineNumber={5}", infoNumber, (int)errorState, (int)errorClass, errorMessage, procedure ?? "None", (int)lineNumber); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index fa7c78364e..8255b4d4bb 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -254,7 +254,7 @@ override protected void Deactivate() { try { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} deactivating", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} deactivating", ObjectID); SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection; if (null != referenceCollection) { @@ -334,12 +334,12 @@ protected void Enlist(Transaction tx) private void EnlistNonNull(Transaction tx) { Debug.Assert(null != tx, "null transaction?"); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transaction {1}.", ObjectID, tx.GetHashCode()); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transaction {1}.", ObjectID, tx.GetHashCode()); bool hasDelegatedTransaction = false; // Promotable transactions are only supported on Yukon // servers or newer. - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, attempting to delegate", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, attempting to delegate", ObjectID); SqlDelegatedTransaction delegatedTransaction = new SqlDelegatedTransaction(this, tx); try @@ -403,7 +403,7 @@ private void EnlistNonNull(Transaction tx) if (hasDelegatedTransaction) { this.DelegatedTransaction = delegatedTransaction; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, delegated to transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, delegated to transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); } } catch (SqlException e) @@ -433,7 +433,7 @@ private void EnlistNonNull(Transaction tx) if (!hasDelegatedTransaction) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, delegation not possible, enlisting.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, delegation not possible, enlisting.", ObjectID); byte[] cookie = null; if (_isGlobalTransaction) @@ -464,7 +464,7 @@ private void EnlistNonNull(Transaction tx) PropagateTransactionCookie(cookie); _isEnlistedInTransaction = true; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, enlisted with transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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 @@ -488,7 +488,7 @@ private void EnlistNonNull(Transaction tx) internal void EnlistNull() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, unenlisting.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, unenlisting.", ObjectID); // We were in a transaction, but now we are not - so send // message to server with empty transaction - confirmed proper // behavior from Sameet Agarwal @@ -506,7 +506,7 @@ internal void EnlistNull() _isEnlistedInTransaction = false; EnlistedTransaction = null; // Tell the base class about our enlistment - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, unenlisted.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, unenlisted.", ObjectID); // The EnlistTransaction above will return an TransactionEnded event, // which causes the TdsParser or SmiEventSink should to clear the diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs index 912596b55d..04debd8d09 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs @@ -530,7 +530,7 @@ internal SqlConnectionTimeoutErrorInternal TimeoutErrorInternal ThreadHasParserLockForClose = false; _parserLock.Release(); } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, constructed new TDS internal connection", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, constructed new TDS internal connection", ObjectID); } // Returns true if the Sql error is a transient. @@ -728,7 +728,7 @@ protected override void ChangeDatabaseInternal(string database) public override void Dispose() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} disposing", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} disposing", ObjectID); try { TdsParser parser = Interlocked.Exchange(ref _parser, null); // guard against multiple concurrent dispose calls -- Delegated Transactions might cause this. @@ -1176,12 +1176,12 @@ private void CompleteLogin(bool enlistOK) // ROR should not affect state of connection recovery if (_federatedAuthenticationRequested && !_federatedAuthenticationAcknowledged) { - SqlClientEventSource.Log.TraceEvent(" {0}, Server did not acknowledge the federated authentication request", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Server did not acknowledge the federated authentication request", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged); } if (_federatedAuthenticationInfoRequested && !_federatedAuthenticationInfoReceived) { - SqlClientEventSource.Log.TraceEvent(" {0}, Server never sent the requested federated authentication info", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Server never sent the requested federated authentication info", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoNotReceived); } if (!_sessionRecoveryAcknowledged) @@ -1218,7 +1218,7 @@ private void CompleteLogin(bool enlistOK) _parser.EnableMars(); _fConnectionOpen = true; // mark connection as open - SqlClientEventSource.Log.AdvancedTraceEvent(" Post-Login Phase: Server connection obtained."); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Post-Login Phase: Server connection obtained."); // for non-pooled connections, enlist in a distributed transaction // if present - and user specified to enlist @@ -1340,7 +1340,7 @@ private void Login(ServerInfo server, TimeoutTimer timeout, string newPassword, private void LoginFailure() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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. @@ -1456,7 +1456,7 @@ private bool IsDoNotRetryConnectError(SqlException exc) Debug.Assert(object.ReferenceEquals(connectionOptions, this.ConnectionOptions), "ConnectionOptions argument and property must be the same"); // consider removing the argument int routingAttempts = 0; ServerInfo originalServerInfo = serverInfo; // serverInfo may end up pointing to new object due to routing, original object is used to set CurrentDatasource - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, host={1}", ObjectID, serverInfo.UserServerName); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, host={1}", ObjectID, serverInfo.UserServerName); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. ResolveExtendedServerName(serverInfo, !redirectedUserInstance, connectionOptions); @@ -1525,7 +1525,7 @@ private bool IsDoNotRetryConnectError(SqlException exc) if (RoutingInfo != null) { - SqlClientEventSource.Log.TraceEvent(" Routed to {0}", serverInfo.ExtendedServerName); + SqlClientEventSource.Log.TryTraceEvent(" Routed to {0}", serverInfo.ExtendedServerName); if (routingAttempts > 0) { throw SQL.ROR_RecursiveRoutingNotSupported(this); @@ -1611,7 +1611,7 @@ private bool IsDoNotRetryConnectError(SqlException exc) // Sleep for a bit to prevent clogging the network with requests, // then update sleep interval for next iteration (max 1 second interval) - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } @@ -1675,7 +1675,7 @@ TimeoutTimer timeout ) { Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used"); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, useFailover={1}[bool], primary={2}, failover={3}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName, failoverHost ?? "null"); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, useFailover={1}[bool], primary={2}, failover={3}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName, failoverHost); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. long timeoutUnitInterval; @@ -1734,7 +1734,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) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); failoverServerInfo.SetDerivedNames(string.Empty, ServerProvidedFailOverPartner); } currentServerInfo = failoverServerInfo; @@ -1764,7 +1764,7 @@ TimeoutTimer timeout // If it is read-only routing - we did not supply AppIntent=RO (it should be checked before) // If it is something else, not known yet (future server) - this client is not designed to support this. // In any case, server should not have sent the routing info. - SqlClientEventSource.Log.TraceEvent(" Routed to {0}", RoutingInfo.ServerName); + SqlClientEventSource.Log.TryTraceEvent(" Routed to {0}", RoutingInfo.ServerName); throw SQL.ROR_UnexpectedRoutingInfo(this); } break; // leave the while loop -- we've successfully connected @@ -1804,7 +1804,7 @@ TimeoutTimer timeout // the network with requests, then update sleep interval for next iteration (max 1 second interval) if (1 == attemptNumber % 2) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } @@ -1860,7 +1860,7 @@ private void ResolveExtendedServerName(ServerInfo serverInfo, bool aliasLookup, TimeoutTimer timeout, bool withFailover = false) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); RoutingInfo = null; // forget routing information _parser._physicalStateObj.SniContext = SniContext.Snix_Connect; @@ -1962,7 +1962,7 @@ internal bool GetSessionAndReconnectIfNeeded(SqlConnection parent, int timeout = internal void BreakConnection() { var connection = Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Breaking connection.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Breaking connection.", ObjectID); DoomThisConnection(); // Mark connection as unusable, so it will be destroyed if (null != connection) { @@ -2068,7 +2068,7 @@ internal void OnEnvChange(SqlEnvChange rec) break; case TdsEnums.ENV_ROUTING: - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received routing info", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received routing info", ObjectID); if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0) { throw SQL.ROR_InvalidRoutingInfo(this); @@ -2112,7 +2112,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."); - SqlClientEventSource.Log.TraceEvent(" {0}, Generating federated authentication token", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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. @@ -2141,9 +2141,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // And on successful login, try to update the cache with the new token. if (contextValidity <= _dbAuthenticationContextUnLockedRefreshTimeSpan) { - 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()); + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + 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; } @@ -2163,9 +2166,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // If a thread is already doing the refresh, just use the existing token in the cache and proceed. else if (contextValidity <= _dbAuthenticationContextLockedRefreshTimeSpan) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, " + - "The authentication context needs a refresh.The expiration time is {1}. " + - "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" {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. @@ -2179,10 +2185,10 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // Indicate in EventSource Trace that we are successful with the update. if (attemptRefreshTokenLocked) { - SqlClientEventSource.Log.TraceEvent(" {0}, The attempt to get a new access token succeeded under the locked mode.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, The attempt to get a new access token succeeded under the locked mode.", ObjectID); } } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); } } @@ -2243,14 +2249,17 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP // Else some other thread is already updating it, so just proceed forward with the existing token in the cache. if (dbConnectionPoolAuthenticationContext.LockToUpdate()) { - SqlClientEventSource.Log.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()); + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + 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 { - SqlClientEventSource.Log.TraceEvent(" {0}, Refreshing the context is already in progress by another thread.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Refreshing the context is already in progress by another thread.", ObjectID); } if (authenticationContextLocked) @@ -2421,7 +2430,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) || _timeout.IsExpired || _timeout.MillisecondsRemaining <= sleepInterval) { - SqlClientEventSource.Log.TraceEvent(" {0}", msalException.ErrorCode); + SqlClientEventSource.Log.TryTraceEvent(" {0}", msalException.ErrorCode); // Error[0] SqlErrorCollection sqlErs = new SqlErrorCollection(); sqlErs.Add(new SqlError(0, (byte)0x00, (byte)TdsEnums.MIN_ERROR_CLASS, ConnectionOptions.DataSource, StringsHelper.GetString(Strings.SQL_MSALFailure, username, ConnectionOptions.Authentication.ToString("G")), ActiveDirectoryAuthentication.MSALGetAccessTokenFunctionName, 0)); @@ -2439,8 +2448,8 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) throw exc; } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); Thread.Sleep(sleepInterval); sleepInterval *= 2; @@ -2456,7 +2465,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) DateTime expirationTime = DateTime.FromFileTimeUtc(_fedAuthToken.expirationFileTime); _newDbConnectionPoolAuthenticationContext = new DbConnectionPoolAuthenticationContext(_fedAuthToken.accessToken, expirationTime); } - SqlClientEventSource.Log.TraceEvent(" {0}, Finished generating federated authentication token.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Finished generating federated authentication token.", ObjectID); return _fedAuthToken; } @@ -2524,10 +2533,10 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for GlobalTransactions", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for GlobalTransactions", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown version number for GlobalTransactions", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown version number for GlobalTransactions", ObjectID); throw SQL.ParsingError(); } @@ -2540,10 +2549,10 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_FEDAUTH: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for federated authentication", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for federated authentication", ObjectID); if (!_federatedAuthenticationRequested) { - SqlClientEventSource.Log.TraceEvent(" {0}, Did not request federated authentication", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Did not request federated authentication", ObjectID); throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); } @@ -2556,14 +2565,14 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // The server shouldn't have sent any additional data with the ack (like a nonce) if (data.Length != 0) { - SqlClientEventSource.Log.TraceEvent(" {0}, Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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"); - SqlClientEventSource.Log.TraceEvent(" {0}, Attempting to use unknown federated authentication library", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Attempting to use unknown federated authentication library", ObjectID); throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType); } _federatedAuthenticationAcknowledged = true; @@ -2582,11 +2591,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) { - SqlClientEventSource.Log.TraceEvent(" {0}, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); } else { - SqlClientEventSource.Log.TraceEvent(" {0}, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); } #endif } @@ -2595,17 +2604,17 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_TCE: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for TCE", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for TCE", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown version number for TCE", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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) { - SqlClientEventSource.Log.TraceEvent(" {0}, Invalid version number for TCE", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Invalid version number for TCE", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidVersion, supportedTceVersion); } @@ -2624,32 +2633,32 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_UTF8SUPPORT: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for UTF8 support", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for UTF8 support", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown value for UTF8 support", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown value for UTF8 support", ObjectID); throw SQL.ParsingError(); } break; } case TdsEnums.FEATUREEXT_DATACLASSIFICATION: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte supportedDataClassificationVersion = data[0]; if ((0 == supportedDataClassificationVersion) || (supportedDataClassificationVersion > TdsEnums.DATA_CLASSIFICATION_VERSION_MAX_SUPPORTED)) { - SqlClientEventSource.Log.TraceEvent(" {0}, Invalid version number for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Invalid version number for DATACLASSIFICATION", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.DataClassificationInvalidVersion, supportedDataClassificationVersion); } if (data.Length != 2) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte enabled = data[1]; @@ -2659,11 +2668,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_SQLDNSCACHING: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for SQLDNSCACHING", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for SQLDNSCACHING", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown token for SQLDNSCACHING", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown token for SQLDNSCACHING", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalTransaction.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalTransaction.cs index fc3ebc5487..77030bd20e 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalTransaction.cs @@ -52,7 +52,7 @@ internal SqlInternalTransaction(SqlInternalConnection innerConnection, Transacti internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction, long transactionId) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Created for connection {1}, outer transaction {2}, Type {3}", ObjectID, innerConnection.ObjectID, (null != outerTransaction) ? outerTransaction.ObjectID : -1, (int)type); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Created for connection {1}, outer transaction {2}, Type {3}", ObjectID, innerConnection.ObjectID, outerTransaction?.ObjectID, (int)type); _innerConnection = innerConnection; _transactionType = type; @@ -254,7 +254,7 @@ 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); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Closing", ObjectID); bool processFinallyBlock = true; try { @@ -280,7 +280,7 @@ internal void CloseFromConnection() internal void Commit() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { @@ -310,7 +310,7 @@ internal void Commit() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -339,7 +339,7 @@ internal void Dispose() private /*protected override*/ void Dispose(bool disposing) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Disposing", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Disposing", ObjectID); if (disposing) { if (null != _innerConnection) @@ -390,7 +390,7 @@ internal void InitParent(SqlTransaction transaction) internal void Rollback() { - var scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + var scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { throw SQL.ConnectionLockedForBcpEvent(); @@ -426,13 +426,13 @@ internal void Rollback() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } internal void Rollback(string transactionName) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, transactionName={1}", ObjectID, transactionName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, transactionName={1}", ObjectID, transactionName); if (_innerConnection.IsLockedForBulkCopy) { throw SQL.ConnectionLockedForBcpEvent(); @@ -462,13 +462,13 @@ internal void Rollback(string transactionName) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } internal void Save(string savePointName) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, savePointName={1}", ObjectID, savePointName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, savePointName={1}", ObjectID, savePointName); _innerConnection.ValidateConnectionForExecute(null); // ROLLBACK takes either a save point name or a transaction name. It will rollback the @@ -495,7 +495,7 @@ internal void Save(string savePointName) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlTransaction.cs index 4a936b4c7c..620b56917e 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -141,8 +141,8 @@ override public void Commit() ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -172,7 +172,7 @@ override public void Commit() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); if (e != null) { s_diagnosticListener.WriteTransactionCommitError(operationId, _isolationLevel, _connection, InternalTransaction, e); @@ -208,7 +208,7 @@ override public void Rollback() if (IsYukonPartialZombie) { // Put something in the trace in case a customer has an issue - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} partial zombie no rollback required", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} partial zombie no rollback required", ObjectID); _internalTransaction = null; // yukon zombification } else @@ -216,8 +216,8 @@ override public void Rollback() ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -234,7 +234,7 @@ override public void Rollback() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); if (e != null) { s_diagnosticListener.WriteTransactionRollbackError(operationId, _isolationLevel, _connection, InternalTransaction, e); @@ -255,7 +255,7 @@ public void Rollback(string transactionName) Guid operationId = s_diagnosticListener.WriteTransactionRollbackBefore(_isolationLevel, _connection, InternalTransaction, transactionName); ZombieCheck(); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} transactionName='{1}'", ObjectID, transactionName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} transactionName='{1}'", ObjectID, transactionName); SqlStatistics statistics = null; try { @@ -273,7 +273,7 @@ public void Rollback(string transactionName) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); if (e != null) { s_diagnosticListener.WriteTransactionRollbackError(operationId, _isolationLevel, _connection, InternalTransaction, e, transactionName); @@ -294,7 +294,7 @@ public void Save(string savePointName) ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} savePointName='{1}'", ObjectID, savePointName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} savePointName='{1}'", ObjectID, savePointName); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -304,7 +304,7 @@ public void Save(string savePointName) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -322,7 +322,7 @@ internal void Zombie() SqlInternalConnection internalConnection = (_connection.InnerConnection as SqlInternalConnection); if (null != internalConnection && !_isFromAPI) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} yukon deferred zombie", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} yukon deferred zombie", ObjectID); } else { diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs index 50f012d574..230509be7f 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -383,25 +383,25 @@ internal void ProcessPendingAck(TdsParserStateObject stateObj) switch (authType) { case SqlAuthenticationMethod.ActiveDirectoryPassword: - SqlClientEventSource.Log.TraceEvent(" Active Directory Password authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Password authentication"); break; case SqlAuthenticationMethod.ActiveDirectoryIntegrated: - SqlClientEventSource.Log.TraceEvent(" Active Directory Integrated authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Integrated authentication"); break; case SqlAuthenticationMethod.ActiveDirectoryInteractive: - SqlClientEventSource.Log.TraceEvent(" Active Directory Interactive authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Interactive authentication"); break; case SqlAuthenticationMethod.ActiveDirectoryServicePrincipal: - SqlClientEventSource.Log.TraceEvent(" Active Directory Service Principal authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Service Principal authentication"); break; case SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow: - SqlClientEventSource.Log.TraceEvent(" Active Directory Device Code Flow authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Device Code Flow authentication"); break; case SqlAuthenticationMethod.SqlPassword: - SqlClientEventSource.Log.TraceEvent(" SQL Password authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" SQL Password authentication"); break; default: - SqlClientEventSource.Log.TraceEvent(" SQL authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" SQL authentication"); break; } } @@ -412,7 +412,7 @@ internal void ProcessPendingAck(TdsParserStateObject stateObj) if (integratedSecurity || authType == SqlAuthenticationMethod.ActiveDirectoryIntegrated) { LoadSSPILibrary(); - SqlClientEventSource.Log.TraceEvent(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication"); } byte[] instanceName = null; @@ -446,7 +446,7 @@ internal void ProcessPendingAck(TdsParserStateObject stateObj) // don't, the memory for the connection object might not be accurate and thus // a bad error could be returned (as it was when it was freed to early for me). _physicalStateObj.Dispose(); - SqlClientEventSource.Log.TraceEvent(" Login failure", "ERR|SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Login failure"); ThrowExceptionAndWarning(_physicalStateObj); Debug.Fail("SNI returned status != success, but no error thrown?"); } @@ -481,19 +481,19 @@ internal void ProcessPendingAck(TdsParserStateObject stateObj) _physicalStateObj.AssignPendingDNSInfo(serverInfo.UserProtocol, FQDNforDNSCahce, ref _connHandler.pendingSQLDNSObject); } - SqlClientEventSource.Log.TraceEvent(" Sending prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending prelogin handshake"); SendPreLoginHandshake(instanceName, encrypt); _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake); _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake); _physicalStateObj.SniContext = SniContext.Snix_PreLogin; - SqlClientEventSource.Log.TraceEvent(" Consuming prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Consuming prelogin handshake"); PreLoginHandshakeStatus status = ConsumePreLoginHandshake(encrypt, trustServerCert, integratedSecurity, out marsCapable, out _connHandler._fedAuthRequired); if (status == PreLoginHandshakeStatus.InstanceFailure) { - SqlClientEventSource.Log.TraceEvent(" Prelogin handshake unsuccessful. Reattempting prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Prelogin handshake unsuccessful. Reattempting prelogin handshake"); _physicalStateObj.Dispose(); // Close previous connection // On Instance failure re-connect and flush SNI named instance cache. @@ -504,14 +504,14 @@ internal void ProcessPendingAck(TdsParserStateObject stateObj) if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); - SqlClientEventSource.Log.TraceEvent(" Login failure", "ERR|SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Login failure"); ThrowExceptionAndWarning(_physicalStateObj); } uint retCode = _physicalStateObj.SniGetConnectionId(ref _connHandler._clientConnectionId); Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); - SqlClientEventSource.Log.TraceEvent(" Sending prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending prelogin handshake"); if (null == _connHandler.pendingSQLDNSObject) { @@ -526,7 +526,7 @@ internal void ProcessPendingAck(TdsParserStateObject stateObj) // one pre-login packet and know we are connecting to Shiloh. if (status == PreLoginHandshakeStatus.InstanceFailure) { - SqlClientEventSource.Log.TraceEvent(" Prelogin handshake unsuccessful. Login failure", "ERR|SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Prelogin handshake unsuccessful. Login failure"); throw SQL.InstanceFailure(); } } @@ -587,7 +587,7 @@ internal void EnableMars() internal TdsParserStateObject CreateSession() { TdsParserStateObject session = TdsParserStateObjectFactory.Singleton.CreateSessionObject(this, _pMarsPhysicalConObj, true); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} created session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} created session {1}", ObjectID, session.ObjectID); return session; } @@ -599,12 +599,12 @@ internal TdsParserStateObject GetSession(object owner) session = _sessionPool.GetSession(owner); Debug.Assert(!session.HasPendingData, "pending data on a pooled MARS session"); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} getting session {1} from pool", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} getting session {1} from pool", ObjectID, session.ObjectID); } else { session = _physicalStateObj; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} getting physical session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} getting physical session {1}", ObjectID, session.ObjectID); } Debug.Assert(session._outputPacketNumber == 1, "The packet number is expected to be 1"); return session; @@ -764,7 +764,7 @@ private void SendPreLoginHandshake(byte[] instanceName, bool encrypt) int actIdSize = GUID_SIZE + sizeof(uint); offset += actIdSize; optionDataSize += actIdSize; - SqlClientEventSource.Log.TraceEvent(" ClientConnectionID {0}, ActivityID {1}", _connHandler._clientConnectionId.ToString(), actId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" ClientConnectionID {0}, ActivityID {1}", _connHandler?._clientConnectionId, actId); break; case (int)PreLoginOptions.FEDAUTHREQUIRED: @@ -1005,7 +1005,7 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(bool encrypt, bool trus // Only 0x00 and 0x01 are accepted values from the server. if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01) { - SqlClientEventSource.Log.TraceEvent(" {0}, " + + SqlClientEventSource.Log.TryTraceEvent(" {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]); } @@ -1046,7 +1046,7 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(bool encrypt, bool trus internal void Deactivate(bool connectionIsDoomed) { // Called when the connection that owns us is deactivated. - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} deactivating", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} deactivating", ObjectID); if (SqlClientEventSource.Log.IsStateDumpEnabled()) { SqlClientEventSource.Log.StateDumpEvent(" {0} {1}", ObjectID, TraceString()); @@ -1206,11 +1206,12 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle // be copied to the end of the error collection so that the user may see all the errors and also the // warnings that occurred. // can be deleted) + //_errorAndWarningsLock lock is implemented inside GetFullErrorAndWarningCollection SqlErrorCollection temp = stateObj.GetFullErrorAndWarningCollection(out breakConnection); if (temp.Count == 0) { - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {0}", ObjectID); } Debug.Assert(temp != null, "TdsParser::ThrowExceptionAndWarning: null errors collection!"); Debug.Assert(temp.Count > 0, "TdsParser::ThrowExceptionAndWarning called with no exceptions or warnings!"); @@ -1252,7 +1253,6 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle } } - // call OnError outside of _ErrorCollectionLock to avoid deadlock if (exception != null) { if (breakConnection) @@ -1317,13 +1317,13 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle internal SqlError ProcessSNIError(TdsParserStateObject stateObj) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(""); try { #if DEBUG // There is an exception here for MARS as its possible that another thread has closed the connection just as we see an error Debug.Assert(SniContext.Undefined != stateObj.DebugOnlyCopyOfSniContext || ((_fMARS) && ((_state == TdsParserState.Closed) || (_state == TdsParserState.Broken))), "SniContext must not be None"); - SqlClientEventSource.Log.SNITraceEvent(" SNIContext must not be None = {0}, _fMARS = {1}, TDS Parser State = {2}", stateObj.DebugOnlyCopyOfSniContext, _fMARS, _state); + SqlClientEventSource.Log.TrySNITraceEvent(" SNIContext must not be None = {0}, _fMARS = {1}, TDS Parser State = {2}", stateObj.DebugOnlyCopyOfSniContext, _fMARS, _state); #endif SNIErrorDetails details = GetSniErrorDetails(); @@ -1335,17 +1335,17 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) { case (int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithMoreThan64IPs: // Connecting with the MultiSubnetFailover connection option to a SQL Server instance configured with more than 64 IP addresses is not supported. - SqlClientEventSource.Log.AdvancedTraceEvent(" Connecting with the MultiSubnetFailover connection option to a SQL Server instance configured with more than 64 IP addresses is not supported."); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Connecting with the MultiSubnetFailover connection option to a SQL Server instance configured with more than 64 IP addresses is not supported."); throw SQL.MultiSubnetFailoverWithMoreThan64IPs(); case (int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithInstanceSpecified: // Connecting to a named SQL Server instance using the MultiSubnetFailover connection option is not supported. - SqlClientEventSource.Log.AdvancedTraceEvent(" Connecting to a named SQL Server instance using the MultiSubnetFailover connection option is not supported."); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Connecting to a named SQL Server instance using the MultiSubnetFailover connection option is not supported."); throw SQL.MultiSubnetFailoverWithInstanceSpecified(); case (int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithNonTcpProtocol: // Connecting to a SQL Server instance using the MultiSubnetFailover connection option is only supported when using the TCP protocol. - SqlClientEventSource.Log.AdvancedTraceEvent(" Connecting to a SQL Server instance using the MultiSubnetFailover connection option is only supported when using the TCP protocol."); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Connecting to a SQL Server instance using the MultiSubnetFailover connection option is only supported when using the TCP protocol."); throw SQL.MultiSubnetFailoverWithNonTcpProtocol(); // continue building SqlError instance } @@ -1353,7 +1353,7 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) // PInvoke code automatically sets the length of the string for us // So no need to look for \0 string errorMessage = details.errorMessage; - SqlClientEventSource.Log.AdvancedTraceEvent("< sc.TdsParser.ProcessSNIError |ERR|ADV > Error message Detail: {0}", details.errorMessage); + SqlClientEventSource.Log.TryAdvancedTraceEvent("< sc.TdsParser.ProcessSNIError |ERR|ADV > Error message Detail: {0}", details.errorMessage); /* Format SNI errors and add Context Information * @@ -1371,12 +1371,12 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) if (TdsParserStateObjectFactory.UseManagedSNI) { Debug.Assert(!string.IsNullOrEmpty(details.errorMessage) || details.sniErrorNumber != 0, "Empty error message received from SNI"); - SqlClientEventSource.Log.AdvancedTraceEvent(" Empty error message received from SNI. Error Message = {0}, SNI Error Number ={1}", details.errorMessage, details.sniErrorNumber); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Empty error message received from SNI. Error Message = {0}, SNI Error Number ={1}", details.errorMessage, details.sniErrorNumber); } else { Debug.Assert(!string.IsNullOrEmpty(details.errorMessage), "Empty error message received from SNI"); - SqlClientEventSource.Log.AdvancedTraceEvent(" Empty error message received from SNI. Error Message = {0}", details.errorMessage); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Empty error message received from SNI. Error Message = {0}", details.errorMessage); } string sniContextEnumName = TdsEnums.GetSniContextEnumName(stateObj.SniContext); @@ -1386,7 +1386,7 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) string providerName = StringsHelper.GetResourceString(providerRid); Debug.Assert(!string.IsNullOrEmpty(providerName), $"invalid providerResourceId '{providerRid}'"); uint win32ErrorCode = details.nativeError; - SqlClientEventSource.Log.AdvancedTraceEvent(" SNI Native Error Code = {0}", win32ErrorCode); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" SNI Native Error Code = {0}", win32ErrorCode); if (details.sniErrorNumber == 0) { // Provider error. The message from provider is preceeded with non-localizable info from SNI @@ -1394,9 +1394,9 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) // int iColon = errorMessage.IndexOf(':'); Debug.Assert(0 <= iColon, "':' character missing in sni errorMessage"); - SqlClientEventSource.Log.AdvancedTraceEvent(" ':' character missing in sni errorMessage. Error Message index of ':' = {0}", iColon); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" ':' character missing in sni errorMessage. Error Message index of ':' = {0}", iColon); Debug.Assert(errorMessage.Length > iColon + 1 && errorMessage[iColon + 1] == ' ', "Expecting a space after the ':' character"); - SqlClientEventSource.Log.AdvancedTraceEvent(" Expecting a space after the ':' character. Error Message Length = {0}", errorMessage.Length); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Expecting a space after the ':' character. Error Message Length = {0}", errorMessage.Length); // extract the message excluding the colon and trailing cr/lf chars if (0 <= iColon) { @@ -1445,7 +1445,7 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) errorMessage = string.Format("{0} (provider: {1}, error: {2} - {3})", sqlContextInfo, providerName, (int)details.sniErrorNumber, errorMessage); - SqlClientEventSource.Log.AdvancedTraceErrorEvent(" SNI Error Message. Native Error = {0}, Line Number ={1}, Function ={2}, Exception ={3}, Server = {4}", + SqlClientEventSource.Log.TryAdvancedTraceErrorEvent(" SNI Error Message. Native Error = {0}, Line Number ={1}, Function ={2}, Exception ={3}, Server = {4}", (int)details.nativeError, (int)details.lineNumber, details.function, details.exception, _server); return new SqlError((int)details.nativeError, 0x00, TdsEnums.FATAL_ERROR_CLASS, @@ -1453,7 +1453,7 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1930,7 +1930,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead Debug.Fail($"unexpected token; token = {token,-2:X2}"); _state = TdsParserState.Broken; _connHandler.BreakConnection(); - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, unexpected TDS token found {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, unexpected TDS token found {0}", ObjectID); throw SQL.ParsingError(); } @@ -2254,7 +2254,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead } case TdsEnums.SQLLOGINACK: { - SqlClientEventSource.Log.TraceEvent(" Received login acknowledgement token", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Received login acknowledgement token"); SqlLoginAck ack; if (!TryProcessLoginAck(stateObj, out ack)) { @@ -3680,11 +3680,11 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, SqlFedAuthInfo tempFedAuthInfo = new SqlFedAuthInfo(); // Skip reading token length, since it has already been read in caller - SqlClientEventSource.Log.AdvancedTraceEvent(" FEDAUTHINFO token stream length = {0}", tokenLen); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" FEDAUTHINFO token stream length = {0}", tokenLen); if (tokenLen < sizeof(uint)) { // the token must at least contain a DWORD indicating the number of info IDs - SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); + SqlClientEventSource.Log.TryTraceEvent(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen); } @@ -3692,22 +3692,27 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, uint optionsCount; if (!stateObj.TryReadUInt32(out optionsCount)) { - SqlClientEventSource.Log.TraceEvent(" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream."); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadCountOfInfoIds); } tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount - SqlClientEventSource.Log.AdvancedTraceEvent(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); + } if (tokenLen > 0) { // read the rest of the token byte[] tokenData = new byte[tokenLen]; int totalRead = 0; bool successfulRead = stateObj.TryReadByteArray(tokenData, tokenLen, out totalRead); - SqlClientEventSource.Log.AdvancedTraceEvent(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); - + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); + } if (!successfulRead || totalRead != tokenLen) { - SqlClientEventSource.Log.TraceEvent(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}", tokenLen, totalRead); + SqlClientEventSource.Log.TryTraceEvent(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}", tokenLen, totalRead); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadTokenStream); } @@ -3728,7 +3733,10 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, byte id = tokenData[currentOptionOffset]; uint dataLen = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 1))); uint dataOffset = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 5))); - SqlClientEventSource.Log.AdvancedTraceEvent(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture)); + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" 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 @@ -3740,7 +3748,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) { - SqlClientEventSource.Log.TraceEvent(" FedAuthInfoDataOffset points to an invalid location.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FedAuthInfoDataOffset points to an invalid location."); throw SQL.ParsingErrorOffset(ParsingErrorState.FedAuthInfoInvalidOffset, unchecked((int)dataOffset)); } @@ -3752,15 +3760,15 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } catch (ArgumentOutOfRangeException e) { - SqlClientEventSource.Log.TraceEvent(" Failed to read FedAuthInfoData.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" Failed to read FedAuthInfoData."); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadData, e); } catch (ArgumentException e) { - SqlClientEventSource.Log.TraceEvent(" FedAuthInfoData is not in unicode format.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FedAuthInfoData is not in unicode format."); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e); } - SqlClientEventSource.Log.AdvancedTraceEvent(" FedAuthInfoData: {0}", data); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" FedAuthInfoData: {0}", data); // store data in tempFedAuthInfo switch ((TdsEnums.FedAuthInfoId)id) @@ -3774,22 +3782,22 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, break; default: - SqlClientEventSource.Log.AdvancedTraceEvent(" Ignoring unknown federated authentication info option: {0}", id); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Ignoring unknown federated authentication info option: {0}", id); break; } } } else { - SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream is not long enough to contain the data it claims to.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FEDAUTHINFO token stream is not long enough to contain the data it claims to."); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForData, tokenLen); } - SqlClientEventSource.Log.TraceEvent(" Processed FEDAUTHINFO token stream: {0}", tempFedAuthInfo.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Processed FEDAUTHINFO token stream: {0}", tempFedAuthInfo); if (string.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || string.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) { // We should be receiving both stsurl and spn - SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream does not contain both STSURL and SPN.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FEDAUTHINFO token stream does not contain both STSURL and SPN."); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDoesNotContainStsurlAndSpn); } @@ -4156,7 +4164,7 @@ internal bool TryProcessReturnValue(int length, TdsParserStateObject stateObj, o // validate the index (ordinal passed) if (index >= cipherTable.Value.Size) { - SqlClientEventSource.Log.TraceEvent(" Incorrect ordinal received {0}, max tab size: {1}", index, cipherTable.Value.Size); + SqlClientEventSource.Log.TryTraceEvent(" Incorrect ordinal received {0}, max tab size: {1}", index, cipherTable.Value.Size); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidOrdinalIntoCipherInfoTable, index); } } @@ -8133,7 +8141,7 @@ internal void TdsLogin(SqlLogin rec, TdsEnums.FeatureExtension requestedFeatures } WriteInt(log7Flags, _physicalStateObj); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, TDS Login7 flags = {1}:", ObjectID, log7Flags); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, TDS Login7 flags = {1}:", ObjectID, log7Flags); WriteInt(0, _physicalStateObj); // ClientTimeZone is not used WriteInt(0, _physicalStateObj); // LCID is unused by server @@ -8253,7 +8261,7 @@ internal void TdsLogin(SqlLogin rec, TdsEnums.FeatureExtension requestedFeatures { if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) { - SqlClientEventSource.Log.TraceEvent(" Sending federated authentication feature request", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending federated authentication feature request"); } WriteInt(feOffset, _physicalStateObj); @@ -8288,7 +8296,7 @@ internal void TdsLogin(SqlLogin rec, TdsEnums.FeatureExtension requestedFeatures } if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) { - SqlClientEventSource.Log.TraceEvent(" Sending federated authentication feature request", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending federated authentication feature request"); Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null."); WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true); } @@ -8348,7 +8356,7 @@ internal void SendFedAuthToken(SqlFedAuthToken fedAuthToken) { Debug.Assert(fedAuthToken != null, "fedAuthToken cannot be null"); Debug.Assert(fedAuthToken.accessToken != null, "fedAuthToken.accessToken cannot be null"); - SqlClientEventSource.Log.TraceEvent(" Sending federated authentication token", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending federated authentication token"); _physicalStateObj._outputMessageType = TdsEnums.MT_FEDAUTH; byte[] accessToken = fedAuthToken.accessToken; @@ -8721,7 +8729,7 @@ internal void PropagateDistributedTransaction(byte[] buffer, int timeout, TdsPar internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) { int old_outputPacketNumber = stateObj._outputPacketNumber; - SqlClientEventSource.Log.TraceEvent(" Exception caught on ExecuteXXX: '{0}'", e.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Exception caught on ExecuteXXX: '{0}'", e); if (stateObj.HasOpenResult) { // Need to decrement openResultCount if operation failed. @@ -8752,7 +8760,7 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) // Reset the ThreadHasParserLock value in case our caller expects it to be set\not set _connHandler.ThreadHasParserLockForClose = originalThreadHasParserLock; } - SqlClientEventSource.Log.TraceEvent(" Exception rethrown.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" Exception rethrown."); } } @@ -8810,7 +8818,7 @@ internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationReques if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); } stateObj.SniContext = SniContext.Snix_Execute; @@ -8939,7 +8947,7 @@ internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationReques if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); } stateObj.SniContext = SniContext.Snix_Execute; @@ -9764,7 +9772,7 @@ private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefa if (advancedTraceIsOn) { var sendDefaultValue = sendDefault ? 1 : 0; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); } // @@ -10804,7 +10812,7 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio Debug.Assert(ushort.MaxValue >= service.Length, "Service length is out of range"); Debug.Assert(-1 <= timeout, "Timeout"); - SqlClientEventSource.Log.NotificationTraceEvent(" NotificationRequest: userData: '{0}', options: '{1}', timeout: '{2}'", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); + SqlClientEventSource.Log.TryNotificationTraceEvent(" NotificationRequest: userData: '{0}', options: '{1}', timeout: '{2}'", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj); // Query notifications Type WriteShort(callbackId.Length * 2, stateObj); // Length in bytes @@ -10829,7 +10837,7 @@ private void WriteTraceHeaderData(TdsParserStateObject stateObj) stateObj.WriteByteArray(actId.Id.ToByteArray(), GUID_SIZE, 0); // Id (Guid) WriteUnsignedInt(actId.Sequence, stateObj); // sequence number - SqlClientEventSource.Log.TraceEvent(" ActivityID {0}", actId); + SqlClientEventSource.Log.TryTraceEvent(" ActivityID {0}", actId); } private void WriteRPCBatchHeaders(TdsParserStateObject stateObj, SqlNotificationRequest notificationRequest) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index 7de3dad2b5..f89086384b 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -36,7 +36,7 @@ internal TdsParserSessionPool(TdsParser parser) _cache = new List(); _freeStateObjects = new TdsParserStateObject[MaxInactiveCount]; _freeStateObjectCount = 0; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} created session pool for parser {1}", ObjectID, parser.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} created session pool for parser {1}", ObjectID, parser.ObjectID); } private bool IsDisposed @@ -60,7 +60,7 @@ internal void Deactivate() // When being deactivated, we check all the sessions in the // cache to make sure they're cleaned up and then we dispose of // sessions that are past what we want to keep around. - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} deactivating cachedCount={1}", ObjectID, _cachedCount); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} deactivating cachedCount={1}", ObjectID, _cachedCount); try { lock (_cache) @@ -79,7 +79,7 @@ internal void Deactivate() if (session.IsOrphaned) { // TODO: consider adding a performance counter for the number of sessions we reclaim - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} reclaiming session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} reclaiming session {1}", ObjectID, session.ObjectID); PutSession(session); } } @@ -90,13 +90,13 @@ internal void Deactivate() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } internal void Dispose() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} disposing cachedCount={1}", ObjectID, _cachedCount); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} disposing cachedCount={1}", ObjectID, _cachedCount); lock (_cache) { // Dispose free sessions @@ -154,7 +154,7 @@ internal TdsParserStateObject GetSession(object owner) { // No free objects, create a new one session = _parser.CreateSession(); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} adding session {1} to pool", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} adding session {1} to pool", ObjectID, session.ObjectID); _cache.Add(session); _cachedCount = _cache.Count; @@ -163,7 +163,7 @@ internal TdsParserStateObject GetSession(object owner) session.Activate(owner); } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} using session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} using session {1}", ObjectID, session.ObjectID); return session; } @@ -185,7 +185,7 @@ internal void PutSession(TdsParserStateObject session) else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount)) { // Session is good to re-use and our cache has space - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} keeping session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} keeping session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); Debug.Assert(!session.HasPendingData, "pending data on a pooled session?"); _freeStateObjects[_freeStateObjectCount] = session; @@ -194,7 +194,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 - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} disposing session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index 78bdda5c7c..a5e84c2a6a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -542,8 +542,8 @@ internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount) return false; } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount); - SqlClientEventSource.Log.AdvancedTraceBinEvent(" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount); + SqlClientEventSource.Log.TryAdvancedTraceBinEvent(" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); return true; } @@ -873,7 +873,7 @@ internal void DecrementOpenResultCount() internal int DecrementPendingCallbacks(bool release) { int remaining = Interlocked.Decrement(ref _pendingCallbacks); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); FreeGcHandle(remaining, release); // NOTE: TdsParserSessionPool may call DecrementPendingCallbacks on a TdsParserStateObject which is already disposed // This is not dangerous (since the stateObj is no longer in use), but we need to add a workaround in the assert for it @@ -926,7 +926,7 @@ internal int IncrementAndObtainOpenResultCount(SqlInternalTransaction transactio internal int IncrementPendingCallbacks() { int remaining = Interlocked.Increment(ref _pendingCallbacks); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}"); return remaining; } @@ -2534,7 +2534,7 @@ internal bool IsConnectionAlive(bool throwOnException) if ((error != TdsEnums.SNI_SUCCESS) && (error != TdsEnums.SNI_WAIT_TIMEOUT)) { // Connection is dead - SqlClientEventSource.Log.TraceEvent(" received error {0} on idle connection", (int)error); + SqlClientEventSource.Log.TryTraceEvent(" received error {0} on idle connection", (int)error); isAlive = false; if (throwOnException) { @@ -2923,7 +2923,7 @@ public void WriteAsyncCallback(IntPtr key, PacketHandle packet, uint sniError) { if (sniError != TdsEnums.SNI_SUCCESS) { - SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)sniError); + SqlClientEventSource.Log.TryTraceEvent(" write async returned error code {0}", (int)sniError); try { AddError(_parser.ProcessSNIError(this)); @@ -3413,7 +3413,7 @@ private Task SNIWritePacket(PacketHandle packet, out uint sniError, bool canAccu if (error != TdsEnums.SNI_SUCCESS) { - SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)error); + SqlClientEventSource.Log.TryTraceEvent(" write async returned error code {0}", (int)error); AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(); } @@ -3448,7 +3448,7 @@ private Task SNIWritePacket(PacketHandle packet, out uint sniError, bool canAccu } else { - SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)sniError); + SqlClientEventSource.Log.TryTraceEvent(" write async returned error code {0}", (int)sniError); AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(callerHasConnectionLock); } @@ -3487,35 +3487,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; + } - uint sniError; - _parser._asyncWrite = false; // stop async write - SNIWritePacket(attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false); - SqlClientEventSource.Log.TraceEvent(" Send Attention ASync.", "Info"); - } - finally - { - if (releaseLock) + uint sniError; + _parser._asyncWrite = false; // stop async write + SNIWritePacket(attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false); + SqlClientEventSource.Log.TryTraceEvent(" Send Attention ASync."); + } + finally { - _parser.Connection.ThreadHasParserLockForClose = false; - _parser.Connection._parserLock.Release(); + if (releaseLock) + { + _parser.Connection.ThreadHasParserLockForClose = false; + _parser.Connection._parserLock.Release(); + } } - } #if DEBUG } #endif @@ -3528,8 +3528,8 @@ internal void SendAttention(bool mustTakeWriteLock = false) _attentionSending = false; } - SqlClientEventSource.Log.AdvancedTraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); - SqlClientEventSource.Log.TraceEvent(" Attention sent to the server.", "Info"); + SqlClientEventSource.Log.TryAdvancedTraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); + SqlClientEventSource.Log.TryTraceEvent(" Attention sent to the server."); AssertValidState(); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs index 193babd231..7d5b995776 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs @@ -39,13 +39,13 @@ public TdsParserStateObject CreateTdsParserStateObject(TdsParser parser) { if (UseManagedSNI) { - SqlClientEventSource.Log.TraceEvent(" Found AppContext switch '{0}' enabled, managed networking implementation will be used." + SqlClientEventSource.Log.TryTraceEvent(" Found AppContext switch '{0}' enabled, managed networking implementation will be used." , UseManagedNetworkingOnWindows); return new TdsParserStateObjectManaged(parser); } else { - SqlClientEventSource.Log.TraceEvent(" AppContext switch '{0}' not enabled, native networking implementation will be used." + SqlClientEventSource.Log.TryTraceEvent(" AppContext switch '{0}' not enabled, native networking implementation will be used." , UseManagedNetworkingOnWindows); return new TdsParserStateObjectNative(parser); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlTypes/SqlFileStream.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlTypes/SqlFileStream.Windows.cs index fec2f1f768..509a2e7700 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlTypes/SqlFileStream.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlTypes/SqlFileStream.Windows.cs @@ -61,7 +61,7 @@ public sealed partial class SqlFileStream : System.IO.Stream /// public SqlFileStream(string path, byte[] transactionContext, FileAccess access, FileOptions options, long allocationSize) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} access={1} options={2} path='{3}'", ObjectID, (int)access, (int)options, path); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} access={1} options={2} path='{3}'", ObjectID, (int)access, (int)options, path); try { //----------------------------------------------------------------- @@ -86,7 +86,7 @@ public SqlFileStream(string path, byte[] transactionContext, FileAccess access, } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -599,7 +599,7 @@ long allocationSize eaBuffer: b, eaLength: (uint)fullSize); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, desiredAccess=0x{1}, allocationSize={2}, " + + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, desiredAccess=0x{1}, allocationSize={2}, " + "fileAttributes=0x{3}, shareAccess=0x{4}, dwCreateDisposition=0x{5}, createOptions=0x{ dwCreateOptions}", ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)nShareAccess, dwCreateDisposition); retval = status; 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 659c4f31be..e52a60e1e0 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -101,7 +101,7 @@ static private void TraceException(string trace, Exception e) Debug.Assert(null != e, "TraceException: null Exception"); if (null != e) { - SqlClientEventSource.Log.TraceEvent(trace, e); + SqlClientEventSource.Log.TryTraceEvent(trace, e); } } 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 794332c1fa..c51f4f2730 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs @@ -470,7 +470,7 @@ static private string[] NoDuplicateUnion(string[] a, string[] b) private static string[] ParseRestrictions(string restrictions, Hashtable synonyms) { #if DEBUG - SqlClientEventSource.Log.AdvancedTraceEvent(" Restrictions='{0}'", restrictions); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Restrictions='{0}'", restrictions); #endif List restrictionValues = new List(); StringBuilder buffer = new StringBuilder(restrictions.Length); @@ -486,7 +486,7 @@ private static string[] ParseRestrictions(string restrictions, Hashtable synonym if (!ADP.IsEmpty(keyname)) { #if DEBUG - SqlClientEventSource.Log.AdvancedTraceEvent(" KeyName='{0}'", keyname); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" 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 4274ad3eba..07431834fb 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 @@ -641,7 +641,7 @@ private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hash } else { - SqlClientEventSource.Log.AdvancedTraceEvent(" KeyName='{0}'", keyname); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" KeyName='{0}'", keyname); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs index 4170e38943..7f02867eed 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -28,10 +28,10 @@ internal static class ExceptionBuilder Debug.Assert(null != e, "TraceException: null Exception"); if (null != e) { - SqlClientEventSource.Log.AdvancedTraceEvent(trace, e.Message); + SqlClientEventSource.Log.TryAdvancedTraceEvent(trace, e.Message); try { - SqlClientEventSource.Log.AdvancedTraceEvent(" Environment StackTrace = '{0}'", Environment.StackTrace); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Environment StackTrace = '{0}'", Environment.StackTrace); } catch (System.Security.SecurityException) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index fa5eddef35..50383d27a7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -65,7 +65,7 @@ internal int ObjectID public void ClearAllPools() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent("", "API"); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(""); try { Dictionary connectionPoolGroups = _connectionPoolGroups; @@ -80,14 +80,14 @@ public void ClearAllPools() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } public void ClearPool(DbConnection connection) { ADP.CheckArgumentNull(connection, "connection"); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", GetObjectId(connection)); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", GetObjectId(connection)); try { DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); @@ -98,7 +98,7 @@ public void ClearPool(DbConnection connection) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -106,7 +106,7 @@ 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"); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" connectionString"); try { @@ -119,7 +119,7 @@ public void ClearPool(DbConnectionPoolKey key) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -151,7 +151,7 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakeNonPooledObject(owningConnection, PerformanceCounters); } - SqlClientEventSource.Log.TraceEvent(" {0}, Non-pooled database connection created.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Non-pooled database connection created.", ObjectID); return newConnection; } @@ -167,7 +167,7 @@ internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbCo PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakePooledConnection(pool); } - SqlClientEventSource.Log.TraceEvent(" {0}, Pooled database connection created.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Pooled database connection created.", ObjectID); return newConnection; } @@ -362,7 +362,7 @@ 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); + SqlClientEventSource.Log.TryTraceEvent(" {0}, GetConnection failed because a pool timeout occurred.", ObjectID); // If GetConnection failed while the pool is running, the pool timeout occurred. throw ADP.PooledOpenTimeout(); @@ -381,7 +381,7 @@ 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); + SqlClientEventSource.Log.TryTraceEvent(" {0}, GetConnection failed because a pool timeout occurred and all retries were exhausted.", ObjectID); // exhausted all retries or timed out - give up throw ADP.PooledOpenTimeout(); @@ -408,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)) { - SqlClientEventSource.Log.TraceEvent(" {0}, DisabledPoolGroup={1}", ObjectID, connectionPoolGroup.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, DisabledPoolGroup={1}", ObjectID, connectionPoolGroup.ObjectID); // reusing existing pool option in case user originally used SetConnectionPoolOptions DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions; @@ -539,7 +539,7 @@ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPo private void PruneConnectionPoolGroups(object state) { // when debugging this method, expect multiple threads at the same time - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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 @@ -559,7 +559,7 @@ private void PruneConnectionPoolGroups(object state) if (0 == pool.Count) { _poolsToRelease.Remove(pool); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, ReleasePool={1}", ObjectID, pool.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, ReleasePool={1}", ObjectID, pool.ObjectID); PerformanceCounters.NumberOfInactiveConnectionPools.Decrement(); } } @@ -584,7 +584,7 @@ private void PruneConnectionPoolGroups(object state) if (0 == poolsLeft) { _poolGroupsToRelease.Remove(poolGroup); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, ReleasePoolGroup={1}", ObjectID, poolGroup.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, ReleasePoolGroup={1}", ObjectID, poolGroup.ObjectID); PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Decrement(); } } @@ -650,7 +650,7 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { Debug.Assert(null != poolGroup, "null poolGroup?"); - SqlClientEventSource.Log.TraceEvent(" {0}, poolGroup={1}", ObjectID, poolGroup.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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 25ef54f6f7..3256c9c39a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -163,7 +163,7 @@ protected internal SysTx.Transaction EnlistedTransaction if (null != value) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Enlisting.", ObjectID, value.GetHashCode()); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Enlisting.", ObjectID, value.GetHashCode()); TransactionOutcomeEnlist(value); } } @@ -390,7 +390,7 @@ internal void ActivateConnection(SysTx.Transaction transaction) { // Internal method called from the connection pooler so we don't expose // the Activate method publicly. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Activating", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Activating", ObjectID); #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); Debug.Assert(1 == activateCount, "activated multiple times?"); @@ -461,7 +461,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac //////////////////////////////////////////////////////////////// Debug.Assert(null != owningObject, "null owningObject"); Debug.Assert(null != connectionFactory, "null connectionFactory"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0} Closing.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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 @@ -566,7 +566,7 @@ internal void DeactivateConnection() { // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Deactivating", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Deactivating", ObjectID); #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); Debug.Assert(0 == activateCount, "activated multiple times?"); @@ -600,7 +600,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. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Delegated Transaction Completed.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Delegated Transaction Completed.", ObjectID); if (1 == _pooledCount) { @@ -663,7 +663,7 @@ public virtual void Dispose() protected internal void DoNotPoolThisConnection() { _cannotBePooled = true; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Marking pooled object as non-poolable so it will be disposed", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Marking pooled object as non-poolable so it will be disposed", ObjectID); } /// Ensure that this connection cannot be put back into the pool. @@ -671,7 +671,7 @@ protected internal void DoNotPoolThisConnection() protected internal void DoomThisConnection() { _connectionIsDoomed = true; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Dooming", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Dooming", ObjectID); } // Reset connection doomed status so it can be re-connected and pooled. @@ -805,7 +805,7 @@ internal void PrePush(object expectedOwner) } //DbConnection x = (expectedOwner as DbConnection); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Preparing to push into pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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% @@ -837,7 +837,7 @@ internal void PostPop(object newOwner) _pooledCount--; //DbConnection x = (newOwner as DbConnection); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Preparing to pop from pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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) @@ -894,7 +894,7 @@ internal void DetachCurrentTransactionIfEnded() // Detach transaction from connection. internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction Completed. (pooledCount={1})", ObjectID, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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 @@ -935,7 +935,7 @@ internal void CleanupConnectionOnTransactionCompletion(SysTx.Transaction transac void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) { SysTx.Transaction transaction = e.Transaction; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); CleanupTransactionOnCompletion(transaction); CleanupConnectionOnTransactionCompletion(transaction); @@ -952,7 +952,7 @@ private void TransactionOutcomeEnlist(SysTx.Transaction transaction) internal void SetInStasis() { _isInStasis = true; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID); PerformanceCounters.NumberOfStasisConnections.Increment(); } @@ -960,11 +960,11 @@ private void TerminateStasis(bool returningToPool) { if (returningToPool) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed. Returning to general pool.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed. Returning to general pool.", ObjectID); } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed/leaked. Disposing.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed/leaked. Disposing.", ObjectID); } PerformanceCounters.NumberOfStasisConnections.Decrement(); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index 214c080622..b69d3bb122 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 @@ -81,7 +81,7 @@ internal TransactedConnectionPool(DbConnectionPool pool) Debug.Assert(null != pool, "null pool?"); _pool = pool; _transactedCxns = new Dictionary(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Constructed for connection pool {1}", ObjectID, _pool.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Constructed for connection pool {1}", ObjectID, _pool.ObjectID); } internal int ObjectID @@ -140,7 +140,7 @@ internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction) if (null != transactedObject) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } return transactedObject; } @@ -167,7 +167,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); connections.Add(transactedObject); } } @@ -202,13 +202,13 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); connections.Add(transactedObject); } } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Adding List to transacted pool.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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); @@ -236,7 +236,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt } } } - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Added.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Added.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } Pool.PerformanceCounters.NumberOfFreeConnections.Increment(); @@ -245,7 +245,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionInternal transactedObject) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); TransactedConnectionList connections; int entry = -1; @@ -279,7 +279,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern // safely remove the list from the transacted pool. if (0 >= connections.Count) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Removing List from transacted pool.", ObjectID, transaction.GetHashCode()); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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 @@ -296,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." ); - 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); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transacted pool not yet created prior to transaction completing. Connection may be leaked.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } } @@ -523,7 +523,7 @@ protected override bool ReleaseHandle() _poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback _state = State.Running; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Constructed.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Constructed.", ObjectID); //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls // StartBackgroundCallbacks after pool is actually in the collection @@ -671,7 +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. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}", ObjectID); // Destroy free objects that put us above MinPoolSize from old stack. while (Count > MinPoolSize) @@ -745,7 +745,7 @@ private void CleanupCallback(Object state) break; Debug.Assert(obj != null, "null connection is not expected"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, ChangeStacks={1}", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, ChangeStacks={1}", ObjectID, obj.ObjectID); Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); Debug.Assert(obj.CanBePooled, "pooled object is not poolable"); @@ -760,7 +760,7 @@ private void CleanupCallback(Object state) internal void Clear() { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Clearing.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Clearing.", ObjectID); DbConnectionInternal obj; // First, quickly doom everything. @@ -796,7 +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(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Cleared.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Cleared.", ObjectID); } private Timer CreateCleanupTimer() @@ -886,7 +886,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio } } } - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Added to pool.", ObjectID, newObj != null ? newObj?.ObjectID.ToString() ?? "null" : "null"); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Added to pool.", ObjectID, newObj?.ObjectID); // Reset the error wait: _errorWait = ERROR_WAIT_DEFAULT; @@ -947,7 +947,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio private void DeactivateObject(DbConnectionInternal obj) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Deactivating.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Deactivating.", ObjectID, obj.ObjectID); obj.DeactivateConnection(); // we presume this operation is safe outside of a lock... bool returnToGeneralPool = false; @@ -1087,11 +1087,11 @@ internal void DestroyObject(DbConnectionInternal obj) // again. if (obj.IsTxRootWaitingForTxEnd) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Has Delegated Transaction, waiting to Dispose.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Has Delegated Transaction, waiting to Dispose.", ObjectID, obj.ObjectID); } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Removing from pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Removing from pool.", ObjectID, obj.ObjectID); bool removed = false; lock (_objectList) { @@ -1102,18 +1102,18 @@ internal void DestroyObject(DbConnectionInternal obj) if (removed) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Removed from pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Removed from pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfPooledConnections.Decrement(); } obj.Dispose(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Disposed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Disposed.", ObjectID, obj.ObjectID); PerformanceCounters.HardDisconnectsPerSecond.Increment(); } } private void ErrorCallback(Object state) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Resetting Error handling.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Resetting Error handling.", ObjectID); _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); @@ -1287,7 +1287,7 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource {0}, DbConnectionInternal State != Running.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, DbConnectionInternal State != Running.", ObjectID); connection = null; return true; } @@ -1332,7 +1332,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj SysTx.Transaction transaction = null; PerformanceCounters.SoftConnectsPerSecond.Increment(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Getting connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Getting connection.", ObjectID); // If automatic transaction enlistment is required, then we try to // get the connection from the transacted connection pool first. @@ -1385,7 +1385,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj switch (waitResult) { case WAIT_TIMEOUT: - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Wait timed out.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Wait timed out.", ObjectID); Interlocked.Decrement(ref _waitCount); connection = null; return false; @@ -1393,12 +1393,12 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case ERROR_HANDLE: // Throw the error that PoolCreateRequest stashed. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Errors are set.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Errors are set.", ObjectID); Interlocked.Decrement(ref _waitCount); throw TryCloneCachedException(); case CREATION_HANDLE: - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Creating new connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Creating new connection.", ObjectID); try { obj = UserCreateRequest(owningObject, userOptions); @@ -1451,7 +1451,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj if ((obj != null) && (!obj.IsConnectionAlive())) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); obj = null; // Setting to null in case creating a new object fails @@ -1462,7 +1462,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj RuntimeHelpers.PrepareConstrainedRegions(); try { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Creating new connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Creating new connection.", ObjectID); obj = UserCreateRequest(owningObject, userOptions); } finally @@ -1473,7 +1473,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj else { // Timeout waiting for creation semaphore - return null - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Wait timed out.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Wait timed out.", ObjectID); connection = null; return false; } @@ -1483,28 +1483,28 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case WAIT_FAILED: Debug.Assert(waitForMultipleObjectsExHR != 0, "WaitForMultipleObjectsEx failed but waitForMultipleObjectsExHR remained 0"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Wait failed.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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): - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Semaphore handle abandonded.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Semaphore handle abandonded.", ObjectID); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(SEMAPHORE_HANDLE, _waitHandles.PoolSemaphore); case (WAIT_ABANDONED + ERROR_HANDLE): - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Error handle abandonded.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Error handle abandonded.", ObjectID); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(ERROR_HANDLE, _waitHandles.ErrorEvent); case (WAIT_ABANDONED + CREATION_HANDLE): - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Creation handle abandoned.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Creation handle abandoned.", ObjectID); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(CREATION_HANDLE, _waitHandles.CreationSemaphore); default: - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, WaitForMultipleObjects={1}", ObjectID, waitResult); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, WaitForMultipleObjects={1}", ObjectID, waitResult); Interlocked.Decrement(ref _waitCount); throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult); } @@ -1576,7 +1576,7 @@ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal o internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) { PerformanceCounters.SoftConnectsPerSecond.Increment(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, replacing connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, replacing connection.", ObjectID); DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); if (newConnection != null) @@ -1618,7 +1618,7 @@ private DbConnectionInternal GetFromGeneralPool() if (null != obj) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Popped from general pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Popped from general pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfFreeConnections.Decrement(); } return (obj); @@ -1635,7 +1635,7 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac if (null != obj) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Popped from transacted pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Popped from transacted pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfFreeConnections.Decrement(); if (obj.IsTransactionRoot) @@ -1646,14 +1646,14 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac } catch { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); throw; } } else if (!obj.IsConnectionAlive()) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); obj = null; } @@ -1668,7 +1668,7 @@ private void PoolCreateRequest(object state) { // called by pooler to ensure pool requests are currently being satisfied - // creation mutex has not been obtained - long scopeID = SqlClientEventSource.Log.PoolerScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryPoolerScopeEnterEvent(" {0}", ObjectID); try { if (State.Running == _state) @@ -1753,7 +1753,7 @@ private void PoolCreateRequest(object state) else { // trace waitResult and ignore the failure - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, PoolCreateRequest called WaitForSingleObject failed {1}", ObjectID, waitResult); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, PoolCreateRequest called WaitForSingleObject failed {1}", ObjectID, waitResult); } } catch (Exception e) @@ -1767,7 +1767,7 @@ private void PoolCreateRequest(object state) // Now that CreateObject can throw, we need to catch the exception and discard it. // There is no further action we can take beyond tracing. The error will be // thrown to the user the next time they request a connection. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, PoolCreateRequest called CreateConnection which threw an exception: {1}", ObjectID, e); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, PoolCreateRequest called CreateConnection which threw an exception: {1}", ObjectID, e); } finally { @@ -1787,7 +1787,7 @@ private void PoolCreateRequest(object state) } finally { - SqlClientEventSource.Log.PoolerScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryPoolerScopeLeaveEvent(scopeID); } } @@ -1800,7 +1800,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"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Pushing to general pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Pushing to general pool.", ObjectID, obj.ObjectID); _stackNew.Push(obj); _waitHandles.PoolSemaphore.Release(1); @@ -1849,7 +1849,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. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Transaction has ended.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Transaction has ended.", ObjectID, obj.ObjectID); if (_state == State.Running && obj.CanBePooled) { @@ -1874,7 +1874,7 @@ private void QueuePoolCreateRequest() private bool ReclaimEmancipatedObjects() { bool emancipatedObjectFound = false; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}", ObjectID); List reclaimedObjects = new List(); int count; @@ -1926,7 +1926,7 @@ private bool ReclaimEmancipatedObjects() for (int i = 0; i < count; ++i) { DbConnectionInternal obj = reclaimedObjects[i]; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Reclaiming.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Reclaiming.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfReclaimedConnections.Increment(); emancipatedObjectFound = true; @@ -1939,7 +1939,7 @@ private bool ReclaimEmancipatedObjects() internal void Startup() { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, CleanupWait={1}", ObjectID, _cleanupWait); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, CleanupWait={1}", ObjectID, _cleanupWait); _cleanupTimer = CreateCleanupTimer(); if (NeedToReplenish) @@ -1950,7 +1950,7 @@ internal void Startup() internal void Shutdown() { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}", ObjectID); _state = State.ShuttingDown; // deactivate timer callbacks @@ -1972,7 +1972,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern Debug.Assert(null != transactedObject, "null transactedObject?"); // Note: connection may still be associated with transaction due to Explicit Unbinding requirement. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {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 8cd608d127..6aa0847667 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -273,7 +273,7 @@ private bool MarkPoolGroupAsActive() if (PoolGroupStateIdle == _state) { _state = PoolGroupStateActive; - SqlClientEventSource.Log.TraceEvent(" {0}, Active", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Active", ObjectID); } return (PoolGroupStateActive == _state); } @@ -335,12 +335,12 @@ internal bool Prune() if (PoolGroupStateActive == _state) { _state = PoolGroupStateIdle; - SqlClientEventSource.Log.TraceEvent(" {0}, Idle", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Idle", ObjectID); } else if (PoolGroupStateIdle == _state) { _state = PoolGroupStateDisabled; - SqlClientEventSource.Log.TraceEvent(" {0}, Disabled", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Disabled", ObjectID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs index 618a6ea183..ad0e88a1d2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs @@ -87,7 +87,7 @@ internal DbConnectionOptions ConnectionOptions private string ConnectionString_Get() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions connectionOptions = UserConnectionOptions; return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); @@ -131,8 +131,10 @@ private void ConnectionString_Set(DbConnectionPoolKey key) throw ADP.OpenConnectionPropertySet(ADP.ConnectionString, connectionInternal.State); } - string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); - SqlClientEventSource.Log.TraceEvent(" {0}, '{1}'", ObjectID, cstr); + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + SqlClientEventSource.Log.TraceEvent(" {0}, '{1}'", ObjectID, connectionOptions.UsersConnectionStringForTrace()); + } } internal DbConnectionInternal InnerConnection @@ -182,11 +184,11 @@ internal void Abort(Exception e) // will end the reliable try... if (e is OutOfMemoryException) { - SqlClientEventSource.Log.TraceEvent(" {0}, Aborting operation due to asynchronous exception: {'OutOfMemory'}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Aborting operation due to asynchronous exception: {'OutOfMemory'}", ObjectID); } else { - SqlClientEventSource.Log.TraceEvent(" {0}, Aborting operation due to asynchronous exception: {1}", ObjectID, e.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Aborting operation due to asynchronous exception: {1}", ObjectID, e); } } @@ -199,7 +201,7 @@ internal void AddWeakReference(object value, int tag) override protected DbCommand CreateDbCommand() { DbCommand command = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; @@ -208,7 +210,7 @@ override protected DbCommand CreateDbCommand() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } return command; } @@ -245,7 +247,7 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)); permissionSet.Demand(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection enlisting in a transaction.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection enlisting in a transaction.", ObjectID); SysTx.Transaction indigoTransaction = null; if (null != transaction) @@ -270,7 +272,7 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans override public void EnlistTransaction(SysTx.Transaction transaction) { SqlConnection.ExecutePermission.Demand(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection enlisting in a transaction.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection enlisting in a transaction.", ObjectID); // If we're currently enlisted in a transaction and we were called // on the EnlistTransaction method (Whidbey) we're not allowed to diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs index 6d29848ed3..c18fdda558 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) { - SqlClientEventSource.Log.TraceEvent(" LocalDB - handle obtained"); + SqlClientEventSource.Log.TryTraceEvent(" LocalDB - handle obtained"); } else { @@ -117,7 +117,7 @@ static LocalDBCreateInstanceDelegate LocalDBCreateInstance if (functionAddr == IntPtr.Zero) { int hResult = Marshal.GetLastWin32Error(); - SqlClientEventSource.Log.TraceEvent(" GetProcAddress for LocalDBCreateInstance error 0x{0}", hResult); + SqlClientEventSource.Log.TryTraceEvent(" 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 impossible to get this error. int hResult = Marshal.GetLastWin32Error(); - SqlClientEventSource.Log.TraceEvent(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); + SqlClientEventSource.Log.TryTraceEvent(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); } s_localDBFormatMessage = (LocalDBFormatMessageDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBFormatMessageDelegate)); @@ -315,7 +315,7 @@ internal static void CreateLocalDBInstance(string instance) } else { - SqlClientEventSource.Log.TraceEvent(" No system.data.localdb section found in configuration"); + SqlClientEventSource.Log.TryTraceEvent(" No system.data.localdb section found in configuration"); } s_configurableInstances = tempConfigurableInstances; } @@ -342,14 +342,14 @@ internal static void CreateLocalDBInstance(string instance) // LocalDBCreateInstance is thread- and cross-process safe method, it is OK to call from two threads simultaneously int hr = LocalDBCreateInstance(instanceInfo.version, instance, flags: 0); - SqlClientEventSource.Log.TraceEvent(" Starting creation of instance {0} version {1}", instance, instanceInfo.version); + SqlClientEventSource.Log.TryTraceEvent(" Starting creation of instance {0} version {1}", instance, instanceInfo.version); if (hr < 0) { throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_CreateFailed"), instance: instance, localDbError: hr); } - SqlClientEventSource.Log.TraceEvent(" Finished creation of instance {0}", instance); + SqlClientEventSource.Log.TryTraceEvent(" 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 3cc4328ce8..663d042127 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs @@ -267,7 +267,7 @@ internal override void MessagePosted(int number, byte state, byte errorClass, st { if (null == _parent) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, number={1} state={2} errorClass={3} server='{4}' message='{5}' procedure='{6}' linenumber={7}.", 0, number, state, errorClass, server ?? "", message ?? "", procedure ?? "", lineNumber); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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/Server/SmiMetaData.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiMetaData.cs index 22d8d1c469..1c4312d9b1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiMetaData.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiMetaData.cs @@ -830,7 +830,7 @@ virtual internal string TraceString(int indent) } } - return String.Format(CultureInfo.InvariantCulture, "\n\t" + return string.Format(CultureInfo.InvariantCulture, "\n\t" + "{0} SqlDbType={1:g}\n\t" + "{0} MaxLength={2:d}\n\t" + "{0} Precision={3:d}\n\t" 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 af9a603898..06bdc0bb6b 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 @@ -38,7 +38,7 @@ static SqlAuthenticationProviderManager() catch (ConfigurationErrorsException e) { // Don't throw an error for invalid config files - SqlClientEventSource.Log.TraceEvent("Unable to load custom SqlAuthenticationProviders or SqlClientAuthenticationProviders. ConfigurationManager failed to load due to configuration errors: {0}", e); + SqlClientEventSource.Log.TryTraceEvent("Unable to load custom SqlAuthenticationProviders or SqlClientAuthenticationProviders. ConfigurationManager failed to load due to configuration errors: {0}", e); } Instance = new SqlAuthenticationProviderManager(configurationSection); Instance.SetProvider(SqlAuthenticationMethod.ActiveDirectoryIntegrated, activeDirectoryAuthProvider); 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 37a4ff7c30..fdfbc1a71b 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 @@ -632,8 +632,8 @@ private string CreateInitialQuery() private Task CreateAndExecuteInitialQueryAsync(out BulkCopySimpleResultSet result) { string TDSCommand = CreateInitialQuery(); - SqlClientEventSource.Log.TraceEvent(" Initial Query: '{0}'", TDSCommand); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryTraceEvent(" Initial Query: '{0}'", TDSCommand); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); if (executeTask == null) @@ -956,7 +956,7 @@ private string TryGetOrderHintText(HashSet destColumnNames) // private Task SubmitUpdateBulkCommand(string TDSCommand) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); if (executeTask == null) @@ -2586,7 +2586,7 @@ private void CheckAndRaiseNotification() // it's also the user's chance to cause an exception ... _stateObj.BcpLock = true; abortOperation = FireRowsCopiedEvent(_rowsCopied); - SqlClientEventSource.Log.TraceEvent("", "INFO"); + SqlClientEventSource.Log.TryTraceEvent(""); // just in case some pathological person closes the target connection ... if (ConnectionState.Open != _connection.State) @@ -2975,18 +2975,18 @@ private void CopyBatchesAsyncContinuedOnError(bool cleanupParser) { tdsReliabilitySection.Start(); #endif //DEBUG - if ((cleanupParser) && (_parser != null) && (_stateObj != null)) - { - _parser._asyncWrite = false; - Task task = _parser.WriteBulkCopyDone(_stateObj); - Debug.Assert(task == null, "Write should not pend when error occurs"); - RunParser(); - } + if ((cleanupParser) && (_parser != null) && (_stateObj != null)) + { + _parser._asyncWrite = false; + Task task = _parser.WriteBulkCopyDone(_stateObj); + Debug.Assert(task == null, "Write should not pend when error occurs"); + RunParser(); + } - if (_stateObj != null) - { - CleanUpStateObject(); - } + if (_stateObj != null) + { + CleanUpStateObject(); + } #if DEBUG } finally 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 26db371812..d0a9d96be7 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 @@ -343,7 +343,7 @@ internal CommandEventSink(SqlCommand command) : base() internal override void StatementCompleted(int rowsAffected) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, rowsAffected={1}.", _command.ObjectID, rowsAffected); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, rowsAffected={1}.", _command.ObjectID, rowsAffected); _command.InternalRecordsAffected = rowsAffected; // UNDONE: need to fire events back to user code, but this may be called @@ -355,12 +355,12 @@ internal override void StatementCompleted(int rowsAffected) internal override void BatchCompleted() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}.", _command.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}.", _command.ObjectID); } internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 parameterValues) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} metaData.Length={1}.", _command.ObjectID, (null != metaData) ? metaData.Length : -1); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} metaData.Length={1}.", _command.ObjectID, metaData?.Length); if (SqlClientEventSource.Log.IsAdvancedTraceOn()) { @@ -368,7 +368,7 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp { for (int i = 0; i < metaData.Length; i++) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, metaData[{1}] is {2}{3}", _command.ObjectID, i, metaData[i].GetType().ToString(), metaData[i].TraceString()); + SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, metaData[{1}] is {2}{3}", _command.ObjectID, i, metaData[i].GetType(), metaData[i].TraceString()); } } } @@ -379,7 +379,10 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter parameterValues, int ordinal) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, metaData[{1}] is {2}{ 3}", _command.ObjectID, ordinal, metaData.GetType().ToString(), metaData.TraceString()); + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, metaData[{1}] is {2}{ 3}", _command.ObjectID, ordinal, metaData?.GetType(), metaData?.TraceString()); + } Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion); _command.OnParameterAvailableSmi(metaData, parameterValues, ordinal); } @@ -562,7 +565,7 @@ private SqlCommand(SqlCommand from) : this() } } _activeConnection = value; // UNDONE: Designers need this setter. Should we block other scenarios? - SqlClientEventSource.Log.TraceEvent(" {0}, {1}", ObjectID, (null != value) ? value.ObjectID : -1); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value?.ObjectID); } } @@ -640,7 +643,7 @@ public SqlNotificationRequest Notification } set { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); _sqlDep = null; _notification = value; } @@ -690,7 +693,7 @@ internal SqlStatistics Statistics } // TODO: Add objid here - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); _transaction = value; } } @@ -725,7 +728,7 @@ override public string CommandText } set { - SqlClientEventSource.Log.TraceEvent(" {0}, String Value = '{1}'", ObjectID, value); + SqlClientEventSource.Log.TryTraceEvent(" {0}, String Value = '{1}'", ObjectID, value); if (0 != ADP.SrcCompare(_commandText, value)) { @@ -763,7 +766,7 @@ override public int CommandTimeout } set { - SqlClientEventSource.Log.TraceEvent(" {0}, {1}", ObjectID, value); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value); if (value < 0) { throw ADP.InvalidCommandTimeout(value); @@ -808,7 +811,7 @@ override public CommandType CommandType } set { - SqlClientEventSource.Log.TraceEvent(" {0}, {1}{2}", ObjectID, (int)value, _commandType); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}{2}", ObjectID, (int)value, _commandType); if (_commandType != value) { switch (value) @@ -951,7 +954,7 @@ internal void OnStatementCompleted(int recordCount) { try { - SqlClientEventSource.Log.TraceEvent(" {0}, recordCount={1}", ObjectID, recordCount); + SqlClientEventSource.Log.TryTraceEvent(" {0}, recordCount={1}", ObjectID, recordCount); handler(this, new StatementCompletedEventArgs(recordCount)); } catch (Exception e) @@ -989,8 +992,8 @@ override public void Prepare() } SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); statistics = SqlStatistics.StartTimer(Statistics); @@ -1092,7 +1095,7 @@ override public void Prepare() } SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } private void InternalPrepare() @@ -1156,7 +1159,7 @@ internal void Unprepare() } _cachedMetaData = null; - SqlClientEventSource.Log.TraceEvent(" {0}, Command unprepared.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command unprepared.", ObjectID); } // Cancel is supposed to be multi-thread safe. @@ -1166,8 +1169,8 @@ internal void Unprepare() /// override public void Cancel() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); SqlStatistics statistics = null; try @@ -1286,7 +1289,7 @@ override public void Cancel() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1329,8 +1332,8 @@ override public object ExecuteScalar() _pendingCancel = false; SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); bool success = false; int? sqlExceptionNumber = null; @@ -1353,7 +1356,7 @@ override public object ExecuteScalar() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1399,8 +1402,8 @@ override public int ExecuteNonQuery() SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); bool success = false; int? sqlExceptionNumber = null; @@ -1421,7 +1424,7 @@ override public int ExecuteNonQuery() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1437,7 +1440,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) _pendingCancel = false; SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1447,7 +1450,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1463,7 +1466,7 @@ public IAsyncResult BeginExecuteNonQuery() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); SqlConnection.ExecutePermission.Demand(); return BeginExecuteNonQueryInternal(0, callback, stateObject, 0, inRetry: false); } @@ -1689,7 +1692,7 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); } } @@ -1707,7 +1710,7 @@ private void ThrowIfReconnectionHasBeenCanceled() private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -1969,7 +1972,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st { // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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) @@ -2023,8 +2026,8 @@ public XmlReader ExecuteXmlReader() SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); bool success = false; int? sqlExceptionNumber = null; @@ -2048,7 +2051,7 @@ public XmlReader ExecuteXmlReader() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -2065,7 +2068,7 @@ public IAsyncResult BeginExecuteXmlReader() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); SqlConnection.ExecutePermission.Demand(); return BeginExecuteXmlReaderInternal(CommandBehavior.SequentialAccess, callback, stateObject, 0, inRetry: false); } @@ -2218,13 +2221,13 @@ public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); } } private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2343,7 +2346,7 @@ public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObjec /// override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); return ExecuteReader(behavior, ADP.ExecuteReader); } @@ -2351,8 +2354,8 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) new public SqlDataReader ExecuteReader() { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -2361,15 +2364,15 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } /// new public SqlDataReader ExecuteReader(CommandBehavior 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); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, behavior={1}", ObjectID, (int)behavior); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); try { @@ -2377,7 +2380,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -2392,7 +2395,7 @@ public IAsyncResult BeginExecuteReader(CommandBehavior behavior) [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); SqlConnection.ExecutePermission.Demand(); return BeginExecuteReaderInternal(behavior, callback, stateObject, 0, inRetry: false); } @@ -2473,13 +2476,13 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); } } private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2881,7 +2884,7 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string /// public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -2966,7 +2969,7 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b /// new public Task ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3100,7 +3103,7 @@ public Task ExecuteXmlReaderAsync() /// public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3706,7 +3709,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 - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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"); @@ -3768,7 +3771,7 @@ private void RunExecuteNonQuerySmi(bool sendToPipe) SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, innerConnection={1}, transactionId=0x{2}, cmdBehavior={3}.", ObjectID, innerConnection.ObjectID, transactionId, (int)CommandBehavior.Default); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, innerConnection={1}, transactionId=0x{2}, cmdBehavior={3}.", ObjectID, innerConnection.ObjectID, transactionId, (int)CommandBehavior.Default); if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { @@ -5250,7 +5253,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi Debug.Assert(!IsUserPrepared, "CommandType.Text with no params should not be prepared!"); if (returnStream) { - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); } string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior); @@ -5315,7 +5318,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi rpc.options = TdsEnums.RPC_NOMETADATA; if (returnStream) { - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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. @@ -5338,7 +5341,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi optionSettings = GetSetOptionsString(cmdBehavior); if (returnStream) { - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as RPC.", ObjectID); } // turn set options ON @@ -5433,7 +5436,7 @@ private SqlDataReader RunExecuteReaderSmi(CommandBehavior cmdBehavior, RunBehavi long transactionId; SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, innerConnection={1}, transactionId=0x{2}, commandBehavior={(int)cmdBehavior}.", ObjectID, innerConnection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, innerConnection={1}, transactionId=0x{2}, commandBehavior={(int)cmdBehavior}.", ObjectID, innerConnection.ObjectID, transactionId); if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { @@ -5653,7 +5656,7 @@ private void NotifyDependency() public SqlCommand Clone() { SqlCommand clone = new SqlCommand(this); - SqlClientEventSource.Log.TraceEvent(" {0}, clone={1}", ObjectID, clone.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, clone={1}", ObjectID, clone?.ObjectID); return clone; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index 7f833e8907..6c5c3a306a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -129,7 +129,7 @@ internal int ObjectID internal void Append(SqlCommand command) { ADP.CheckArgumentNull(command, "command"); - SqlClientEventSource.Log.TraceEvent(" {0}, command={1}, parameterCount={2}", ObjectID, command.ObjectID, command.Parameters.Count); + SqlClientEventSource.Log.TryTraceEvent(" {0}, command={1}, parameterCount={2}", ObjectID, command.ObjectID, command.Parameters.Count); string cmdText = command.CommandText; if (ADP.IsEmpty(cmdText)) @@ -264,7 +264,7 @@ internal static void BuildStoredProcedureName(StringBuilder builder, string part internal void Clear() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); DbCommand batchCommand = BatchCommand; if (null != batchCommand) { @@ -280,7 +280,7 @@ internal void Clear() internal void Dispose() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); SqlCommand command = _batchCommand; _commandList = null; _batchCommand = null; @@ -294,7 +294,7 @@ internal void Dispose() internal int ExecuteNonQuery() { SqlConnection.ExecutePermission.Demand(); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { @@ -315,7 +315,7 @@ internal int ExecuteNonQuery() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(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 8181a4e27d..491ff0cc0a 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 @@ -1196,7 +1196,7 @@ public SqlTransaction BeginTransaction(string transactionName) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, isolationLevel={1}", ObjectID, (int)isolationLevel); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, isolationLevel={1}", ObjectID, (int)isolationLevel); try { @@ -1212,7 +1212,7 @@ override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLeve } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1221,7 +1221,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam { WaitForPendingReconnection(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, iso={1}, transactionName='{2}'", ObjectID, (int)iso, (ADP.IsEmpty(transactionName) ? "None" : transactionName)); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, iso={1}, transactionName='{2}'", ObjectID, (int)iso, transactionName); try { @@ -1249,7 +1249,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); SqlStatistics.StopTimer(statistics); } } @@ -1259,7 +1259,7 @@ override public void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -1353,8 +1353,8 @@ void CloseInnerConnection() /// override public void Close() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { @@ -1438,7 +1438,7 @@ override public void Close() SqlDebugContext sdc = _sdc; _sdc = null; - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); if (sdc != null) { @@ -1498,8 +1498,8 @@ override public void Open() /// public void Open(SqlConnectionOverrides overrides) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { @@ -1533,7 +1533,7 @@ public void Open(SqlConnectionOverrides overrides) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1567,7 +1567,7 @@ private async Task ReconnectAsync(int timeout) { if (ctoken.IsCancellationRequested) { - SqlClientEventSource.Log.TraceEvent(" Original ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Original ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId); return; } try @@ -1589,15 +1589,15 @@ private async Task ReconnectAsync(int timeout) ForceNewConnection = false; } - SqlClientEventSource.Log.TraceEvent(" Reconnection succeeded. ClientConnectionID {0} -> {1}", _originalConnectionId.ToString(), ClientConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Reconnection succeeded. ClientConnectionID {0} -> {1}", _originalConnectionId, ClientConnectionId); return; } catch (SqlException e) { - SqlClientEventSource.Log.TraceEvent(" Original ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message); + SqlClientEventSource.Log.TryTraceEvent(" Original ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message); if (attempt == retryCount - 1) { - SqlClientEventSource.Log.TraceEvent(" Original ClientConnectionID {0} - give up reconnection", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Original ClientConnectionID {0} - give up reconnection", _originalConnectionId); throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) @@ -1664,7 +1664,7 @@ internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; - SqlClientEventSource.Log.TraceEvent(" Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId); _recoverySessionData = cData; if (beforeDisconnect != null) @@ -1757,8 +1757,8 @@ void CancelOpenAndWait() /// public override Task OpenAsync(CancellationToken cancellationToken) { - long scopeID = SqlClientEventSource.Log.PoolerScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryPoolerScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { @@ -1835,7 +1835,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.PoolerScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryPoolerScopeLeaveEvent(scopeID); } } @@ -1856,7 +1856,7 @@ public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource retryTask) { - SqlClientEventSource.Log.TraceEvent(" {0}", _parent.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", _parent.ObjectID); _registration.Dispose(); try @@ -2213,7 +2213,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {0}, Connection broken.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection broken.", ObjectID); Close(); } }; @@ -2222,7 +2222,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {0}, Connection broken.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection broken.", ObjectID); Close(); } } @@ -2330,7 +2330,7 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) Debug.Assert(null != imevent, "null SqlInfoMessageEventArgs"); var imeventValue = (null != imevent) ? imevent.Message : ""; - SqlClientEventSource.Log.TraceEvent(" {0}, Message='{1}'", ObjectID, imeventValue); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Message='{1}'", ObjectID, imeventValue); SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage]; if (null != handler) @@ -2544,8 +2544,8 @@ private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, s /// public static void ChangePassword(string connectionString, string newPassword) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); - SqlClientEventSource.Log.CorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(""); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); try { @@ -2585,15 +2585,15 @@ public static void ChangePassword(string connectionString, string newPassword) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } /// public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); - SqlClientEventSource.Log.CorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(""); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); try { @@ -2655,7 +2655,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -2774,7 +2774,7 @@ private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) { if (asmRef.Version != TypeSystemAssemblyVersion && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.TraceEvent(" SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version.ToString(), TypeSystemAssemblyVersion.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version, TypeSystemAssemblyVersion); } asmRef.Version = TypeSystemAssemblyVersion; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs index ba0c018224..2c56d89165 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; } - SqlClientEventSource.Log.TraceEvent("Set connection pool CreateTimeout={0} when AD Interactive is in use.", connectionTimeout); + SqlClientEventSource.Log.TryTraceEvent("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 767f5d97db..24071a3db1 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) { - SqlClientEventSource.Log.TraceEvent(" alias change detected. Clearing PoolGroup"); + SqlClientEventSource.Log.TryTraceEvent(" alias change detected. Clearing PoolGroup"); base.PoolGroup.Clear(); _alias = server; } @@ -99,7 +99,7 @@ internal void FailoverCheck(SqlInternalConnection connection, bool actualUseFail if (UseFailoverPartner != actualUseFailoverPartner) { // TODO: will connections in progress somehow be active for two different datasources? - SqlClientEventSource.Log.TraceEvent(" Failover detected. failover partner='{0}'. Clearing PoolGroup", actualFailoverPartner); + SqlClientEventSource.Log.TryTraceEvent(" 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 5fbb147c37..68da2c6f4e 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; - SqlClientEventSource.Log.TraceEvent(" {0}, {1}", ObjectID, value); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value); } } @@ -249,7 +249,7 @@ override protected RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, override protected int ExecuteBatch() { Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); return _commandSet.ExecuteNonQuery(); } @@ -273,7 +273,7 @@ override protected bool GetBatchedRecordsAffected(int commandIdentifier, out int /// override protected void InitializeBatching() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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 c29b521eef..176b3ddf3c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -939,7 +939,7 @@ private void CleanPartialReadReliable() override public void Close() { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { @@ -1026,7 +1026,7 @@ override public void Close() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1670,7 +1670,7 @@ override public int GetProviderSpecificValues(object[] values) override public DataTable GetSchemaTable() { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { @@ -1688,7 +1688,7 @@ override public DataTable GetSchemaTable() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -3596,7 +3596,7 @@ override public bool NextResult() private bool TryNextResult(out bool more) { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -3774,7 +3774,7 @@ private bool TryNextResult(out bool more) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -3802,7 +3802,7 @@ override public bool Read() private bool TryReadInternal(bool setTimeout, out bool more) { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -4004,7 +4004,7 @@ private bool TryReadInternal(bool setTimeout, out bool more) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -4469,7 +4469,7 @@ private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateO // broken connection, so check state first. if (parser.State == TdsParserState.OpenLoggedIn) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID '{1}'", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID '{1}'", ObjectID, ActivityCorrelator.Current); 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"); @@ -4781,7 +4781,7 @@ private void AssertReaderState(bool requireData, bool permitAsync, int? columnIn /// public override Task NextResultAsync(CancellationToken cancellationToken) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { @@ -4827,7 +4827,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) { if (t != null) { - SqlClientEventSource.Log.TraceEvent(" attempt retry {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" attempt retry {0}", ObjectID); PrepareForAsyncContinuation(); } @@ -4845,7 +4845,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -4909,7 +4909,7 @@ internal Task GetBytesAsync(int i, byte[] buffer, int index, int length, in { if (t != null) { - SqlClientEventSource.Log.TraceEvent(" attempt retry {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" attempt retry {0}", ObjectID); PrepareForAsyncContinuation(); } @@ -5080,7 +5080,7 @@ private Task GetBytesAsyncReadDataStage(int i, byte[] buffer, int index, in /// public override Task ReadAsync(CancellationToken cancellationToken) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { if (IsClosed) @@ -5200,7 +5200,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) { if (t != null) { - SqlClientEventSource.Log.TraceEvent(" attempt retry {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" attempt retry {0}", ObjectID); PrepareForAsyncContinuation(); } @@ -5239,7 +5239,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs index bc5d483954..50fd5e0746 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs @@ -374,7 +374,7 @@ public override void Close() private void CloseInternal(bool closeConnection) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); bool processFinallyBlock = true; try { @@ -410,7 +410,7 @@ private void CloseInternal(bool closeConnection) Connection.Close(); } - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } } @@ -433,7 +433,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) { - long scopeID = SqlClientEventSource.Log.AdvancedScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryAdvancedScopeEnterEvent(" {0}", ObjectID); try { _hasRows = false; @@ -466,7 +466,7 @@ internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) } finally { - SqlClientEventSource.Log.AdvanceScopeLeave(scopeID); + SqlClientEventSource.Log.TryAdvanceScopeLeave(scopeID); } } @@ -486,7 +486,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) internal unsafe bool InternalRead(bool ignoreNonFatalErrors) { - long scopeID = SqlClientEventSource.Log.AdvancedScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryAdvancedScopeEnterEvent(" {0}", ObjectID); try { // Don't move unless currently in results. @@ -525,7 +525,7 @@ internal unsafe bool InternalRead(bool ignoreNonFatalErrors) } finally { - SqlClientEventSource.Log.AdvanceScopeLeave(scopeID); + SqlClientEventSource.Log.TryAdvanceScopeLeave(scopeID); } } @@ -1316,7 +1316,7 @@ internal ReaderEventSink(SqlDataReaderSmi reader, SmiEventSink parent) internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIsRow) { var mdLength = (null != md) ? md.Length : -1; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, md.Length={1} nextEventIsRow={2}.", reader.ObjectID, mdLength, nextEventIsRow); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, md.Length={1} nextEventIsRow={2}.", reader.ObjectID, mdLength, nextEventIsRow); if (SqlClientEventSource.Log.IsAdvancedTraceOn()) { @@ -1324,7 +1324,7 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs { for (int i = 0; i < md.Length; i++) { - SqlClientEventSource.Log.TraceEvent(" {0}, metaData[{1}] is {2}{3}", reader.ObjectID, i, md[i].GetType().ToString(), md[i].TraceString()); + SqlClientEventSource.Log.TraceEvent(" {0}, metaData[{1}] is {2}{3}", reader.ObjectID, i, md[i].GetType(), md[i].TraceString()); } } } @@ -1334,25 +1334,25 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs // Obsolete V2- method internal override void RowAvailable(ITypedGetters row) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} (v2).", reader.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} (v2).", reader.ObjectID); this.reader.RowAvailable(row); } internal override void RowAvailable(ITypedGettersV3 row) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} (ITypedGettersV3).", reader.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} (ITypedGettersV3).", reader.ObjectID); this.reader.RowAvailable(row); } internal override void RowAvailable(SmiTypedGetterSetter rowData) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} (SmiTypedGetterSetter).", reader.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} (SmiTypedGetterSetter).", reader.ObjectID); this.reader.RowAvailable(rowData); } internal override void StatementCompleted(int recordsAffected) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} recordsAffected= {1}.", reader.ObjectID, recordsAffected); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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. @@ -1362,7 +1362,7 @@ internal override void StatementCompleted(int recordsAffected) internal override void BatchCompleted() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}.", reader.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}.", reader.ObjectID); // devnote: relies on SmiEventSink_Default to pass event to parent // parent's callback *MUST* come before reader's BatchCompleted, since diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs index ef597d5fcd..082de06d3f 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 @@ -88,7 +88,7 @@ public void Initialize() // transaction. SqlInternalConnection connection = _connection; SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, delegating transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, delegating transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -105,7 +105,7 @@ public void Initialize() #endif //DEBUG if (connection.IsEnlistedInTransaction) { - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, was enlisted, now defecting.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, was enlisted, now defecting.", ObjectID, connection.ObjectID); // defect first connection.EnlistNull(); @@ -169,7 +169,7 @@ public Byte[] Promote() if (null != connection) { SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, promoting transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, promoting transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -262,13 +262,13 @@ public Byte[] Promote() else { // The transaction was aborted externally, since it's already doomed above, we only log the same. - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, aborted during promote.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, aborted during promote.", ObjectID, connection.ObjectID); } } else { // The transaction was aborted externally, doom the connection to make sure it's eventually rolled back and log the same. - SqlClientEventSource.Log.TraceEvent(" {0}, Connection null, aborted before promoting.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection null, aborted before promoting.", ObjectID); } return returnValue; } @@ -287,7 +287,7 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) #endif //DEBUG SqlConnection usersConnection = connection.Connection; RuntimeHelpers.PrepareConstrainedRegions(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, rolling back transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, rolling back transaction.", ObjectID, connection.ObjectID); try { lock (connection) @@ -364,7 +364,7 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) { // The transaction was aborted, report that to SysTx and log the same. enlistment.Aborted(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection null, aborted before rollback.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection null, aborted before rollback.", ObjectID); } } @@ -378,7 +378,7 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) if (null != connection) { SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, committing transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, committing transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -501,7 +501,7 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) { // The transaction was aborted before we could commit, report that to SysTx and log the same. enlistment.Aborted(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection null, aborted before commit.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection null, aborted before commit.", ObjectID); } } @@ -515,7 +515,7 @@ internal void TransactionEnded(SysTx.Transaction transaction) if (connection != null) { - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, transaction completed externally.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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 89fab12b93..52bcec0599 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -339,7 +339,7 @@ public SqlDependency(SqlCommand command) : this(command, null, SQL.SqlDependency [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public SqlDependency(SqlCommand command, string options, int timeout) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, options: '{1}', timeout: '{2}'", ObjectID, options, timeout); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, options: '{1}', timeout: '{2}'", ObjectID, options, timeout); try { if (InOutOfProcHelper.InProc) @@ -362,7 +362,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -459,7 +459,7 @@ internal int Timeout // EventHandlers to be fired when dependency is notified. add { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { @@ -472,12 +472,12 @@ internal int Timeout if (_dependencyFired) { // If fired, fire the new event immediately. - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency already fired, firing new event."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency already fired, firing new event."); sqlNotificationEvent = new SqlNotificationEventArgs(SqlNotificationType.Subscribe, SqlNotificationInfo.AlreadyChanged, SqlNotificationSource.Client); } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency has not fired, adding new event."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency has not fired, adding new event."); EventContextPair pair = new EventContextPair(value, this); if (!_eventList.Contains(pair)) { @@ -498,12 +498,12 @@ internal int Timeout } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } remove { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { if (null != value) @@ -521,7 +521,7 @@ internal int Timeout } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } @@ -538,7 +538,7 @@ public void AddCommandDependency(SqlCommand command) { // Adds command to dependency collection so we automatically create the SqlNotificationsRequest object // and listen for a notification for the added commands. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { if (command == null) @@ -550,7 +550,7 @@ public void AddCommandDependency(SqlCommand command) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -576,10 +576,10 @@ private static void ObtainProcessDispatcher() if (nativeStorage == null) { - SqlClientEventSource.Log.NotificationTraceEvent(" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher."); #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource.Log.NotificationTraceEvent(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); #endif _AppDomain masterDomain = SNINativeMethodWrapper.GetDefaultAppDomain(); @@ -605,33 +605,33 @@ private static void ObtainProcessDispatcher() } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - ObjectHandle.Unwrap returned null!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - ObjectHandle.Unwrap returned null!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyObtainProcessDispatcherFailureObjectHandle); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - AppDomain.CreateInstance returned null!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - AppDomain.CreateInstance returned null!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureCreateInstance); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - unable to obtain default AppDomain!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - unable to obtain default AppDomain!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureAppDomain); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher."); #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource.Log.NotificationTraceEvent(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" 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. - SqlClientEventSource.Log.NotificationTraceEvent(" processDispatcher obtained, ID: {0}", _processDispatcher.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" processDispatcher obtained, ID: {0}", _processDispatcher.ObjectID); } } @@ -680,7 +680,7 @@ public static bool Start(string connectionString, string queue) internal static bool Start(string connectionString, string queue, bool useDefaults) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" 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 @@ -754,7 +754,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul out errorOccurred, out appDomainStart); - SqlClientEventSource.Log.NotificationTraceEvent(" Start (defaults) returned: '{0}', with service: '{1}', server: '{2}', database: '{3}'", result, service, server, database); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Start (defaults) returned: '{0}', with service: '{1}', server: '{2}', database: '{3}'", result, service, server, database); } finally { @@ -776,7 +776,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - SqlClientEventSource.Log.NotificationTraceEvent(" Exception occurred from Stop() after duplicate was found on Start()."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception occurred from Stop() after duplicate was found on Start()."); } throw SQL.SqlDependencyDuplicateStart(); } @@ -789,7 +789,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul queue, _appDomainKey, SqlDependencyPerAppDomainDispatcher.SingletonInstance); - SqlClientEventSource.Log.NotificationTraceEvent(" Start (user provided queue) returned: '{0}'", result); + SqlClientEventSource.Log.TryNotificationTraceEvent(" 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. @@ -804,7 +804,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - SqlClientEventSource.Log.NotificationTraceEvent(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); throw; } } @@ -813,7 +813,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -833,7 +833,7 @@ public static bool Stop(string connectionString, string queue) internal static bool Stop(string connectionString, string queue, bool useDefaults, bool startFailed) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" 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 @@ -943,7 +943,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -953,7 +953,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault private static bool AddToServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); try { bool result = false; @@ -964,7 +964,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!_serverUserHash.ContainsKey(server)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Hash did not contain server, adding."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Hash did not contain server, adding."); identityDatabaseHash = new Dictionary>(); _serverUserHash.Add(server, identityDatabaseHash); } @@ -977,7 +977,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!identityDatabaseHash.ContainsKey(identityUser)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Hash contained server but not user, adding user."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Hash contained server but not user, adding user."); databaseServiceList = new List(); identityDatabaseHash.Add(identityUser, databaseServiceList); } @@ -988,13 +988,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!databaseServiceList.Contains(databaseService)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Adding database."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Adding database."); databaseServiceList.Add(databaseService); result = true; } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash already contained server, user, and database - we will throw!."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash already contained server, user, and database - we will throw!."); } } @@ -1002,13 +1002,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private static void RemoveFromServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); try { lock (_serverUserHash) @@ -1028,43 +1028,43 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair int index = databaseServiceList.IndexOf(databaseService); if (index >= 0) { - SqlClientEventSource.Log.NotificationTraceEvent(" Hash contained server, user, and database - removing database."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Hash contained server, user, and database - removing database."); databaseServiceList.RemoveAt(index); if (databaseServiceList.Count == 0) { - SqlClientEventSource.Log.NotificationTraceEvent(" databaseServiceList count 0, removing the list for this server and user."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" databaseServiceList count 0, removing the list for this server and user."); identityDatabaseHash.Remove(identityUser); if (identityDatabaseHash.Count == 0) { - SqlClientEventSource.Log.NotificationTraceEvent(" identityDatabaseHash count 0, removing the hash for this server."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" identityDatabaseHash count 0, removing the hash for this server."); _serverUserHash.Remove(server); } } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash contained server and user but not database!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash contained server and user but not database!"); Debug.Assert(false, "Unexpected state - hash did not contain database!"); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash contained server but not user!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash contained server but not user!"); Debug.Assert(false, "Unexpected state - hash did not contain user!"); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash did not contain server!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash did not contain server!"); Debug.Assert(false, "Unexpected state - hash did not contain server!"); } } } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1072,7 +1072,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { // Server must be an exact match, but user and database only needs to match exactly if there is more than one // for the given user or database passed. That is ambiguious and we must fail. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" server: '{0}', failoverServer: '{1}', database: '{2}'", server, failoverServer, database); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" server: '{0}', failoverServer: '{1}', database: '{2}'", server, failoverServer, database); try { @@ -1085,17 +1085,17 @@ internal static string GetDefaultComposedOptions(string server, string failoverS if (0 == _serverUserHash.Count) { // Special error for no calls to start. - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - no start calls have been made, about to throw."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - no start calls have been made, about to throw."); throw SQL.SqlDepDefaultOptionsButNoStart(); } else if (!ADP.IsEmpty(failoverServer) && _serverUserHash.ContainsKey(failoverServer)) { - SqlClientEventSource.Log.NotificationTraceEvent(" using failover server instead\n"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" using failover server instead\n"); server = failoverServer; } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - not listening to this server, about to throw."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - not listening to this server, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } } @@ -1108,7 +1108,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { if (identityDatabaseHash.Count > 1) { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - not listening for this user, " + + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - not listening for this user, " + "but listening to more than one other user, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } @@ -1156,19 +1156,19 @@ internal static string GetDefaultComposedOptions(string server, string failoverS else { // More than one database for given server, ambiguous - fail the default case! - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" 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!"); - SqlClientEventSource.Log.NotificationTraceEvent(" resulting options: '{0}'.", result); + SqlClientEventSource.Log.TryNotificationTraceEvent(" resulting options: '{0}'.", result); return result; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1180,7 +1180,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS // use this list for a reverse lookup based on server. internal void AddToServerList(string server) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); try { lock (_serverList) @@ -1189,7 +1189,7 @@ internal void AddToServerList(string server) if (0 > index) { // If less than 0, item was not found in list. - SqlClientEventSource.Log.NotificationTraceEvent(" Server not present in hashtable, adding server: '{0}'.", server); + SqlClientEventSource.Log.TryNotificationTraceEvent(" 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); } @@ -1197,7 +1197,7 @@ internal void AddToServerList(string server) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1211,7 +1211,7 @@ internal bool ContainsServer(string server) internal string ComputeHashAndAddToDispatcher(SqlCommand command) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, command.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {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. @@ -1226,18 +1226,18 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) string commandHash = ComputeCommandHash(command.Connection.ConnectionString, command); // calculate the string representation of command string idString = SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddCommandEntry(commandHash, this); // Add to map. - SqlClientEventSource.Log.NotificationTraceEvent(" computed id string: '{0}'.", idString); + SqlClientEventSource.Log.TryNotificationTraceEvent(" computed id string: '{0}'.", idString); return idString; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { List eventList = null; @@ -1255,12 +1255,12 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql // raises Timeout event but before removing this event from the list. If notification is received from // server in this case, we will hit this code path. // It is safe to ignore this race condition because no event is sent to user and no leak happens. - SqlClientEventSource.Log.NotificationTraceEvent(" ignore notification received after timeout!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ignore notification received after timeout!"); } else { Debug.Assert(false, "Received notification twice - we should never enter this state!"); - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - notification received twice - we should never enter this state!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - notification received twice - we should never enter this state!"); } } else @@ -1274,7 +1274,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (eventList != null) { - SqlClientEventSource.Log.NotificationTraceEvent(" Firing events."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Firing events."); foreach (EventContextPair pair in eventList) { pair.Invoke(new SqlNotificationEventArgs(type, info, source)); @@ -1283,19 +1283,19 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is used by SqlCommand. internal void StartTimer(SqlNotificationRequest notificationRequest) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { if (_expirationTime == DateTime.MaxValue) { - SqlClientEventSource.Log.NotificationTraceEvent(" We've timed out, executing logic."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" We've timed out, executing logic."); int seconds = SQL.SqlDependencyServerTimeout; if (0 != _timeout) { @@ -1313,7 +1313,7 @@ internal void StartTimer(SqlNotificationRequest notificationRequest) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1326,7 +1326,7 @@ private void AddCommandInternal(SqlCommand cmd) if (cmd != null) { // Don't bother with BID if command null. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, cmd.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, cmd.ObjectID); try { SqlConnection connection = cmd.Connection; @@ -1336,7 +1336,7 @@ private void AddCommandInternal(SqlCommand cmd) // Fail if cmd has notification that is not already associated with this dependency. if (cmd._sqlDep == null || cmd._sqlDep != this) { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - throwing command has existing SqlNotificationRequest exception."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - throwing command has existing SqlNotificationRequest exception."); throw SQL.SqlCommandHasExistingSqlNotificationRequest(); } } @@ -1368,7 +1368,7 @@ private void AddCommandInternal(SqlCommand cmd) if (0 == _eventList.Count) { // Keep logic just in case. - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - firing events, though it is unexpected we have events at this point."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - firing events, though it is unexpected we have events at this point."); needToInvalidate = true; // Delay invalidation until outside of lock. } } @@ -1382,14 +1382,14 @@ private void AddCommandInternal(SqlCommand cmd) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } private string ComputeCommandHash(string connectionString, SqlCommand command) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, command.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {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. @@ -1446,12 +1446,12 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) } string result = builder.ToString(); - SqlClientEventSource.Log.NotificationTraceEvent(" ComputeCommandHash result: '{0}'.", result); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ComputeCommandHash result: '{0}'.", result); return result; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(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 6566ee1c72..d05a0bb2b2 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 @@ -78,7 +78,7 @@ internal int ObjectID // ----------- internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, HashHelper?.Queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, HashHelper?.Queue); bool setupCompleted = false; try @@ -101,7 +101,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(_hashHelper.ConnectionStringBuilder.ConnectionString); - SqlClientEventSource.Log.NotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif // Always use ConnectionStringBuilder since in default case it is different from the @@ -216,7 +216,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -276,7 +276,7 @@ internal string Server // SqlDependencyProcessDispatcher.QueueAppDomainUnload on AppDomain.Unload. internal bool AppDomainUnload(string appDomainKey) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, AppDomainKey: '{1}'", ObjectID, appDomainKey); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, AppDomainKey: '{1}'", ObjectID, appDomainKey); try { Debug.Assert(!ADP.IsEmpty(appDomainKey), "Unexpected empty appDomainKey!"); @@ -288,9 +288,9 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { // Do nothing if AppDomain did not call Start! - SqlClientEventSource.Log.NotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}'.", appDomainKey); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}'.", appDomainKey); int value = _appDomainKeyHash[appDomainKey]; - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{0}' count: '{1}'.", appDomainKey, value); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{0}' count: '{1}'.", appDomainKey, value); Debug.Assert(value > 0, "Why is value 0 or less?"); bool ignored = false; @@ -307,26 +307,26 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{0}' entry not removed from hash. Count: {1}'", appDomainKey, _appDomainKeyHash[appDomainKey]); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{0}' entry not removed from hash. Count: {1}'", appDomainKey, _appDomainKeyHash[appDomainKey]); } } else { - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{0}'.", appDomainKey); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{0}'.", appDomainKey); } } - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{0}'.", _stopped); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{0}'.", _stopped); return _stopped; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void AsynchronouslyQueryServiceBrokerQueue() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { AsyncCallback callback = new AsyncCallback(AsyncResultCallback); @@ -334,13 +334,13 @@ private void AsynchronouslyQueryServiceBrokerQueue() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void AsyncResultCallback(IAsyncResult asyncResult) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { using (SqlDataReader reader = _com.EndExecuteReader(asyncResult)) @@ -366,7 +366,7 @@ private void AsyncResultCallback(IAsyncResult asyncResult) _errorState = true; throw; } - SqlClientEventSource.Log.NotificationTraceEvent(" Exception occurred."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception occurred."); if (!_stop) { // Only assert if not in cancel path. @@ -386,13 +386,13 @@ private void AsyncResultCallback(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void CreateQueueAndService(bool restart) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { SqlCommand com = new SqlCommand(); @@ -522,18 +522,18 @@ private void CreateQueueAndService(bool restart) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { appDomainStart = false; // Reset out param. int result = Interlocked.Increment(ref _startCount); // Add to refCount. - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> {0}, incremented _startCount: {1}", _staticInstance.ObjectID, result); + SqlClientEventSource.Log.TryNotificationTraceEvent("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. @@ -542,25 +542,25 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { _appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1; - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{0}', incremented count: '{1}'.", appDomainKey, _appDomainKeyHash[appDomainKey]); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{0}', incremented count: '{1}'.", appDomainKey, _appDomainKeyHash[appDomainKey]); } else { _appDomainKeyHash[appDomainKey] = 1; appDomainStart = true; - SqlClientEventSource.Log.NotificationTraceEvent(" _appDomainKeyHash did not contain AppDomainKey: '{0}', added to hashtable and value set to 1.", appDomainKey); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _appDomainKeyHash did not contain AppDomainKey: '{0}', added to hashtable and value set to 1.", appDomainKey); } } } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void ProcessNotificationResults(SqlDataReader reader) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { Guid handle = Guid.Empty; // Conversation_handle. Always close this! @@ -570,18 +570,18 @@ private void ProcessNotificationResults(SqlDataReader reader) { while (reader.Read()) { - SqlClientEventSource.Log.NotificationTraceEvent(" Row read."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Row read."); #if DEBUG if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) { for (int i = 0; i < reader.FieldCount; i++) { - SqlClientEventSource.Log.NotificationTraceEvent(" column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i).ToString()); + SqlClientEventSource.Log.NotificationTraceEvent(" column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i)); } } #endif string msgType = reader.GetString(0); - SqlClientEventSource.Log.NotificationTraceEvent(" msgType: '{0}'", msgType); + SqlClientEventSource.Log.TryNotificationTraceEvent(" msgType: '{0}'", msgType); handle = reader.GetGuid(1); // Only process QueryNotification messages. @@ -594,7 +594,7 @@ private void ProcessNotificationResults(SqlDataReader reader) if (null != notification) { string key = notification.Key; - SqlClientEventSource.Log.NotificationTraceEvent(" Key: '{0}'", key); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Key: '{0}'", key); int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash" if (index >= 0) @@ -623,25 +623,25 @@ private void ProcessNotificationResults(SqlDataReader reader) else { Debug.Assert(false, "Received notification but do not have an associated PerAppDomainDispatcher!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Received notification but do not have an associated PerAppDomainDispatcher!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Received notification but do not have an associated PerAppDomainDispatcher!"); } } else { Debug.Assert(false, "Unexpected ID format received!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Unexpected ID format received!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Unexpected ID format received!"); } } else { Debug.Assert(false, "Null notification returned from ProcessMessage!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Null notification returned from ProcessMessage!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Null notification returned from ProcessMessage!"); } } else { Debug.Assert(false, "Null payload for QN notification type!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Null payload for QN notification type!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Null payload for QN notification type!"); } } else @@ -649,7 +649,7 @@ private void ProcessNotificationResults(SqlDataReader reader) handle = Guid.Empty; // VSDD 546707: this assert was hit by SQL Notification fuzzing tests, disable it to let these tests run on Debug bits // Debug.Assert(false, "Unexpected message format received!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Unexpected message format received!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Unexpected message format received!"); } } } @@ -681,7 +681,7 @@ private void ProcessNotificationResults(SqlDataReader reader) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -692,7 +692,7 @@ private void ProcessNotificationResults(SqlDataReader reader) private void Restart(object unused) { // Unused arg required by TimerCallback. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { try @@ -854,13 +854,13 @@ private void Restart(object unused) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } internal bool Stop(string appDomainKey, out bool appDomainStop) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { appDomainStop = false; @@ -880,7 +880,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) int value = _appDomainKeyHash[appDomainKey]; Debug.Assert(value > 0, "Unexpected count for appDomainKey"); - SqlClientEventSource.Log.NotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}', pre-decrement Count: '{1}'.", appDomainKey, value); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}', pre-decrement Count: '{1}'.", appDomainKey, value); if (value > 0) { @@ -888,7 +888,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR pre-decremented count <= 0!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR pre-decremented count <= 0!"); Debug.Assert(false, "Unexpected AppDomainKey count in Stop()"); } @@ -900,7 +900,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR appDomainKey not null and not found in hash!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR appDomainKey not null and not found in hash!"); Debug.Assert(false, "Unexpected state on Stop() - no AppDomainKey entry in hashtable!"); } } @@ -913,7 +913,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) { // If we've reached refCount 0, destroy. // Lock to ensure Cancel() complete prior to other thread calling TearDown. - SqlClientEventSource.Log.NotificationTraceEvent(" Reached 0 count, cancelling and waiting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Reached 0 count, cancelling and waiting."); lock (this) { @@ -957,7 +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) { - SqlClientEventSource.Log.NotificationTraceEvent(" forcing cleanup. elapsedSeconds: '{0}', _errorState: '{1}'.", retryStopwatch.Elapsed.Seconds, _errorState); + SqlClientEventSource.Log.TryNotificationTraceEvent(" forcing cleanup. elapsedSeconds: '{0}', _errorState: '{1}'.", retryStopwatch.Elapsed.Seconds, _errorState); Timer retryTimer = _retryTimer; _retryTimer = null; if (retryTimer != null) @@ -976,7 +976,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" _startCount not 0 after decrement. _startCount: '{0}'.", _startCount); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _startCount not 0 after decrement. _startCount: '{0}'.", _startCount); } Debug.Assert(0 <= _startCount, "Invalid start count state"); @@ -985,13 +985,13 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void SynchronouslyQueryServiceBrokerQueue() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { @@ -1002,14 +1002,14 @@ private void SynchronouslyQueryServiceBrokerQueue() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } [SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")] private void TearDownAndDispose() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { @@ -1083,7 +1083,7 @@ private void TearDownAndDispose() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } @@ -1227,42 +1227,42 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) catch (ArgumentException e) { ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace. - SqlClientEventSource.Log.NotificationTraceEvent(" Exception thrown - Enum.Parse failed to parse the value '{0}' of the attribute '{1}'.", xmlReader.Value, xmlReader.LocalName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception thrown - Enum.Parse failed to parse the value '{0}' of the attribute '{1}'.", xmlReader.Value, xmlReader.LocalName); return null; } } if (MessageAttributes.All != messageAttributes) { - SqlClientEventSource.Log.NotificationTraceEvent(" Not all expected attributes in Message; messageAttributes = '{0}'.", (int)messageAttributes); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Not all expected attributes in Message; messageAttributes = '{0}'.", (int)messageAttributes); return null; } // Proceed to the "Message" node. if (!xmlReader.Read()) { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" 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))) { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Proceed to the Text Node. if (!xmlReader.Read()) { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Verify state after Read(). if (xmlReader.NodeType != XmlNodeType.Text) { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } @@ -1272,7 +1272,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the Text Node. if (!xmlMessageReader.Read()) { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } @@ -1283,7 +1283,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } } @@ -1292,7 +1292,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; // failure } } @@ -1472,19 +1472,19 @@ internal int ObjectID private SqlDependencyProcessDispatcher(object dummyVariable) { Debug.Assert(null == _staticInstance, "Real constructor called with static instance already created!"); - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); #endif _connectionContainers = new Dictionary(); _sqlDependencyPerAppDomainDispatchers = new Dictionary(); } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1492,18 +1492,18 @@ private SqlDependencyProcessDispatcher(object dummyVariable) // Required to be public, even on internal class, for Remoting infrastructure. public SqlDependencyProcessDispatcher() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { // Empty constructor and object - dummy to obtain singleton. #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); #endif } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1529,7 +1529,7 @@ internal SqlDependencyProcessDispatcher SingletonProcessDispatcher out string user, string queue) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: {1}", _staticInstance.ObjectID, queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: {1}", _staticInstance.ObjectID, queue); try { // Force certain connection string properties to be used by SqlDependencyProcessDispatcher. @@ -1562,7 +1562,7 @@ internal SqlDependencyProcessDispatcher SingletonProcessDispatcher } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1574,7 +1574,7 @@ public override object InitializeLifetimeService() private void Invalidate(string server, SqlNotification sqlNotification) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, server: {1}", ObjectID, server); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, server: {1}", ObjectID, server); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1606,7 +1606,7 @@ private void Invalidate(string server, SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1623,7 +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) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { string appDomainKey = (string)state; @@ -1655,7 +1655,7 @@ private void AppDomainUnloading(object state) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1722,7 +1722,7 @@ private void AppDomainUnloading(object state) out bool appDomainStart, bool useDefaults) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: '{1}', appDomainKey: '{2}', perAppDomainDispatcher ID: '{3}'", ObjectID, queueService, appDomainKey, dispatcher.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {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!"); @@ -1749,7 +1749,7 @@ private void AppDomainUnloading(object state) queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - SqlClientEventSource.Log.NotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif bool started = false; @@ -1759,7 +1759,7 @@ private void AppDomainUnloading(object state) { if (!_connectionContainers.ContainsKey(hashHelper)) { - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable miss, creating new container.", ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable miss, creating new container.", ObjectID); container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults); _connectionContainers.Add(hashHelper, container); started = true; @@ -1768,10 +1768,10 @@ private void AppDomainUnloading(object state) else { container = _connectionContainers[hashHelper]; - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); if (container.InErrorState) { - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, container: {1} is in error state!", ObjectID, container.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, container: {1} is in error state!", ObjectID, container.ObjectID); errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start(). } else @@ -1786,15 +1786,15 @@ private void AppDomainUnloading(object state) server = container.Server; database = container.Database; queueService = container.Queue; - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, default service: '{1}', server: '{2}', database: '{3}'", ObjectID, queueService, server, database); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, default service: '{1}', server: '{2}', database: '{3}'", ObjectID, queueService, server, database); } - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, started: {1}", ObjectID, started); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, started: {1}", ObjectID, started); return started; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1811,7 +1811,7 @@ private void AppDomainUnloading(object state) string appDomainKey, out bool appDomainStop) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, queueService); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, queueService); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1829,7 +1829,7 @@ private void AppDomainUnloading(object state) queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - SqlClientEventSource.Log.NotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif bool stopped = false; @@ -1839,7 +1839,7 @@ private void AppDomainUnloading(object state) if (_connectionContainers.ContainsKey(hashHelper)) { SqlConnectionContainer container = _connectionContainers[hashHelper]; - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {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; @@ -1852,16 +1852,16 @@ private void AppDomainUnloading(object state) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable miss.", ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable miss.", ObjectID); } } - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, stopped: {1}", ObjectID, stopped); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, stopped: {1}", ObjectID, stopped); return stopped; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(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 3de7a11191..6f91683a4d 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,7 +92,7 @@ internal int ObjectID private SqlDependencyPerAppDomainDispatcher() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { _dependencyIdToDependencyHash = new Dictionary(); @@ -106,7 +106,7 @@ private SqlDependencyPerAppDomainDispatcher() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -124,7 +124,7 @@ public override object InitializeLifetimeService() private void UnloadEventHandler(object sender, EventArgs e) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { // Make non-blocking call to ProcessDispatcher to ThreadPool.QueueUserWorkItem to complete @@ -139,7 +139,7 @@ private void UnloadEventHandler(object sender, EventArgs e) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -150,7 +150,7 @@ private void UnloadEventHandler(object sender, EventArgs e) // This method is called upon SqlDependency constructor. internal void AddDependencyEntry(SqlDependency dep) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); try { lock (this) @@ -160,7 +160,7 @@ internal void AddDependencyEntry(SqlDependency dep) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -168,7 +168,7 @@ internal void AddDependencyEntry(SqlDependency dep) internal string AddCommandEntry(string commandHash, SqlDependency dep) { string notificationId = string.Empty; - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, commandHash: '{1}', SqlDependency: {2}", ObjectID, commandHash, dep.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, commandHash: '{1}', SqlDependency: {2}", ObjectID, commandHash, dep.ObjectID); try { lock (this) @@ -176,7 +176,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) if (!_dependencyIdToDependencyHash.ContainsKey(dep.Id)) { // Determine if depId->dep hashtable contains dependency. If not, it's been invalidated. - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency not present in depId->dep hash, must have been invalidated."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency not present in depId->dep hash, must have been invalidated."); } else { @@ -197,12 +197,12 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // join the new dependency to the list if (!dependencyList.Contains(dep)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency not present for commandHash, adding."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency not present for commandHash, adding."); dependencyList.Add(dep); } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency already present for commandHash."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency already present for commandHash."); } } else @@ -216,7 +216,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) SqlDependency.AppDomainKey, // must be first Guid.NewGuid().ToString("D", System.Globalization.CultureInfo.InvariantCulture) ); - SqlClientEventSource.Log.NotificationTraceEvent(" Creating new Dependencies list for commandHash."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Creating new Dependencies list for commandHash."); DependencyList dependencyList = new DependencyList(commandHash); dependencyList.Add(dep); @@ -238,7 +238,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } return notificationId; @@ -247,7 +247,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // This method is called by the ProcessDispatcher upon a notification for this AppDomain. internal void InvalidateCommandID(SqlNotification sqlNotification) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, sqlNotification.Key); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, sqlNotification.Key); try { List dependencyList = null; @@ -258,7 +258,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) if (null != dependencyList) { - SqlClientEventSource.Log.NotificationTraceEvent(" commandHash found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" commandHash found in hashtable."); foreach (SqlDependency dependency in dependencyList) { // Ensure we remove from process static app domain hash for dependency initiated invalidates. @@ -270,7 +270,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" commandHash NOT found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" commandHash NOT found in hashtable."); } } @@ -279,7 +279,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) // After removal from hashtables, invalidate. foreach (SqlDependency dependency in dependencyList) { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency found in commandHash dependency ArrayList - calling invalidate."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency found in commandHash dependency ArrayList - calling invalidate."); try { dependency.Invalidate(sqlNotification.Type, sqlNotification.Info, sqlNotification.Source); @@ -300,14 +300,14 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(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) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); try { List dependencies = new List(); @@ -354,14 +354,14 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is called by SqlCommand to enable ASP.NET scenarios - map from ID to Dependency. internal SqlDependency LookupDependencyEntry(string id) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, Key: '{1}'", ObjectID, id); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, Key: '{1}'", ObjectID, id); try { if (null == id) @@ -383,7 +383,7 @@ internal SqlDependency LookupDependencyEntry(string id) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - dependency ID mismatch - not throwing."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - dependency ID mismatch - not throwing."); } } @@ -391,21 +391,21 @@ internal SqlDependency LookupDependencyEntry(string id) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // Remove the dependency from the hashtable with the passed id. private void LookupDependencyEntryWithRemove(string id) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, id: '{1}'", ObjectID, id); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, id: '{1}'", ObjectID, id); try { lock (this) { if (_dependencyIdToDependencyHash.ContainsKey(id)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Entry found in hashtable - removing."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entry found in hashtable - removing."); _dependencyIdToDependencyHash.Remove(id); // if there are no more dependencies then we can dispose the timer. @@ -417,20 +417,20 @@ private void LookupDependencyEntryWithRemove(string id) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Entry NOT found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entry NOT found in hashtable."); } } } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // Find and return arraylist, and remove passed hash value. private List LookupCommandEntryWithRemove(string notificationId) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, notificationId); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, notificationId); try { DependencyList entry = null; @@ -439,7 +439,7 @@ private List LookupCommandEntryWithRemove(string notificationId) { if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Entries found in hashtable - removing."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entries found in hashtable - removing."); // update the tables - do it inside finally block to avoid ThreadAbort exception interrupt this operation try @@ -453,7 +453,7 @@ private List LookupCommandEntryWithRemove(string notificationId) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Entries NOT found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entries NOT found in hashtable."); } Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!"); @@ -463,14 +463,14 @@ private List LookupCommandEntryWithRemove(string notificationId) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // Remove from commandToDependenciesHash all references to the passed dependency. private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency dependency) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dependency.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dependency.ObjectID); try { lock (this) @@ -483,7 +483,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende DependencyList dependencies = entry.Value; if (dependencies.Remove(dependency)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Removed SqlDependency: {0}, with ID: '{1}'.", dependency.ObjectID, dependency.Id); + SqlClientEventSource.Log.TryNotificationTraceEvent(" 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 @@ -516,7 +516,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -526,7 +526,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende internal void StartTimer(SqlDependency dep) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); try { // If this dependency expires sooner than the current next timeout, change @@ -537,7 +537,7 @@ internal void StartTimer(SqlDependency dep) // Enable the timer if needed (disable when empty, enable on the first addition). if (!_SqlDependencyTimeOutTimerStarted) { - SqlClientEventSource.Log.NotificationTraceEvent(" Timer not yet started, starting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Timer not yet started, starting."); _timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */); // Save this as the earlier timeout to come. @@ -546,7 +546,7 @@ internal void StartTimer(SqlDependency dep) } else if (_nextTimeout > dep.ExpirationTime) { - SqlClientEventSource.Log.NotificationTraceEvent(" Timer already started, resetting time."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Timer already started, resetting time."); // Save this as the earlier timeout to come. _nextTimeout = dep.ExpirationTime; @@ -555,13 +555,13 @@ internal void StartTimer(SqlDependency dep) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private static void TimeoutTimerCallback(object state) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" AppDomainKey: '{0}'", SqlDependency.AppDomainKey); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" AppDomainKey: '{0}'", SqlDependency.AppDomainKey); try { SqlDependency[] dependencies; @@ -574,12 +574,12 @@ private static void TimeoutTimerCallback(object state) if (0 == SingletonInstance._dependencyIdToDependencyHash.Count) { // Nothing to check. - SqlClientEventSource.Log.NotificationTraceEvent(" No dependencies, exiting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" No dependencies, exiting."); return; } if (SingletonInstance._nextTimeout > DateTime.UtcNow) { - SqlClientEventSource.Log.NotificationTraceEvent(" No timeouts expired, exiting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" No timeouts expired, exiting."); // No dependency timed-out yet. return; @@ -650,7 +650,7 @@ private static void TimeoutTimerCallback(object state) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(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 feec3a7438..1a50bbe2d5 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 @@ -40,7 +40,7 @@ internal SqlError(int infoNumber, byte errorState, byte errorClass, string serve _lineNumber = lineNumber; if (errorClass != 0) { - 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); + SqlClientEventSource.Log.TryTraceEvent(" infoNumber={0}, errorState={1}, errorClass={2}, errorMessage='{3}', procedure='{4}', lineNumber={5}", infoNumber, (int)errorState, (int)errorClass, errorMessage, procedure, (int)lineNumber); } _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 b39a0963e2..bb719f3f20 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -313,7 +313,7 @@ override protected DbReferenceCollection CreateReferenceCollection() override protected void Deactivate() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} deactivating", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} deactivating", ObjectID); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -435,12 +435,12 @@ protected void Enlist(SysTx.Transaction tx) private void EnlistNonNull(SysTx.Transaction tx) { Debug.Assert(null != tx, "null transaction?"); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transaction {1}.", ObjectID, tx.GetHashCode()); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transaction {1}.", ObjectID, tx.GetHashCode()); bool hasDelegatedTransaction = false; if (IsYukonOrNewer) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, attempting to delegate", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, attempting to delegate", ObjectID); // Promotable transactions are only supported on Yukon // servers or newer. @@ -507,7 +507,7 @@ private void EnlistNonNull(SysTx.Transaction tx) if (hasDelegatedTransaction) { this.DelegatedTransaction = delegatedTransaction; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, delegated to transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, delegated to transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); } } catch (SqlException e) @@ -540,7 +540,7 @@ private void EnlistNonNull(SysTx.Transaction tx) if (!hasDelegatedTransaction) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, delegation not possible, enlisting.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, delegation not possible, enlisting.", ObjectID); byte[] cookie = null; if (_isGlobalTransaction) @@ -570,7 +570,7 @@ private void EnlistNonNull(SysTx.Transaction tx) // send cookie to server to finish enlistment PropagateTransactionCookie(cookie); _isEnlistedInTransaction = true; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, enlisted with transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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 @@ -593,7 +593,7 @@ private void EnlistNonNull(SysTx.Transaction tx) internal void EnlistNull() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, unenlisting.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, unenlisting.", ObjectID); // We were in a transaction, but now we are not - so send // message to server with empty transaction - confirmed proper @@ -611,7 +611,7 @@ internal void EnlistNull() _isEnlistedInTransaction = false; EnlistedTransaction = null; // Tell the base class about our enlistment - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, unenlisted.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, unenlisted.", ObjectID); // The EnlistTransaction above will return an TransactionEnded event, // which causes the TdsParser or SmiEventSink should to clear the diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs index 5150a54dc8..e866b0c7ff 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs @@ -65,37 +65,37 @@ internal EventSink(SqlInternalConnectionSmi connection) internal override void DefaultDatabaseChanged(string databaseName) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, databaseName='{1}'.", _connection.ObjectID, databaseName); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, databaseName='{1}'.", _connection.ObjectID, databaseName); _connection.CurrentDatabase = databaseName; } internal override void TransactionCommitted(long transactionId) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionEnded(transactionId, TransactionState.Committed); } internal override void TransactionDefected(long transactionId) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionEnded(transactionId, TransactionState.Unknown); } internal override void TransactionEnlisted(long transactionId) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionStarted(transactionId, true); // distributed; } internal override void TransactionEnded(long transactionId) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionEndedByServer(transactionId, TransactionState.Unknown); } internal override void TransactionRolledBack(long transactionId) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); // Dev11 1066: ensure delegated transaction is rolled back _connection.TransactionEndedByServer(transactionId, TransactionState.Aborted); @@ -103,7 +103,7 @@ internal override void TransactionRolledBack(long transactionId) internal override void TransactionStarted(long transactionId) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionStarted(transactionId, false); // not distributed; } } @@ -119,7 +119,7 @@ internal SqlInternalConnectionSmi(SqlConnectionString connectionOptions, SmiCont Debug.Assert(null != _smiConnection, "null SmiContext.ContextConnection?"); _smiEventSink = new EventSink(this); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, constructed new SMI internal connection", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, constructed new SMI internal connection", ObjectID); } internal SmiContext InternalContext @@ -269,7 +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; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, contextTransactionId=0x{1}, contextTransaction={2}, currentSystemTransaction={3}.", ObjectID, contextTransactionId, (null != contextTransaction) ? contextTransaction.GetHashCode() : 0, (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, contextTransactionId=0x{1}, contextTransaction={2}, currentSystemTransaction={3}.", ObjectID, contextTransactionId, (null != contextTransaction) ? contextTransaction.GetHashCode() : 0, (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0); if (SqlInternalTransaction.NullTransactionId != contextTransactionId) { @@ -278,18 +278,18 @@ internal void AutomaticEnlistment() throw SQL.NestedTransactionScopesNotSupported(); // can't use TransactionScope(RequiresNew) inside a Sql Transaction. } - SqlClientEventSource.Log.TraceEvent(" {0}, using context transaction with transactionId=0x{1}", ObjectID, contextTransactionId); + SqlClientEventSource.Log.TryTraceEvent(" {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. - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, no transaction.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, no transaction.", ObjectID); } else { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, using current System.Transaction.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, using current System.Transaction.", ObjectID); base.Enlist(currentSystemTransaction); } } @@ -302,7 +302,7 @@ override protected void ChangeDatabaseInternal(string database) override protected void InternalDeactivate() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Deactivating.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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. @@ -331,13 +331,13 @@ override protected void InternalDeactivate() override internal void DelegatedTransactionEnded() { base.DelegatedTransactionEnded(); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, cleaning up after Delegated Transaction Completion", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, cleaning up after Delegated Transaction Completion", ObjectID); _currentTransaction = null; // clean up our current transaction too } override internal void DisconnectTransaction(SqlInternalTransaction internalTransaction) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Disconnecting Transaction {1}.", ObjectID, internalTransaction.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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"); @@ -361,8 +361,8 @@ override public void Dispose() SqlInternalTransaction internalTransaction, bool isDelegateControlRequest) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionRequest={1}, " + - "transactionName='{2}', isolationLevel={3}, internalTransaction=#{4} transactionId=0x{5}.", ObjectID, transactionRequest.ToString(), transactionName ?? "null", iso.ToString(), (null != internalTransaction) ? internalTransaction.ObjectID : 0, (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionRequest={1}, " + + "transactionName='{2}', isolationLevel={3}, internalTransaction=#{4} transactionId=0x{5}.", ObjectID, transactionRequest, transactionName , iso, (null != internalTransaction) ? internalTransaction.ObjectID : 0, (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); switch (transactionRequest) { @@ -419,11 +419,11 @@ override protected byte[] GetDTCAddress() if (null != whereAbouts) { - SqlClientEventSource.Log.AdvancedTraceEvent(" whereAbouts = {0}, Length = {1}", whereAbouts, (ushort)whereAbouts.Length); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" whereAbouts = {0}, Length = {1}", whereAbouts, (ushort)whereAbouts.Length); } else { - SqlClientEventSource.Log.AdvancedTraceEvent(" whereAbouts=null"); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" whereAbouts=null"); } return whereAbouts; @@ -449,7 +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. - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} context is out of scope", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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... @@ -480,11 +480,11 @@ override protected void PropagateTransactionCookie(byte[] transactionCookie) if (null != transactionCookie) { - SqlClientEventSource.Log.AdvancedTraceEvent(" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); } else { - SqlClientEventSource.Log.AdvancedTraceEvent(" null"); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" null"); } // Propagate the transaction cookie to the server diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs index 49f947acf2..2d90950cef 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 @@ -581,7 +581,7 @@ static SqlInternalConnectionTds() ThreadHasParserLockForClose = false; _parserLock.Release(); } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, constructed new TDS internal connection", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, constructed new TDS internal connection", ObjectID); } // The erros in the transient error set are contained in @@ -849,7 +849,7 @@ override protected void ChangeDatabaseInternal(string database) override public void Dispose() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} disposing", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} disposing", ObjectID); try { TdsParser parser = Interlocked.Exchange(ref _parser, null); // guard against multiple concurrent dispose calls -- Delegated Transactions might cause this. @@ -1441,12 +1441,12 @@ private void CompleteLogin(bool enlistOK) // ROR should not affect state of connection recovery if (_federatedAuthenticationRequested && !_federatedAuthenticationAcknowledged) { - SqlClientEventSource.Log.TraceEvent(" {0}, Server did not acknowledge the federated authentication request", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Server did not acknowledge the federated authentication request", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged); } if (_federatedAuthenticationInfoRequested && !_federatedAuthenticationInfoReceived) { - SqlClientEventSource.Log.TraceEvent(" {0}, Server never sent the requested federated authentication info", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Server never sent the requested federated authentication info", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoNotReceived); } @@ -1484,7 +1484,7 @@ private void CompleteLogin(bool enlistOK) _parser.EnableMars(); _fConnectionOpen = true; // mark connection as open - SqlClientEventSource.Log.AdvancedTraceEvent(" Post-Login Phase: Server connection obtained."); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Post-Login Phase: Server connection obtained."); // for non-pooled connections, enlist in a distributed transaction // if present - and user specified to enlist @@ -1619,7 +1619,7 @@ private void Login(ServerInfo server, TimeoutTimer timeout, string newPassword, private void LoginFailure() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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. @@ -1745,7 +1745,7 @@ private bool IsDoNotRetryConnectError(SqlException exc) int routingAttempts = 0; ServerInfo originalServerInfo = serverInfo; // serverInfo may end up pointing to new object due to routing, original object is used to set CurrentDatasource - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, host={1}", ObjectID, serverInfo.UserServerName); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, host={1}", ObjectID, serverInfo.UserServerName); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. @@ -1851,7 +1851,7 @@ private bool IsDoNotRetryConnectError(SqlException exc) if (_routingInfo != null) { - SqlClientEventSource.Log.TraceEvent(" Routed to {0}", serverInfo.ExtendedServerName); + SqlClientEventSource.Log.TryTraceEvent(" Routed to {0}", serverInfo.ExtendedServerName); if (routingAttempts > _maxNumberOfRedirectRoute) { @@ -1940,7 +1940,7 @@ private bool IsDoNotRetryConnectError(SqlException exc) // Sleep for a bit to prevent clogging the network with requests, // then update sleep interval for next iteration (max 1 second interval) - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; @@ -2024,7 +2024,7 @@ TimeoutTimer timeout { Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used"); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, useFailover={1}[bool], primary={2}, failover={3}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName, failoverHost ?? "null"); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, useFailover={1}[bool], primary={2}, failover={3}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName, failoverHost); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. long timeoutUnitInterval; @@ -2092,7 +2092,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) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); failoverServerInfo.SetDerivedNames(protocol, ServerProvidedFailOverPartner); } currentServerInfo = failoverServerInfo; @@ -2125,7 +2125,7 @@ TimeoutTimer timeout } routingAttempts++; - SqlClientEventSource.Log.TraceEvent(" Routed to {0}", _routingInfo.ServerName); + SqlClientEventSource.Log.TryTraceEvent(" Routed to {0}", _routingInfo.ServerName); if (_parser != null) _parser.Disconnect(); @@ -2194,7 +2194,7 @@ TimeoutTimer timeout // the network with requests, then update sleep interval for next iteration (max 1 second interval) if (1 == attemptNumber % 2) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } @@ -2269,7 +2269,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) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); _routingInfo = null; // forget routing information @@ -2420,7 +2420,7 @@ internal bool GetSessionAndReconnectIfNeeded(SqlConnection parent, int timeout = internal void BreakConnection() { SqlConnection connection = Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Breaking connection.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Breaking connection.", ObjectID); DoomThisConnection(); // Mark connection as unusable, so it will be destroyed if (null != connection) @@ -2512,7 +2512,7 @@ internal void OnEnvChange(SqlEnvChange rec) break; case TdsEnums.ENV_ROUTING: - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received routing info", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received routing info", ObjectID); if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0) { throw SQL.ROR_InvalidRoutingInfo(this); @@ -2557,7 +2557,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."); - SqlClientEventSource.Log.TraceEvent(" {0}, Generating federated authentication token", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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. @@ -2585,10 +2585,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // And on successful login, try to update the cache with the new token. if (contextValidity <= _dbAuthenticationContextUnLockedRefreshTimeSpan) { - 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()); - + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + 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; } @@ -2608,9 +2610,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // If a thread is already doing the refresh, just use the existing token in the cache and proceed. else if (contextValidity <= _dbAuthenticationContextLockedRefreshTimeSpan) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, " + - "The authentication context needs a refresh.The expiration time is {1}. " + - "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" {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. @@ -2624,10 +2629,10 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // Indicate in Bid Trace that we are successful with the update. if (attemptRefreshTokenLocked) { - SqlClientEventSource.Log.TraceEvent(" {0}, The attempt to get a new access token succeeded under the locked mode.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, The attempt to get a new access token succeeded under the locked mode.", ObjectID); } } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); } } @@ -2688,15 +2693,17 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP // Else some other thread is already updating it, so just proceed forward with the existing token in the cache. if (dbConnectionPoolAuthenticationContext.LockToUpdate()) { - SqlClientEventSource.Log.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()); - + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + 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 { - SqlClientEventSource.Log.TraceEvent(" {0}, Refreshing the context is already in progress by another thread.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Refreshing the context is already in progress by another thread.", ObjectID); } if (authenticationContextLocked) @@ -2856,7 +2863,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) || _timeout.IsExpired || _timeout.MillisecondsRemaining <= sleepInterval) { - SqlClientEventSource.Log.TraceEvent(" {0}", msalException.ErrorCode); + SqlClientEventSource.Log.TryTraceEvent(" {0}", msalException.ErrorCode); // Error[0] SqlErrorCollection sqlErs = new SqlErrorCollection(); @@ -2875,8 +2882,8 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) throw exc; } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); Thread.Sleep(sleepInterval); sleepInterval *= 2; @@ -2892,7 +2899,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) DateTime expirationTime = DateTime.FromFileTimeUtc(fedAuthToken.expirationFileTime); _newDbConnectionPoolAuthenticationContext = new DbConnectionPoolAuthenticationContext(fedAuthToken.accessToken, expirationTime); } - SqlClientEventSource.Log.TraceEvent(" {0}, Finished generating federated authentication token.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Finished generating federated authentication token.", ObjectID); return fedAuthToken; } @@ -2959,11 +2966,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_FEDAUTH: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for federated authentication", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for federated authentication", ObjectID); if (!_federatedAuthenticationRequested) { - SqlClientEventSource.Log.TraceEvent(" {0}, Did not request federated authentication", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Did not request federated authentication", ObjectID); throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); } @@ -2976,7 +2983,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // The server shouldn't have sent any additional data with the ack (like a nonce) if (data.Length != 0) { - SqlClientEventSource.Log.TraceEvent(" {0}, Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthFeatureAckContainsExtraData); } break; @@ -2984,7 +2991,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) default: Debug.Fail("Unknown _fedAuthLibrary type"); - SqlClientEventSource.Log.TraceEvent(" {0}, Attempting to use unknown federated authentication library", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Attempting to use unknown federated authentication library", ObjectID); throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType); } _federatedAuthenticationAcknowledged = true; @@ -3003,11 +3010,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) { - SqlClientEventSource.Log.TraceEvent(" {0}, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); } else { - SqlClientEventSource.Log.TraceEvent(" {0}, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); } #endif } @@ -3016,17 +3023,17 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_TCE: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for TCE", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for TCE", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown version number for TCE", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {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) { - SqlClientEventSource.Log.TraceEvent(" {0}, Invalid version number for TCE", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Invalid version number for TCE", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidVersion, supportedTceVersion); } @@ -3045,11 +3052,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for GlobalTransactions", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for GlobalTransactions", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown version number for GlobalTransactions", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown version number for GlobalTransactions", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } @@ -3063,7 +3070,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_AZURESQLSUPPORT: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for AzureSQLSupport", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for AzureSQLSupport", ObjectID); if (data.Length < 1) { @@ -3075,31 +3082,31 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // Bit 0 for RO/FP support if ((data[0] & 1) == 1 && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, FailoverPartner enabled with Readonly intent for AzureSQL DB", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, FailoverPartner enabled with Readonly intent for AzureSQL DB", ObjectID); } break; } case TdsEnums.FEATUREEXT_DATACLASSIFICATION: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte supportedDataClassificationVersion = data[0]; if ((0 == supportedDataClassificationVersion) || (supportedDataClassificationVersion > TdsEnums.DATA_CLASSIFICATION_VERSION_MAX_SUPPORTED)) { - SqlClientEventSource.Log.TraceEvent(" {0}, Invalid version number for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Invalid version number for DATACLASSIFICATION", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.DataClassificationInvalidVersion, supportedDataClassificationVersion); } if (data.Length != 2) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte enabled = data[1]; @@ -3109,11 +3116,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_UTF8SUPPORT: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for UTF8 support", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for UTF8 support", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown value for UTF8 support", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown value for UTF8 support", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } break; @@ -3121,11 +3128,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_SQLDNSCACHING: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for SQLDNSCACHING", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for SQLDNSCACHING", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown token for SQLDNSCACHING", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown token for SQLDNSCACHING", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs index ed645a3d32..1017c8b789 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -142,8 +142,8 @@ override public void Commit() ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -206,7 +206,7 @@ override public void Commit() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -268,7 +268,7 @@ override public void Rollback() if (IsYukonPartialZombie) { // Put something in the trace in case a customer has an issue - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} partial zombie no rollback required", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} partial zombie no rollback required", ObjectID); _internalTransaction = null; // yukon zombification } @@ -277,8 +277,8 @@ override public void Rollback() ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -329,7 +329,7 @@ override public void Rollback() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } } @@ -342,7 +342,7 @@ public void Rollback(string transactionName) ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} transactionName='{1}'", ObjectID, transactionName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} transactionName='{1}'", ObjectID, transactionName); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -392,7 +392,7 @@ public void Rollback(string transactionName) _isFromAPI = false; SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -404,7 +404,7 @@ public void Save(string savePointName) ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} savePointName='{1}'", ObjectID, savePointName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} savePointName='{1}'", ObjectID, savePointName); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -451,7 +451,7 @@ public void Save(string savePointName) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -470,7 +470,7 @@ internal void Zombie() if (null != internalConnection && internalConnection.IsYukonOrNewer && !_isFromAPI) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} yukon deferred zombie", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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 03404784e0..9c7bdee4c4 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 @@ -526,7 +526,7 @@ internal void ProcessPendingAck(TdsParserStateObject stateObj) LoadSSPILibrary(); // now allocate proper length of buffer _sniSpnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength]; - SqlClientEventSource.Log.TraceEvent(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication", "SEC"); } else { @@ -534,25 +534,25 @@ internal void ProcessPendingAck(TdsParserStateObject stateObj) switch (authType) { case SqlAuthenticationMethod.ActiveDirectoryPassword: - SqlClientEventSource.Log.TraceEvent(" Active Directory Password authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Password authentication", "SEC"); break; case SqlAuthenticationMethod.ActiveDirectoryIntegrated: - SqlClientEventSource.Log.TraceEvent(" Active Directory Integrated authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Integrated authentication", "SEC"); break; case SqlAuthenticationMethod.ActiveDirectoryInteractive: - SqlClientEventSource.Log.TraceEvent(" Active Directory Interactive authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Interactive authentication", "SEC"); break; case SqlAuthenticationMethod.ActiveDirectoryServicePrincipal: - SqlClientEventSource.Log.TraceEvent(" Active Directory Service Principal authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Service Principal authentication", "SEC"); break; case SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow: - SqlClientEventSource.Log.TraceEvent(" Active Directory Device Code Flow authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Device Code Flow authentication", "SEC"); break; case SqlAuthenticationMethod.SqlPassword: - SqlClientEventSource.Log.TraceEvent(" SQL Password authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" SQL Password authentication", "SEC"); break; default: - SqlClientEventSource.Log.TraceEvent(" SQL authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" SQL authentication", "SEC"); break; } } @@ -598,7 +598,7 @@ internal void ProcessPendingAck(TdsParserStateObject stateObj) // don't, the memory for the connection object might not be accurate and thus // a bad error could be returned (as it was when it was freed to early for me). _physicalStateObj.Dispose(); - SqlClientEventSource.Log.TraceEvent(" Login failure", "ERR|SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Login failure", "ERR|SEC"); ThrowExceptionAndWarning(_physicalStateObj); Debug.Fail("SNI returned status != success, but no error thrown?"); } @@ -631,21 +631,21 @@ internal void ProcessPendingAck(TdsParserStateObject stateObj) AssignPendingDNSInfo(serverInfo.UserProtocol, FQDNforDNSCahce); // UNDONE - send "" for instance now, need to fix later - SqlClientEventSource.Log.TraceEvent(" Sending prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" 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"); + SqlClientEventSource.Log.TryTraceEvent(" Consuming prelogin handshake", "SEC"); PreLoginHandshakeStatus status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, out marsCapable, out _connHandler._fedAuthRequired); if (status == PreLoginHandshakeStatus.InstanceFailure) { - SqlClientEventSource.Log.TraceEvent(" Prelogin handshake unsuccessful. Reattempting prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Prelogin handshake unsuccessful. Reattempting prelogin handshake", "SEC"); _physicalStateObj.Dispose(); // Close previous connection // On Instance failure re-connect and flush SNI named instance cache. @@ -655,14 +655,14 @@ internal void ProcessPendingAck(TdsParserStateObject stateObj) if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); - SqlClientEventSource.Log.TraceEvent(" Login failure", "ERR|SEC"); + SqlClientEventSource.Log.TryTraceEvent(" 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"); + SqlClientEventSource.Log.TryTraceEvent(" Sending prelogin handshake", "SEC"); // for DNS Caching phase 1 AssignPendingDNSInfo(serverInfo.UserProtocol, FQDNforDNSCahce); @@ -675,11 +675,11 @@ internal void ProcessPendingAck(TdsParserStateObject stateObj) // one pre-login packet and know we are connecting to Shiloh. if (status == PreLoginHandshakeStatus.InstanceFailure) { - SqlClientEventSource.Log.TraceEvent(" Prelogin handshake unsuccessful. Login failure", "ERR|SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Prelogin handshake unsuccessful. Login failure", "ERR|SEC"); throw SQL.InstanceFailure(); } } - SqlClientEventSource.Log.TraceEvent(" Prelogin handshake successful", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Prelogin handshake successful", "SEC"); if (_fMARS && marsCapable) { @@ -825,7 +825,7 @@ internal void EnableMars() internal TdsParserStateObject CreateSession() { TdsParserStateObject session = new TdsParserStateObject(this, (SNIHandle)_pMarsPhysicalConObj.Handle, true); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} created session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} created session {1}", ObjectID, session.ObjectID); return session; } @@ -840,12 +840,12 @@ internal TdsParserStateObject GetSession(object owner) session = _sessionPool.GetSession(owner); Debug.Assert(!session._pendingData, "pending data on a pooled MARS session"); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} getting session {1} from pool", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} getting session {1} from pool", ObjectID, session.ObjectID); } else { session = _physicalStateObj; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} getting physical session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} getting physical session {1}", ObjectID, session.ObjectID); } Debug.Assert(session._outputPacketNumber == 1, "The packet number is expected to be 1"); return session; @@ -1060,7 +1060,7 @@ private void SendPreLoginHandshake(byte[] instanceName, bool encrypt, bool clien offset += actIdSize; optionDataSize += actIdSize; - SqlClientEventSource.Log.TraceEvent(" ClientConnectionID {0}, ActivityID {1}", _connHandler._clientConnectionId.ToString(), actId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" ClientConnectionID {0}, ActivityID {1}", _connHandler._clientConnectionId, actId); break; case (int)PreLoginOptions.FEDAUTHREQUIRED: @@ -1376,7 +1376,7 @@ private void SendPreLoginHandshake(byte[] instanceName, bool encrypt, bool clien // Only 0x00 and 0x01 are accepted values from the server. if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01) { - SqlClientEventSource.Log.TraceEvent(" {0}, " + + SqlClientEventSource.Log.TryTraceEvent(" {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]); @@ -1419,7 +1419,7 @@ internal void Deactivate(bool connectionIsDoomed) { // Called when the connection that owns us is deactivated. - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} deactivating", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} deactivating", ObjectID); if (SqlClientEventSource.Log.IsStateDumpEnabled()) { SqlClientEventSource.Log.StateDumpEvent(" {0}, {1}", ObjectID, TraceString()); @@ -1574,12 +1574,13 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle // be copied to the end of the error collection so that the user may see all the errors and also the // warnings that occurred. // can be deleted) + //_errorAndWarningsLock lock is implemented inside GetFullErrorAndWarningCollection SqlErrorCollection temp = stateObj.GetFullErrorAndWarningCollection(out breakConnection); Debug.Assert(temp.Count > 0, "TdsParser::ThrowExceptionAndWarning called with no exceptions or warnings!"); if (temp.Count == 0) { - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {0}", ObjectID); } Debug.Assert(_connHandler != null, "TdsParser::ThrowExceptionAndWarning called with null connectionHandler!"); @@ -1618,7 +1619,6 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle } } - // call OnError outside of _ErrorCollectionLock to avoid deadlock if (exception != null) { if (breakConnection) @@ -2152,7 +2152,7 @@ internal bool RunReliably(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDat { tdsReliabilitySection.Start(); #endif //DEBUG - return Run(runBehavior, cmdHandler, dataStream, bulkCopyHandler, stateObj); + return Run(runBehavior, cmdHandler, dataStream, bulkCopyHandler, stateObj); #if DEBUG } finally @@ -2298,7 +2298,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead Debug.Fail($"unexpected token; token = {token,-2:X2}"); _state = TdsParserState.Broken; _connHandler.BreakConnection(); - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, unexpected TDS token found {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, unexpected TDS token found {0}", ObjectID); throw SQL.ParsingErrorToken(ParsingErrorState.InvalidTdsTokenReceived, token); // MDAC 82443 } @@ -2620,7 +2620,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead } case TdsEnums.SQLLOGINACK: { - SqlClientEventSource.Log.TraceEvent(" Received login acknowledgement token", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Received login acknowledgement token", "SEC"); SqlLoginAck ack; if (!TryProcessLoginAck(stateObj, out ack)) @@ -2643,7 +2643,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead { _connHandler._federatedAuthenticationInfoReceived = true; SqlFedAuthInfo info; - SqlClientEventSource.Log.TraceEvent(" Received federated authentication info token", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Received federated authentication info token", "SEC"); if (!TryProcessFedAuthInfo(stateObj, tokenLength, out info)) { @@ -4114,12 +4114,12 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, SqlFedAuthInfo tempFedAuthInfo = new SqlFedAuthInfo(); // Skip reading token length, since it has already been read in caller - SqlClientEventSource.Log.AdvancedTraceEvent(" FEDAUTHINFO token stream length = {0}", tokenLen); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" FEDAUTHINFO token stream length = {0}", tokenLen); if (tokenLen < sizeof(uint)) { // the token must at least contain a DWORD indicating the number of info IDs - SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); + SqlClientEventSource.Log.TryTraceEvent(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen); } @@ -4128,25 +4128,28 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, if (!stateObj.TryReadUInt32(out optionsCount)) { - SqlClientEventSource.Log.TraceEvent(" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" 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 - SqlClientEventSource.Log.AdvancedTraceEvent(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); - + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.TryAdvancedTraceEvent(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); + } if (tokenLen > 0) { // read the rest of the token byte[] tokenData = new byte[tokenLen]; int totalRead = 0; bool successfulRead = stateObj.TryReadByteArray(tokenData, 0, tokenLen, out totalRead); - - SqlClientEventSource.Log.AdvancedTraceEvent(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); - + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); + } if (!successfulRead || totalRead != tokenLen) { - SqlClientEventSource.Log.TraceEvent(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}", tokenLen, totalRead); + SqlClientEventSource.Log.TryTraceEvent(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}", tokenLen, totalRead); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadTokenStream); } @@ -4167,7 +4170,10 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, byte id = tokenData[currentOptionOffset]; uint dataLen = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 1))); uint dataOffset = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 5))); - SqlClientEventSource.Log.AdvancedTraceEvent(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture)); + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" 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 @@ -4179,7 +4185,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) { - SqlClientEventSource.Log.TraceEvent(" FedAuthInfoDataOffset points to an invalid location.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FedAuthInfoDataOffset points to an invalid location.", "ERR"); throw SQL.ParsingErrorOffset(ParsingErrorState.FedAuthInfoInvalidOffset, unchecked((int)dataOffset)); } @@ -4191,15 +4197,15 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } catch (ArgumentOutOfRangeException e) { - SqlClientEventSource.Log.TraceEvent(" Failed to read FedAuthInfoData.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" Failed to read FedAuthInfoData.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadData, e); } catch (ArgumentException e) { - SqlClientEventSource.Log.TraceEvent(" FedAuthInfoData is not in unicode format.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FedAuthInfoData is not in unicode format.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e); } - SqlClientEventSource.Log.AdvancedTraceEvent(" FedAuthInfoData: {0}", data); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" FedAuthInfoData: {0}", data); // store data in tempFedAuthInfo switch ((TdsEnums.FedAuthInfoId)id) @@ -4211,22 +4217,22 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, tempFedAuthInfo.stsurl = data; break; default: - SqlClientEventSource.Log.AdvancedTraceEvent(" Ignoring unknown federated authentication info option: {0}", id); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Ignoring unknown federated authentication info option: {0}", id); break; } } } else { - SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream is not long enough to contain the data it claims to.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FEDAUTHINFO token stream is not long enough to contain the data it claims to.", "ERR"); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForData, tokenLen); } - SqlClientEventSource.Log.TraceEvent(" Processed FEDAUTHINFO token stream: {0}", tempFedAuthInfo.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Processed FEDAUTHINFO token stream: {0}", tempFedAuthInfo); if (string.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || string.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) { // We should be receiving both stsurl and spn - SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream does not contain both STSURL and SPN.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FEDAUTHINFO token stream does not contain both STSURL and SPN.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDoesNotContainStsurlAndSpn); } @@ -4655,7 +4661,7 @@ internal bool TryProcessError(byte token, TdsParserStateObject stateObj, out Sql // validate the index (ordinal passed) if (index >= cipherTable.Value.Size) { - SqlClientEventSource.Log.TraceEvent(" Incorrect ordinal received {0}, max tab size: {1}", index, cipherTable.Value.Size); + SqlClientEventSource.Log.TryTraceEvent(" Incorrect ordinal received {0}, max tab size: {1}", index, cipherTable.Value.Size); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidOrdinalIntoCipherInfoTable, index); } } @@ -8953,7 +8959,7 @@ internal int WriteSQLDNSCachingFeatureRequest(bool write /* if false just calcul } WriteInt(log7Flags, _physicalStateObj); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, TDS Login7 flags = {1}:", ObjectID, log7Flags); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, TDS Login7 flags = {1}:", ObjectID, log7Flags); WriteInt(0, _physicalStateObj); // ClientTimeZone is not used WriteInt(0, _physicalStateObj); // LCID is unused by server @@ -9112,7 +9118,7 @@ internal int WriteSQLDNSCachingFeatureRequest(bool write /* if false just calcul }; if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) { - SqlClientEventSource.Log.TraceEvent(" Sending federated authentication feature request", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending federated authentication feature request", "SEC"); Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null."); WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true); }; @@ -9191,7 +9197,7 @@ internal void SendFedAuthToken(SqlFedAuthToken fedAuthToken) { Debug.Assert(fedAuthToken != null, "fedAuthToken cannot be null"); Debug.Assert(fedAuthToken.accessToken != null, "fedAuthToken.accessToken cannot be null"); - SqlClientEventSource.Log.TraceEvent(" Sending federated authentication token", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending federated authentication token", "SEC"); _physicalStateObj._outputMessageType = TdsEnums.MT_FEDAUTH; @@ -9582,7 +9588,7 @@ internal void PropagateDistributedTransaction(byte[] buffer, int timeout, TdsPar internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) { int old_outputPacketNumber = stateObj._outputPacketNumber; - SqlClientEventSource.Log.TraceEvent(" Exception caught on ExecuteXXX: '{0}'", e.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Exception caught on ExecuteXXX: '{0}'", e); if (stateObj.HasOpenResult) { // SQL BU DT 383773 - need to decrement openResultCount if operation failed. @@ -9615,7 +9621,7 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) _connHandler.ThreadHasParserLockForClose = originalThreadHasParserLock; } } - SqlClientEventSource.Log.TraceEvent(" Exception rethrown.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" Exception rethrown.", "ERR"); } internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, bool sync, bool callerHasConnectionLock = false, byte[] enclavePackage = null) @@ -9671,7 +9677,7 @@ internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationReques stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); } stateObj.SniContext = SniContext.Snix_Execute; @@ -9800,7 +9806,7 @@ internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationReques stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); } stateObj.SniContext = SniContext.Snix_Execute; @@ -10666,7 +10672,7 @@ private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefa var sendDefaultValue = sendDefault ? 1 : 0; if (advancedTraceIsOn) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); } // @@ -11723,7 +11729,7 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio Debug.Assert(-1 <= timeout, "Timeout"); - SqlClientEventSource.Log.NotificationTraceEvent(" NotificationRequest: userData: '{0}', options: '{1}', timeout: '{2}'", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); + SqlClientEventSource.Log.TryNotificationTraceEvent(" NotificationRequest: userData: '{0}', options: '{1}', timeout: '{2}'", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj); // Query notifications Type @@ -11750,7 +11756,7 @@ private void WriteTraceHeaderData(TdsParserStateObject stateObj) stateObj.WriteByteArray(actId.Id.ToByteArray(), GUID_SIZE, 0); // Id (Guid) WriteUnsignedInt(actId.Sequence, stateObj); // sequence number - SqlClientEventSource.Log.TraceEvent(" ActivityID {0}", actId); + SqlClientEventSource.Log.TryTraceEvent(" ActivityID {0}", actId); } 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 eb732e95bf..16754b0b7c 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,7 +36,7 @@ internal TdsParserSessionPool(TdsParser parser) _cache = new List(); _freeStateObjects = new TdsParserStateObject[MaxInactiveCount]; _freeStateObjectCount = 0; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} created session pool for parser {1}", ObjectID, parser.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} created session pool for parser {1}", ObjectID, parser.ObjectID); } private bool IsDisposed @@ -60,7 +60,7 @@ internal void Deactivate() // When being deactivated, we check all the sessions in the // cache to make sure they're cleaned up and then we dispose of // sessions that are past what we want to keep around. - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} deactivating cachedCount={1}", ObjectID, _cachedCount); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} deactivating cachedCount={1}", ObjectID, _cachedCount); try { lock (_cache) @@ -79,7 +79,7 @@ internal void Deactivate() if (session.IsOrphaned) { // TODO: consider adding a performance counter for the number of sessions we reclaim - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} reclaiming session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} reclaiming session {1}", ObjectID, session.ObjectID); PutSession(session); } } @@ -90,7 +90,7 @@ internal void Deactivate() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -113,7 +113,7 @@ internal void BestEffortCleanup() internal void Dispose() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} disposing cachedCount={1}", ObjectID, _cachedCount); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} disposing cachedCount={1}", ObjectID, _cachedCount); lock (_cache) { // Dispose free sessions @@ -172,7 +172,7 @@ internal TdsParserStateObject GetSession(object owner) { // No free objects, create a new one session = _parser.CreateSession(); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} adding session {1} to pool", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} adding session {1} to pool", ObjectID, session.ObjectID); _cache.Add(session); _cachedCount = _cache.Count; @@ -180,7 +180,7 @@ internal TdsParserStateObject GetSession(object owner) session.Activate(owner); } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} using session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} using session {1}", ObjectID, session.ObjectID); return session; } @@ -202,7 +202,7 @@ internal void PutSession(TdsParserStateObject session) else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount)) { // Session is good to re-use and our cache has space - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} keeping session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} keeping session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); Debug.Assert(!session._pendingData, "pending data on a pooled session?"); _freeStateObjects[_freeStateObjectCount] = session; @@ -211,7 +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 - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} disposing session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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 62cc1b7be3..7e526ebd9c 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 @@ -564,8 +564,8 @@ internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount) { return false; } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount); - SqlClientEventSource.Log.AdvancedTraceBinEvent(" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount); + SqlClientEventSource.Log.TryAdvancedTraceBinEvent(" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); return true; } @@ -924,11 +924,11 @@ internal void DecrementOpenResultCount() internal int DecrementPendingCallbacks(bool release) { int remaining = Interlocked.Decrement(ref _pendingCallbacks); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); if ((0 == remaining || release) && _gcHandle.IsAllocated) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, FREEING HANDLE!", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, FREEING HANDLE!", ObjectID); _gcHandle.Free(); } @@ -1037,7 +1037,7 @@ internal int IncrementPendingCallbacks() { int remaining = Interlocked.Increment(ref _pendingCallbacks); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}"); return remaining; } @@ -2174,7 +2174,7 @@ internal bool TryReadNetworkPacket() _snapshot.CheckStack(new StackTrace()); } #endif - SqlClientEventSource.Log.TraceEvent(" Async packet replay{0}", "INFO"); + SqlClientEventSource.Log.TryTraceEvent(" Async packet replay{0}", "INFO"); return true; } #if DEBUG @@ -2596,7 +2596,7 @@ internal bool IsConnectionAlive(bool throwOnException) if ((error != TdsEnums.SNI_SUCCESS) && (error != TdsEnums.SNI_WAIT_TIMEOUT)) { // Connection is dead - SqlClientEventSource.Log.TraceEvent(" received error {0} on idle connection", (int)error); + SqlClientEventSource.Log.TryTraceEvent(" received error {0} on idle connection", (int)error); isAlive = false; if (throwOnException) @@ -2811,7 +2811,7 @@ public void ProcessSniPacket(IntPtr packet, UInt32 error) } } SniReadStatisticsAndTracing(); - SqlClientEventSource.Log.AdvancedTraceBinEvent(" Packet read", _inBuff, (ushort)_inBytesRead); + SqlClientEventSource.Log.TryAdvancedTraceBinEvent(" Packet read", _inBuff, (ushort)_inBytesRead); AssertValidState(); } else @@ -2968,7 +2968,7 @@ public void WriteAsyncCallback(IntPtr key, IntPtr packet, UInt32 sniError) { if (sniError != TdsEnums.SNI_SUCCESS) { - SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)sniError); + SqlClientEventSource.Log.TryTraceEvent(" write async returned error code {0}", (int)sniError); try { AddError(_parser.ProcessSNIError(this)); @@ -3436,7 +3436,7 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr if (error != TdsEnums.SNI_SUCCESS) { - SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)error); + SqlClientEventSource.Log.TryTraceEvent(" write async returned error code {0}", (int)error); AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(); @@ -3474,7 +3474,7 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr } else { - SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)sniError); + SqlClientEventSource.Log.TryTraceEvent(" write async returned error code {0}", (int)sniError); AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(callerHasConnectionLock); } @@ -3534,7 +3534,7 @@ internal void SendAttention(bool mustTakeWriteLock = false) UInt32 sniError; _parser._asyncWrite = false; // stop async write SNIWritePacket(Handle, attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false); - SqlClientEventSource.Log.TraceEvent(" Send Attention ASync.", "Info"); + SqlClientEventSource.Log.TryTraceEvent(" Send Attention ASync.", "Info"); } finally { @@ -3557,8 +3557,8 @@ internal void SendAttention(bool mustTakeWriteLock = false) _attentionSending = false; } - SqlClientEventSource.Log.AdvancedTraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); - SqlClientEventSource.Log.TraceEvent(" Attention sent to the server.", "Info"); + SqlClientEventSource.Log.TryAdvancedTraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); + SqlClientEventSource.Log.TryTraceEvent(" Attention sent to the server.", "Info"); AssertValidState(); } @@ -3744,7 +3744,7 @@ private void SniWriteStatisticsAndTracing() _traceChangePasswordLength = 0; } } - SqlClientEventSource.Log.AdvancedTraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); + SqlClientEventSource.Log.TryAdvancedTraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); } [Conditional("DEBUG")] diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs index 650a1652a4..e7581774c9 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,7 +53,7 @@ internal SqlInternalTransaction(SqlInternalConnection innerConnection, Transacti internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction, long transactionId) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Created for connection {1}, outer transaction {2}, Type {3}", ObjectID, innerConnection.ObjectID, (null != outerTransaction) ? outerTransaction.ObjectID : -1, (int)type); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Created for connection {1}, outer transaction {2}, Type {3}", ObjectID, innerConnection.ObjectID, (null != outerTransaction) ? outerTransaction.ObjectID : -1, (int)type); _innerConnection = innerConnection; _transactionType = type; @@ -268,7 +268,7 @@ 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); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Closing", ObjectID); bool processFinallyBlock = true; try @@ -296,7 +296,7 @@ internal void CloseFromConnection() internal void Commit() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { throw SQL.ConnectionLockedForBcpEvent(); @@ -340,7 +340,7 @@ internal void Commit() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -369,7 +369,7 @@ internal void Dispose() private /*protected override*/ void Dispose(bool disposing) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Disposing", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Disposing", ObjectID); if (disposing) { @@ -425,7 +425,7 @@ internal void InitParent(SqlTransaction transaction) internal void Rollback() { - var scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + var scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { @@ -466,13 +466,13 @@ internal void Rollback() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } internal void Rollback(string transactionName) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, transactionName='{1}'", ObjectID, transactionName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, transactionName='{1}'", ObjectID, transactionName); if (_innerConnection.IsLockedForBulkCopy) { @@ -515,13 +515,13 @@ internal void Rollback(string transactionName) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } internal void Save(string savePointName) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, savePointName='{1}'", ObjectID, savePointName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, savePointName='{1}'", ObjectID, savePointName); _innerConnection.ValidateConnectionForExecute(null); try @@ -552,7 +552,7 @@ internal void Save(string savePointName) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs index 3fb3ffe338..f459f32a25 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs @@ -65,7 +65,7 @@ public SqlFileStream Int64 allocationSize ) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} access={1} options={2} path='{3}'", ObjectID, (int)access, (int)options, path); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} access={1} options={2} path='{3}'", ObjectID, (int)access, (int)options, path); try { //----------------------------------------------------------------- @@ -90,7 +90,7 @@ Int64 allocationSize } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -713,7 +713,7 @@ Int64 allocationSize UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode); try { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, desiredAccess=0x{1}, allocationSize={2}, " + + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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, diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index f9000f5d9f..a2d49e96c8 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -13,6 +13,8 @@ internal partial class SqlClientEventSource : EventSource // Defines the singleton instance for the Resources ETW provider internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); + private const string NullStr = "null"; + #region Event IDs // Initialized static Scope IDs private static long s_nextScopeId = 0; @@ -268,8 +270,30 @@ public static class Tasks //Never use event writer directly as they are not checking for enabled/disabled situations. Always use overloads. #region Trace + + #region Traces without if statements + [NonEvent] + internal void TraceEvent(string message, T0 args0, T1 args1) + { + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); + } + + [NonEvent] + internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2) + { + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); + } + + [NonEvent] + internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); + } + #endregion + + #region Traces with if statements [NonEvent] - internal void TraceEvent(string message) + internal void TryTraceEvent(string message) { if (Log.IsTraceEnabled()) { @@ -278,54 +302,56 @@ internal void TraceEvent(string message) } [NonEvent] - internal void TraceEvent(string message, T0 args0) + internal void TryTraceEvent(string message, T0 args0) { if (Log.IsTraceEnabled()) { - Trace(string.Format(message, args0?.ToString() ?? "Null")); + Trace(string.Format(message, args0?.ToString() ?? NullStr)); } } [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1) + internal void TryTraceEvent(string message, T0 args0, T1 args1) { if (Log.IsTraceEnabled()) { - Trace(string.Format(message, args0?.ToString() ?? "Null", args1?.ToString() ?? "Null")); + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2) + internal void TryTraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsTraceEnabled()) { - Trace(string.Format(message, args0, args1, args2)); + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } } [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void TryTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsTraceEnabled()) { - Trace(string.Format(message, args0, args1, args2, args3)); + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } } [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) + internal void TryTraceEvent(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)); + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr, args4?.ToString() ?? NullStr, args5?.ToString() ?? NullStr)); } } #endregion + #endregion + #region Scope [NonEvent] - internal long ScopeEnterEvent(string message) + internal long TryScopeEnterEvent(string message) { if (Log.IsScopeEnabled()) { @@ -335,47 +361,47 @@ internal long ScopeEnterEvent(string message) } [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0) + internal long TryScopeEnterEvent(string message, T0 args0) { if (Log.IsScopeEnabled()) { - return ScopeEnter(string.Format(message, args0)); + return ScopeEnter(string.Format(message, args0?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0, T1 args1) + internal long TryScopeEnterEvent(string message, T0 args0, T1 args1) { if (Log.IsScopeEnabled()) { - return ScopeEnter(string.Format(message, args0, args1)); + return ScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) + internal long TryScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsScopeEnabled()) { - return ScopeEnter(string.Format(message, args0, args1, args2)); + return ScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal long TryScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsScopeEnabled()) { - return ScopeEnter(string.Format(message, args0, args1, args2, args3)); + return ScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal void ScopeLeaveEvent(long scopeId) + internal void TryScopeLeaveEvent(long scopeId) { if (Log.IsScopeEnabled()) { @@ -385,8 +411,18 @@ internal void ScopeLeaveEvent(long scopeId) #endregion #region Notification Trace + + #region Notification Traces without if statements [NonEvent] - internal void NotificationTraceEvent(string message) + internal void NotificationTraceEvent(string message, T0 args0, T1 args1) + { + NotificationTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); + } + #endregion + + #region Notification Traces with if statements + [NonEvent] + internal void TryNotificationTraceEvent(string message) { if (Log.IsNotificationTraceEnabled()) { @@ -395,85 +431,87 @@ internal void NotificationTraceEvent(string message) } [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0) + internal void TryNotificationTraceEvent(string message, T0 args0) { if (Log.IsNotificationTraceEnabled()) { - NotificationTrace(string.Format(message, args0)); + NotificationTrace(string.Format(message, args0?.ToString() ?? NullStr)); } } [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0, T1 args1) + internal void TryNotificationTraceEvent(string message, T0 args0, T1 args1) { if (Log.IsNotificationTraceEnabled()) { - NotificationTrace(string.Format(message, args0, args1)); + NotificationTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0, T1 args1, T2 args2) + internal void TryNotificationTraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsNotificationTraceEnabled()) { - NotificationTrace(string.Format(message, args0, args1, args2)); + NotificationTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } } [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void TryNotificationTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsNotificationTraceEnabled()) { - NotificationTrace(string.Format(message, args0, args1, args2, args3)); + NotificationTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } } #endregion + #endregion + #region Notification Scope [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0) + internal long TryNotificationScopeEnterEvent(string message, T0 args0) { if (Log.IsNotificationScopeEnabled()) { - return NotificationScopeEnter(string.Format(message, args0)); + return NotificationScopeEnter(string.Format(message, args0?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0, T1 args1) + internal long TryNotificationScopeEnterEvent(string message, T0 args0, T1 args1) { if (Log.IsNotificationScopeEnabled()) { - return NotificationScopeEnter(string.Format(message, args0, args1)); + return NotificationScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) + internal long TryNotificationScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsNotificationScopeEnabled()) { - return NotificationScopeEnter(string.Format(message, args0, args1, args2)); + return NotificationScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal long TryNotificationScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsNotificationScopeEnabled()) { - return NotificationScopeEnter(string.Format(message, args0, args1, args2, args3)); + return NotificationScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal void NotificationScopeLeaveEvent(long scopeId) + internal void TryNotificationScopeLeaveEvent(long scopeId) { if (Log.IsNotificationScopeEnabled()) { @@ -484,55 +522,55 @@ internal void NotificationScopeLeaveEvent(long scopeId) #region Pooler Trace [NonEvent] - internal void PoolerTraceEvent(string message, T0 args0) + internal void TryPoolerTraceEvent(string message, T0 args0) { if (Log.IsPoolerTraceEnabled()) { - PoolerTrace(string.Format(message, args0)); + PoolerTrace(string.Format(message, args0?.ToString() ?? NullStr)); } } [NonEvent] - internal void PoolerTraceEvent(string message, T0 args0, T1 args1) + internal void TryPoolerTraceEvent(string message, T0 args0, T1 args1) { if (Log.IsPoolerTraceEnabled()) { - PoolerTrace(string.Format(message, args0, args1)); + PoolerTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2) + internal void TryPoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsPoolerTraceEnabled()) { - PoolerTrace(string.Format(message, args0, args1, args2)); + PoolerTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } } [NonEvent] - internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void TryPoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsPoolerTraceEnabled()) { - PoolerTrace(string.Format(message, args0, args1, args2, args3)); + PoolerTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } } #endregion #region Pooler Scope [NonEvent] - internal long PoolerScopeEnterEvent(string message, T0 args0) + internal long TryPoolerScopeEnterEvent(string message, T0 args0) { if (Log.IsPoolerScopeEnabled()) { - return PoolerScopeEnter(string.Format(message, args0)); + return PoolerScopeEnter(string.Format(message, args0?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal void PoolerScopeLeaveEvent(long scopeId) + internal void TryPoolerScopeLeaveEvent(long scopeId) { if (Log.IsPoolerScopeEnabled()) { @@ -542,8 +580,36 @@ internal void PoolerScopeLeaveEvent(long scopeId) #endregion #region AdvancedTrace + + #region AdvancedTraces without if statements + [NonEvent] + internal void AdvancedTraceEvent(string message, T0 args0) + { + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr)); + } + + [NonEvent] + internal void AdvancedTraceEvent(string message, T0 args0, T1 args1) + { + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); + } + [NonEvent] - internal void AdvancedTraceEvent(string message) + internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2) + { + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); + } + + [NonEvent] + internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); + } + #endregion + + #region AdvancedTraces with if statements + [NonEvent] + internal void TryAdvancedTraceEvent(string message) { if (Log.IsAdvancedTraceOn()) { @@ -552,71 +618,71 @@ internal void AdvancedTraceEvent(string message) } [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0) + internal void TryAdvancedTraceEvent(string message, T0 args0) { if (Log.IsAdvancedTraceOn()) { - AdvancedTrace(string.Format(message, args0)); + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr)); } } [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1) + internal void TryAdvancedTraceEvent(string message, T0 args0, T1 args1) { if (Log.IsAdvancedTraceOn()) { - AdvancedTrace(string.Format(message, args0, args1)); + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2) + internal void TryAdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsAdvancedTraceOn()) { - AdvancedTrace(string.Format(message, args0, args1, args2)); + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } } [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void TryAdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsAdvancedTraceOn()) { - AdvancedTrace(string.Format(message, args0, args1, args2, args3)); + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } } [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) + internal void TryAdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) { if (Log.IsAdvancedTraceOn()) { - AdvancedTrace(string.Format(message, args0, args1, args2, args3, args4, args5)); + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr, args4?.ToString() ?? NullStr, args5?.ToString() ?? NullStr)); } } [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5, T6 args6, T7 args7) + internal void TryAdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5, T6 args6, T7 args7) { if (Log.IsAdvancedTraceOn()) { - AdvancedTrace(string.Format(message, args0, args1, args2, args3, args4, args5, args6, args7)); + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr, args4?.ToString() ?? NullStr, args5?.ToString() ?? NullStr, args6?.ToString() ?? NullStr, args7?.ToString() ?? NullStr)); } } [NonEvent] - internal long AdvancedScopeEnterEvent(string message, T0 args0) + internal long TryAdvancedScopeEnterEvent(string message, T0 args0) { if (Log.IsAdvancedTraceOn()) { - return AdvancedScopeEnter(string.Format(message, args0)); + return AdvancedScopeEnter(string.Format(message, args0?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal void AdvanceScopeLeave(long scopeId) + internal void TryAdvanceScopeLeave(long scopeId) { if (Log.IsAdvancedTraceOn()) { @@ -625,67 +691,66 @@ internal void AdvanceScopeLeave(long scopeId) } [NonEvent] - internal void AdvancedTraceBinEvent(string message, T0 args0, T1 args1) + internal void TryAdvancedTraceBinEvent(string message, T0 args0, T1 args1) { if (Log.IsAdvancedTraceOn()) { - AdvancedTraceBin(string.Format(message, args0, args1)); + AdvancedTraceBin(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void AdvancedTraceErrorEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4) + internal void TryAdvancedTraceErrorEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4) { if (Log.IsAdvancedTraceOn()) { - AdvancedTraceError(string.Format(message, args0, args1, args2, args3, args4)); + AdvancedTraceError(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr, args4?.ToString() ?? NullStr)); } } #endregion + #endregion + #region Correlation Trace [NonEvent] - internal void CorrelationTraceEvent(string message, T0 args0) + internal void TryCorrelationTraceEvent(string message, T0 args0) { if (Log.IsCorrelationEnabled()) { - CorrelationTrace(string.Format(message, args0?.ToString() ?? "Null")); + CorrelationTrace(string.Format(message, args0?.ToString() ?? NullStr)); } } [NonEvent] - internal void CorrelationTraceEvent(string message, T0 args0, T1 args1) + internal void TryCorrelationTraceEvent(string message, T0 args0, T1 args1) { if (Log.IsCorrelationEnabled()) { - CorrelationTrace(string.Format(message, args0?.ToString() ?? "Null", args1?.ToString() ?? "Null")); + CorrelationTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void CorrelationTraceEvent(string message, T0 args0, T1 args1, T2 args2) + internal void TryCorrelationTraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsCorrelationEnabled()) { - CorrelationTrace(string.Format(message, args0?.ToString() ?? "Null", args1?.ToString() ?? "Null", args2?.ToString() ?? "Null")); + CorrelationTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } } #endregion - #region State Dump + #region State Dump without if statements [NonEvent] internal void StateDumpEvent(string message, T0 args0, T1 args1) { - if (Log.IsStateDumpEnabled()) - { - StateDump(string.Format(message, args0, args1)); - } + StateDump(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } #endregion #region SNI Trace [NonEvent] - internal void SNITraceEvent(string message) + internal void TrySNITraceEvent(string message) { if (Log.IsSNITraceEnabled()) { @@ -694,54 +759,54 @@ internal void SNITraceEvent(string message) } [NonEvent] - internal void SNITraceEvent(string message, T0 args0) + internal void TrySNITraceEvent(string message, T0 args0) { if (Log.IsSNITraceEnabled()) { - SNITrace(string.Format(message, args0)); + SNITrace(string.Format(message, args0?.ToString() ?? NullStr)); } } [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1) + internal void TrySNITraceEvent(string message, T0 args0, T1 args1) { if (Log.IsSNITraceEnabled()) { - SNITrace(string.Format(message, args0, args1)); + SNITrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1, T2 args2) + internal void TrySNITraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsSNITraceEnabled()) { - SNITrace(string.Format(message, args0, args1, args2)); + SNITrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } } [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void TrySNITraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsSNITraceEnabled()) { - SNITrace(string.Format(message, args0, args1, args2, args3)); + SNITrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } } [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4) + internal void TrySNITraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4) { if (Log.IsSNITraceEnabled()) { - SNITrace(string.Format(message, args0, args1, args2, args3, args4)); + SNITrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr, args4?.ToString() ?? NullStr)); } } #endregion #region SNI Scope [NonEvent] - internal long SNIScopeEnterEvent(string message) + internal long TrySNIScopeEnterEvent(string message) { if (Log.IsSNIScopeEnabled()) { @@ -751,47 +816,47 @@ internal long SNIScopeEnterEvent(string message) } [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0) + internal long TrySNIScopeEnterEvent(string message, T0 args0) { if (Log.IsSNIScopeEnabled()) { - return SNIScopeEnter(string.Format(message, args0)); + return SNIScopeEnter(string.Format(message, args0?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0, T1 args1) + internal long TrySNIScopeEnterEvent(string message, T0 args0, T1 args1) { if (Log.IsSNIScopeEnabled()) { - return SNIScopeEnter(string.Format(message, args0, args1)); + return SNIScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) + internal long TrySNIScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsSNIScopeEnabled()) { - return SNIScopeEnter(string.Format(message, args0, args1, args2)); + return SNIScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal long TrySNIScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsSNIScopeEnabled()) { - return SNIScopeEnter(string.Format(message, args0, args1, args2, args3)); + return SNIScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal void SNIScopeLeaveEvent(long scopeId) + internal void TrySNIScopeLeaveEvent(long scopeId) { if (Log.IsSNIScopeEnabled()) { diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientLogger.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientLogger.cs index 5150862224..aaec458db8 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientLogger.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientLogger.cs @@ -13,26 +13,26 @@ internal enum LogLevel { Info = 0, Warning, - Error + Error } /// public void LogInfo(string type, string method, string message) { - SqlClientEventSource.Log.TraceEvent("{3}", type, method, LogLevel.Info, message); + SqlClientEventSource.Log.TryTraceEvent("{3}", type, method, LogLevel.Info, message); } /// public void LogWarning(string type, string method, string message) { Console.Out.WriteLine(message); - SqlClientEventSource.Log.TraceEvent("{3}", type, method, LogLevel.Warning, message); + SqlClientEventSource.Log.TryTraceEvent("{3}", type, method, LogLevel.Warning, message); } /// public void LogError(string type, string method, string message) { - SqlClientEventSource.Log.TraceEvent("{3}", type, method, LogLevel.Error, message); + SqlClientEventSource.Log.TryTraceEvent("{3}", type, method, LogLevel.Error, message); } ///