From 7216e84fb9819b56df1d51ca13969d4f89bf507a Mon Sep 17 00:00:00 2001 From: Benjamin Russell Date: Fri, 9 Aug 2024 12:40:30 -0500 Subject: [PATCH] `null != x` => `x != null` (#2751) --- .../Data/ProviderBase/DbConnectionFactory.cs | 42 +++--- .../Data/ProviderBase/DbConnectionInternal.cs | 6 +- .../Interop/SNINativeMethodWrapper.Windows.cs | 4 +- .../Data/Common/DbConnectionOptions.cs | 6 +- .../Data/ProviderBase/DbConnectionFactory.cs | 2 +- .../Data/ProviderBase/DbConnectionInternal.cs | 22 ++-- .../Data/ProviderBase/DbConnectionPool.cs | 54 ++++---- .../ProviderBase/DbConnectionPoolIdentity.cs | 2 +- .../SqlClient/AlwaysEncryptedHelperClasses.cs | 6 +- ...uthenticationProviderManager.NetCoreApp.cs | 2 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 16 +-- .../Microsoft/Data/SqlClient/SqlCommand.cs | 88 ++++++------- .../Microsoft/Data/SqlClient/SqlConnection.cs | 38 +++--- .../Data/SqlClient/SqlConnectionFactory.cs | 22 ++-- .../Data/SqlClient/SqlConnectionHelper.cs | 24 ++-- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 54 ++++---- .../Data/SqlClient/SqlDelegatedTransaction.cs | 16 +-- .../SqlClient/SqlInternalConnectionTds.cs | 34 ++--- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 93 +++++++------- .../Data/SqlClient/TdsParserHelperClasses.cs | 2 +- .../SqlClient/TdsParserStateObject.netcore.cs | 12 +- .../SqlClient/TdsParserStateObjectNative.cs | 2 +- .../Data/Common/NameValuePermission.cs | 42 +++--- .../Data/Common/DBConnectionString.cs | 22 ++-- .../Data/Common/DbConnectionOptions.cs | 10 +- .../src/Microsoft/Data/Common/GreenMethods.cs | 4 +- .../Data/Interop/SNINativeMethodWrapper.cs | 6 +- .../Microsoft/Data/ProviderBase/DbBuffer.cs | 18 +-- .../Data/ProviderBase/DbConnectionFactory.cs | 44 +++---- .../Data/ProviderBase/DbConnectionInternal.cs | 28 ++-- .../Data/ProviderBase/DbConnectionPool.cs | 54 ++++---- .../ProviderBase/DbConnectionPoolCounters.cs | 14 +- .../ProviderBase/DbConnectionPoolIdentity.cs | 2 +- .../SqlAuthenticationProviderManager.cs | 2 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 16 +-- .../Data/SqlClient/SqlClientPermission.cs | 32 ++--- .../SqlClient/SqlClientWrapperSmiStream.cs | 4 +- .../SqlClientWrapperSmiStreamChars.cs | 4 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 120 +++++++++--------- .../Microsoft/Data/SqlClient/SqlConnection.cs | 58 +++++---- .../Data/SqlClient/SqlConnectionFactory.cs | 24 ++-- .../Data/SqlClient/SqlConnectionHelper.cs | 26 ++-- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 104 +++++++-------- .../Data/SqlClient/SqlDataReaderSmi.cs | 2 +- .../Data/SqlClient/SqlDelegatedTransaction.cs | 16 +-- .../SqlClient/SqlInternalConnectionSmi.cs | 57 +++++---- .../SqlClient/SqlInternalConnectionTds.cs | 40 +++--- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 95 +++++++------- .../Data/SqlClient/TdsParserHelperClasses.cs | 8 +- .../SqlClient/TdsParserStateObject.netfx.cs | 14 +- .../src/Microsoft/Data/Common/AdapterUtil.cs | 6 +- .../Data/Common/DbConnectionOptions.Common.cs | 29 +++-- .../Data/Common/DbConnectionStringCommon.cs | 20 ++- .../Microsoft/Data/Common/NameValuePair.cs | 2 +- .../src/Microsoft/Data/DataException.cs | 4 +- .../ProviderBase/DbConnectionPoolGroup.cs | 8 +- .../ProviderBase/DbReferenceCollection.cs | 2 +- .../Data/Sql/SqlNotificationRequest.cs | 4 +- .../ActiveDirectoryAuthenticationProvider.cs | 4 +- .../Data/SqlClient/SQLFallbackDNSCache.cs | 4 +- .../SqlClient/Server/MemoryRecordBuffer.cs | 2 +- .../Data/SqlClient/Server/MetadataUtilsSmi.cs | 8 +- .../SqlClient/Server/SmiEventSink_Default.cs | 14 +- .../Server/SmiEventSink_Default.netfx.cs | 2 +- .../Data/SqlClient/Server/SmiGettersStream.cs | 6 +- .../Data/SqlClient/Server/SmiSettersStream.cs | 6 +- .../Data/SqlClient/Server/SqlMetaData.cs | 12 +- .../Data/SqlClient/Server/SqlRecordBuffer.cs | 6 +- .../Data/SqlClient/Server/ValueUtilsSmi.cs | 2 +- .../SqlClient/Server/ValueUtilsSmi.netfx.cs | 2 +- .../SqlAeadAes256CbcHmac256Algorithm.cs | 2 +- .../src/Microsoft/Data/SqlClient/SqlBuffer.cs | 4 +- ...SqlClientEncryptionAlgorithmFactoryList.cs | 2 +- .../Microsoft/Data/SqlClient/SqlCommandSet.cs | 14 +- .../SqlConnectionPoolGroupProviderInfo.cs | 2 +- .../Data/SqlClient/SqlConnectionString.cs | 10 +- .../Data/SqlClient/SqlDataAdapter.cs | 14 +- .../Microsoft/Data/SqlClient/SqlDependency.cs | 22 ++-- .../Data/SqlClient/SqlDependencyListener.cs | 20 +-- .../Data/SqlClient/SqlDependencyUtils.cs | 6 +- .../src/Microsoft/Data/SqlClient/SqlEnums.cs | 2 +- .../Microsoft/Data/SqlClient/SqlException.cs | 2 +- .../Data/SqlClient/SqlInfoMessageEvent.cs | 2 +- .../Data/SqlClient/SqlInternalConnection.cs | 30 ++--- .../Data/SqlClient/SqlInternalTransaction.cs | 4 +- .../Microsoft/Data/SqlClient/SqlParameter.cs | 18 +-- .../Microsoft/Data/SqlClient/SqlStatistics.cs | 4 +- .../Data/SqlClient/SqlTransaction.Common.cs | 4 +- .../src/Microsoft/Data/SqlClient/SqlUtil.cs | 2 +- .../SqlClient/TdsParserSafeHandles.Windows.cs | 4 +- .../Data/SqlClient/TdsParserSessionPool.cs | 7 +- .../Data/SqlClient/TdsParserStateObject.cs | 2 +- .../Data/SqlClient/TdsParserStaticMethods.cs | 2 +- .../Data/SqlClient/TdsValueSetter.cs | 2 +- ...ncryptionCertificateStoreProviderShould.cs | 2 +- .../AlwaysEncryptedTests/Utility.cs | 6 +- .../ManualTests/DataCommon/DataTestUtility.cs | 6 +- .../MultipleResultsTest.cs | 6 +- .../SQL/AdapterTest/AdapterTest.cs | 12 +- .../DataClassificationTest.cs | 2 +- .../SQL/ParameterTest/SteTypeBoundaries.cs | 2 +- .../ManualTests/SQL/ParameterTest/TvpTest.cs | 8 +- .../SqlBulkCopyTest/InvalidAccessFromEvent.cs | 2 +- 103 files changed, 900 insertions(+), 883 deletions(-) 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 d1b7bf1ca0..065035113d 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 @@ -55,7 +55,7 @@ public void ClearAllPools() foreach (KeyValuePair entry in connectionPoolGroups) { DbConnectionPoolGroup poolGroup = entry.Value; - if (null != poolGroup) + if (poolGroup != null) { poolGroup.Clear(); } @@ -69,7 +69,7 @@ public void ClearPool(DbConnection connection) using (TryEventScope.Create(" {0}", GetObjectId(connection))) { DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); - if (null != poolGroup) + if (poolGroup != null) { poolGroup.Clear(); } @@ -98,15 +98,15 @@ internal virtual DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(D internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) { - Debug.Assert(null != owningConnection, "null owningConnection?"); - Debug.Assert(null != poolGroup, "null poolGroup?"); + Debug.Assert(owningConnection != null, "null owningConnection?"); + Debug.Assert(poolGroup != null, "null poolGroup?"); DbConnectionOptions connectionOptions = poolGroup.ConnectionOptions; DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo; DbConnectionPoolKey poolKey = poolGroup.PoolKey; DbConnectionInternal newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions); - if (null != newConnection) + if (newConnection != null) { SqlClientEventSource.Log.HardConnectRequest(); newConnection.MakeNonPooledObject(owningConnection); @@ -117,11 +117,11 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) { - Debug.Assert(null != pool, "null pool?"); + Debug.Assert(pool != null, "null pool?"); DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo; DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions); - if (null != newConnection) + if (newConnection != null) { SqlClientEventSource.Log.HardConnectRequest(); newConnection.MakePooledConnection(pool); @@ -167,8 +167,8 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti { // if poolgroup is disabled, it will be replaced with a new entry - Debug.Assert(null != owningObject, "null owningObject?"); - Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?"); + Debug.Assert(owningObject != null, "null owningObject?"); + Debug.Assert(connectionPoolGroup != null, "null connectionPoolGroup?"); // It is possible that while the outer connection object has // been sitting around in a closed and unused state in some long @@ -179,7 +179,7 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti // re-create the pool entry whenever it's disabled. // however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work - if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) + if (connectionPoolGroup.IsDisabled && connectionPoolGroup.PoolGroupOptions != null) { SqlClientEventSource.Log.TryTraceEvent(" {0}, DisabledPoolGroup={1}", ObjectID, connectionPoolGroup?.ObjectID); @@ -188,10 +188,10 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti // get the string to hash on again DbConnectionOptions connectionOptions = connectionPoolGroup.ConnectionOptions; - Debug.Assert(null != connectionOptions, "prevent expansion of connectionString"); + Debug.Assert(connectionOptions != null, "prevent expansion of connectionString"); connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions); - Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?"); + Debug.Assert(connectionPoolGroup != null, "null connectionPoolGroup?"); SetConnectionPoolGroup(owningObject, connectionPoolGroup); } DbConnectionPool connectionPool = connectionPoolGroup.GetConnectionPool(this); @@ -207,7 +207,7 @@ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, D DbConnectionPoolGroup connectionPoolGroup; Dictionary connectionPoolGroups = _connectionPoolGroups; - if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))) + if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && connectionPoolGroup.PoolGroupOptions != null)) { // If we can't find an entry for the connection string in // our collection of pool entries, then we need to create a @@ -238,7 +238,7 @@ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, D // We don't support connection pooling on Win9x if (poolOptions == null) { - if (null != connectionPoolGroup) + if (connectionPoolGroup != null) { // reusing existing pool option in case user originally used SetConnectionPoolOptions poolOptions = connectionPoolGroup.PoolGroupOptions; @@ -276,8 +276,8 @@ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, D Debug.Assert(!connectionPoolGroup.IsDisabled, "Disabled pool entry discovered"); } } - Debug.Assert(null != connectionPoolGroup, "how did we not create a pool entry?"); - Debug.Assert(null != userConnectionOptions, "how did we not have user connection options?"); + Debug.Assert(connectionPoolGroup != null, "how did we not create a pool entry?"); + Debug.Assert(userConnectionOptions != null, "how did we not have user connection options?"); } else if (userConnectionOptions == null) { @@ -303,7 +303,7 @@ private void PruneConnectionPoolGroups(object state) DbConnectionPool[] poolsToRelease = _poolsToRelease.ToArray(); foreach (DbConnectionPool pool in poolsToRelease) { - if (null != pool) + if (pool != null) { pool.Clear(); @@ -328,7 +328,7 @@ private void PruneConnectionPoolGroups(object state) DbConnectionPoolGroup[] poolGroupsToRelease = _poolGroupsToRelease.ToArray(); foreach (DbConnectionPoolGroup poolGroup in poolGroupsToRelease) { - if (null != poolGroup) + if (poolGroup != null) { int poolsLeft = poolGroup.Clear(); // may add entries to _poolsToRelease @@ -353,7 +353,7 @@ private void PruneConnectionPoolGroups(object state) foreach (KeyValuePair entry in connectionPoolGroups) { - if (null != entry.Value) + if (entry.Value != null) { Debug.Assert(!entry.Value.IsDisabled, "Disabled pool entry discovered"); @@ -380,7 +380,7 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) // Queue the pool up for release -- we'll clear it out and dispose // of it as the last part of the pruning timer callback so we don't // do it with the pool entry or the pool collection locked. - Debug.Assert(null != pool, "null pool?"); + Debug.Assert(pool != null, "null pool?"); // set the pool to the shutdown state to force all active // connections to be automatically disposed when they @@ -401,7 +401,7 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { - Debug.Assert(null != poolGroup, "null poolGroup?"); + Debug.Assert(poolGroup != null, "null poolGroup?"); 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 107b5c1850..fd5e3e2848 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 @@ -300,7 +300,7 @@ internal void MakePooledConnection(DbConnectionPool connectionPool) internal void NotifyWeakReference(int message) { DbReferenceCollection referenceCollection = ReferenceCollection; - if (null != referenceCollection) + if (referenceCollection != null) { referenceCollection.Notify(message); } @@ -418,7 +418,7 @@ internal void PostPop(DbConnection newOwner) 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) + if (Pool != null) { if (0 != _pooledCount) { @@ -434,7 +434,7 @@ internal void PostPop(DbConnection newOwner) internal void RemoveWeakReference(object value) { DbReferenceCollection referenceCollection = ReferenceCollection; - if (null != referenceCollection) + if (referenceCollection != null) { referenceCollection.Remove(value); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Interop/SNINativeMethodWrapper.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Interop/SNINativeMethodWrapper.Windows.cs index 8483edd42c..8ba17db53d 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Interop/SNINativeMethodWrapper.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Interop/SNINativeMethodWrapper.Windows.cs @@ -505,10 +505,10 @@ internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref Sni_Consumer_Info native_consumerInfo) { native_consumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize; - native_consumerInfo.fnReadComp = null != consumerInfo.readDelegate + native_consumerInfo.fnReadComp = consumerInfo.readDelegate != null ? Marshal.GetFunctionPointerForDelegate(consumerInfo.readDelegate) : IntPtr.Zero; - native_consumerInfo.fnWriteComp = null != consumerInfo.writeDelegate + native_consumerInfo.fnWriteComp = consumerInfo.writeDelegate != null ? Marshal.GetFunctionPointerForDelegate(consumerInfo.writeDelegate) : IntPtr.Zero; native_consumerInfo.ConsumerKey = consumerInfo.key; diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionOptions.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionOptions.cs index 693717c7d7..759696d471 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionOptions.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionOptions.cs @@ -15,7 +15,7 @@ internal string ExpandAttachDbFileName(string replacementValue) int copyPosition = 0; StringBuilder builder = new(_usersConnectionString.Length); - for (NameValuePair current = _keyChain; null != current; current = current.Next) + for (NameValuePair current = _keyChain; current != null; current = current.Next) { if (string.Equals(current.Name, DbConnectionStringKeywords.AttachDBFilename, StringComparison.InvariantCultureIgnoreCase)) { @@ -38,12 +38,12 @@ internal string ExpandAttachDbFileName(string replacementValue) internal static string ExpandDataDirectory(string keyword, string value) { string fullPath = null; - if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) + if (value != null && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) { // find the replacement path object rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory"); var rootFolderPath = (rootFolderObject as string); - if ((null != rootFolderObject) && rootFolderPath == null) + if (rootFolderObject != null && rootFolderPath == null) { throw ADP.InvalidDataDirectory(); } 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 bbf59fbb47..ba14e4ffb7 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 @@ -20,7 +20,7 @@ internal abstract partial class DbConnectionFactory internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection) { - Debug.Assert(null != owningConnection, "null owningConnection?"); + Debug.Assert(owningConnection != null, "null owningConnection?"); DbConnectionPoolGroup poolGroup; DbConnectionPool connectionPool; 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 056576f7fa..6458d11f48 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 @@ -37,8 +37,8 @@ protected internal Transaction EnlistedTransaction set { Transaction currentEnlistedTransaction = _enlistedTransaction; - if ((currentEnlistedTransaction == null && (null != value)) - || ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value))) + if ((currentEnlistedTransaction == null && value != null) + || (currentEnlistedTransaction != null && !currentEnlistedTransaction.Equals(value))) { // WebData 20000024 // Pay attention to the order here: @@ -53,7 +53,7 @@ protected internal Transaction EnlistedTransaction Transaction previousTransactionClone = null; try { - if (null != value) + if (value != null) { valueClone = value.Clone(); } @@ -88,12 +88,12 @@ protected internal Transaction EnlistedTransaction // we really need to dispose our clones; they may have // native resources and GC may not happen soon enough. // VSDevDiv 479564: don't dispose if still holding reference in _enlistedTransaction - if (null != previousTransactionClone && + if (previousTransactionClone != null && !object.ReferenceEquals(previousTransactionClone, _enlistedTransaction)) { previousTransactionClone.Dispose(); } - if (null != valueClone && !object.ReferenceEquals(valueClone, _enlistedTransaction)) + if (valueClone != null && !object.ReferenceEquals(valueClone, _enlistedTransaction)) { valueClone.Dispose(); } @@ -104,7 +104,7 @@ protected internal Transaction EnlistedTransaction // against multiple concurrent calls to enlist, which really // isn't supported anyway. - if (null != value) + if (value != null) { SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Enlisting.", ObjectID, value.GetHashCode()); TransactionOutcomeEnlist(value); @@ -251,7 +251,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac // if the DbConnectionInternal derived class needs to close the connection it should // delegate to the DbConnection if one exists or directly call dispose // DbConnection owningObject = (DbConnection)Owner; - // if (null != owningObject) { + // if (owningObject != null) { // owningObject.Close(); // force the closed state on the outer object. // } // else { @@ -261,8 +261,8 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac //////////////////////////////////////////////////////////////// // DON'T MESS WITH THIS CODE UNLESS YOU KNOW WHAT YOU'RE DOING! //////////////////////////////////////////////////////////////// - Debug.Assert(null != owningObject, "null owningObject"); - Debug.Assert(null != connectionFactory, "null connectionFactory"); + Debug.Assert(owningObject != null, "null owningObject"); + Debug.Assert(connectionFactory != null, "null connectionFactory"); SqlClientEventSource.Log.TryPoolerTraceEvent(" {0} Closing.", ObjectID); // if an exception occurs after the state change but before the try block @@ -288,7 +288,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac // The singleton closed classes won't have owners and // connection pools, and we won't want to put them back // into the pool. - if (null != connectionPool) + if (connectionPool != null) { connectionPool.PutObject(this, owningObject); // PutObject calls Deactivate for us... // NOTE: Before we leave the PutObject call, another @@ -468,7 +468,7 @@ internal void CleanupConnectionOnTransactionCompletion(Transaction transaction) DetachTransaction(transaction, false); DbConnectionPool pool = Pool; - if (null != pool) + if (pool != null) { pool.TransactionEnded(transaction, this); } 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 e8c2ccbc97..745ca55c0e 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 @@ -37,7 +37,7 @@ internal TransactedConnectionList(int initialAllocation, Transaction tx) : base( internal void Dispose() { - if (null != _transaction) + if (_transaction != null) { _transaction.Dispose(); } @@ -70,7 +70,7 @@ sealed private class TransactedConnectionPool internal TransactedConnectionPool(DbConnectionPool pool) { - Debug.Assert(null != pool, "null pool?"); + Debug.Assert(pool != null, "null pool?"); _pool = pool; _transactedCxns = new Dictionary(); @@ -95,7 +95,7 @@ internal DbConnectionPool Pool internal DbConnectionInternal GetTransactedObject(Transaction transaction) { - Debug.Assert(null != transaction, "null transaction?"); + Debug.Assert(transaction != null, "null transaction?"); DbConnectionInternal transactedObject = null; @@ -131,7 +131,7 @@ internal DbConnectionInternal GetTransactedObject(Transaction transaction) } } - if (null != transactedObject) + if (transactedObject != null) { SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } @@ -140,8 +140,8 @@ internal DbConnectionInternal GetTransactedObject(Transaction transaction) internal void PutTransactedObject(Transaction transaction, DbConnectionInternal transactedObject) { - Debug.Assert(null != transaction, "null transaction?"); - Debug.Assert(null != transactedObject, "null transactedObject?"); + Debug.Assert(transaction != null, "null transaction?"); + Debug.Assert(transactedObject != null, "null transactedObject?"); TransactedConnectionList connections; bool txnFound = false; @@ -213,7 +213,7 @@ internal void PutTransactedObject(Transaction transaction, DbConnectionInternal } finally { - if (null != transactionClone) + if (transactionClone != null) { if (newConnections != null) { @@ -411,9 +411,9 @@ internal DbConnectionPool( DbConnectionPoolIdentity identity, DbConnectionPoolProviderInfo connectionPoolProviderInfo) { - Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup"); + Debug.Assert(connectionPoolGroup != null, "null connectionPoolGroup"); - if ((null != identity) && identity.IsRestricted) + if (identity != null && identity.IsRestricted) { throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToPoolOnRestrictedToken); } @@ -565,7 +565,7 @@ internal bool UseLoadBalancing private bool UsingIntegrateSecurity { - get { return (null != _identity && DbConnectionPoolIdentity.NoIdentity != _identity); } + get { return _identity != null && DbConnectionPoolIdentity.NoIdentity != _identity; } } private void CleanupCallback(object state) @@ -688,7 +688,7 @@ internal void Clear() { obj = _objectList[i]; - if (null != obj) + if (obj != null) { obj.DoNotPoolThisConnection(); } @@ -892,7 +892,7 @@ private void DeactivateObject(DbConnectionInternal obj) // thread. Transaction transaction = obj.EnlistedTransaction; - if (null != transaction) + if (transaction != null) { // NOTE: we're not locking on _state, so it's possible that its // value could change between the conditional check and here. @@ -1227,7 +1227,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj { // Ensure that we release this waiter, regardless // of any exceptions that may be thrown. - if (null != obj) + if (obj != null) { Interlocked.Decrement(ref _waitCount); } @@ -1304,7 +1304,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 (obj != null && obj.IsAccessTokenExpired) { DestroyObject(obj); obj = null; @@ -1312,7 +1312,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj } while (obj == null); } - if (null != obj) + if (obj != null) { PrepareConnection(owningObject, obj, transaction); } @@ -1390,7 +1390,7 @@ private DbConnectionInternal GetFromGeneralPool() // following assert to fire, which really mucks up stress against // checked bits. - if (null != obj) + if (obj != null) { SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Popped from general pool.", ObjectID, obj.ObjectID); SqlClientEventSource.Log.ExitFreeConnection(); @@ -1403,11 +1403,11 @@ private DbConnectionInternal GetFromTransactedPool(out Transaction transaction) transaction = ADP.GetCurrentTransaction(); DbConnectionInternal obj = null; - if (null != transaction && null != _transactedConnectionPool) + if (transaction != null && _transactedConnectionPool != null) { obj = _transactedConnectionPool.GetTransactedObject(transaction); - if (null != obj) + if (obj != null) { SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Popped from transacted pool.", ObjectID, obj.ObjectID); SqlClientEventSource.Log.ExitFreeConnection(); @@ -1505,7 +1505,7 @@ private void PoolCreateRequest(object state) } // We do not need to check error flag here, since we know if // CreateObject returned null, we are in error case. - if (null != newObj) + if (newObj != null) { PutNewObject(newObj); } @@ -1559,7 +1559,7 @@ private void PoolCreateRequest(object state) internal void PutNewObject(DbConnectionInternal obj) { - Debug.Assert(null != obj, "why are we adding a null object to the pool?"); + Debug.Assert(obj != null, "why are we adding a null object to the pool?"); // Debug.Assert(obj.CanBePooled, "non-poolable object in pool"); SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Pushing to general pool.", ObjectID, obj.ObjectID); @@ -1570,7 +1570,7 @@ internal void PutNewObject(DbConnectionInternal obj) internal void PutObject(DbConnectionInternal obj, object owningObject) { - Debug.Assert(null != obj, "null obj?"); + Debug.Assert(obj != null, "null obj?"); SqlClientEventSource.Log.SoftDisconnectRequest(); // Once a connection is closing (which is the state that we're in at @@ -1595,7 +1595,7 @@ internal void PutObject(DbConnectionInternal obj, object owningObject) internal void PutObjectFromTransactedPool(DbConnectionInternal obj) { - Debug.Assert(null != obj, "null pooledObject?"); + Debug.Assert(obj != null, "null pooledObject?"); Debug.Assert(obj.EnlistedTransaction == null, "pooledObject is still enlisted?"); // called by the transacted connection pool , once it's removed the @@ -1643,7 +1643,7 @@ private bool ReclaimEmancipatedObjects() { DbConnectionInternal obj = _objectList[i]; - if (null != obj) + if (obj != null) { bool locked = false; @@ -1712,7 +1712,7 @@ internal void Shutdown() // deactivate timer callbacks Timer t = _cleanupTimer; _cleanupTimer = null; - if (null != t) + if (t != null) { t.Dispose(); } @@ -1724,8 +1724,8 @@ internal void Shutdown() // other objects is unnecessary (hence the asymmetry of Ended but no Begin) internal void TransactionEnded(Transaction transaction, DbConnectionInternal transactedObject) { - Debug.Assert(null != transaction, "null transaction?"); - Debug.Assert(null != transactedObject, "null transactedObject?"); + Debug.Assert(transaction != null, "null transaction?"); + Debug.Assert(transactedObject != null, "null transactedObject?"); // Note: connection may still be associated with transaction due to Explicit Unbinding requirement. SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); @@ -1735,7 +1735,7 @@ internal void TransactionEnded(Transaction transaction, DbConnectionInternal tra // the connection from it's list, then we put the connection back in // general circulation. TransactedConnectionPool transactedConnectionPool = _transactedConnectionPool; - if (null != transactedConnectionPool) + if (transactedConnectionPool != null) { transactedConnectionPool.TransactionEnded(transaction, transactedObject); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs index f1b985a6de..7b650bd6f7 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs @@ -30,7 +30,7 @@ internal bool IsRestricted override public bool Equals(object value) { bool result = ((this == NoIdentity) || (this == value)); - if (!result && (null != value)) + if (!result && value != null) { DbConnectionPoolIdentity that = ((DbConnectionPoolIdentity)value); result = ((_sidString == that._sidString) && (_isRestricted == that._isRestricted) && (_isNetwork == that._isNetwork)); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedHelperClasses.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedHelperClasses.cs index 0a4fe787a9..6c09532f6b 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedHelperClasses.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedHelperClasses.cs @@ -423,7 +423,7 @@ internal SqlCipherMetadata(SqlTceCipherInfoEntry sqlTceCipherInfoEntry, /// internal bool IsAlgorithmInitialized() { - return (null != _sqlClientEncryptionAlgorithm) ? true : false; + return _sqlClientEncryptionAlgorithm != null ? true : false; } } @@ -439,7 +439,7 @@ internal partial class SqlMetaDataPriv /// internal bool IsAlgorithmInitialized() { - if (null != cipherMD) + if (cipherMD != null) { return cipherMD.IsAlgorithmInitialized(); } @@ -455,7 +455,7 @@ internal byte NormalizationRuleVersion { get { - if (null != cipherMD) + if (cipherMD != null) { return cipherMD.NormalizationRuleVersion; } 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 b92a30905e..3775daf9ad 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 @@ -119,7 +119,7 @@ private static T FetchConfigurationSection(string name) { Type t = typeof(T); object section = ConfigurationManager.GetSection(name); - if (null != section) + if (section != null) { if (section is ConfigurationSection configSection && configSection.GetType() == t) { 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 68221caf66..93bf6e119f 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 @@ -385,7 +385,7 @@ internal SqlStatistics Statistics { get { - if (null != _connection) + if (_connection != null) { if (_connection.StatisticsEnabled) { @@ -683,7 +683,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i { updateBulkCommandText.Append(" COLLATE " + collation_name.Value); // Compare collations only if the collation value was set on the metadata - if (null != _sqlDataReaderRowSource && metadata.collation != null) + if (_sqlDataReaderRowSource != null && metadata.collation != null) { // On SqlDataReader we can verify the sourcecolumn collation! int sourceColumnId = _localColumnMappings[assocId]._internalSourceColumnOrdinal; @@ -847,7 +847,7 @@ private void Dispose(bool disposing) try { Debug.Assert(_internalTransaction == null, "Internal transaction exists during dispose"); - if (null != _internalTransaction) + if (_internalTransaction != null) { _internalTransaction.Rollback(); _internalTransaction.Dispose(); @@ -922,7 +922,7 @@ private object GetValueFromSourceRow(int destRowIndex, out bool isSqlType, out b } } // SqlDataReader-specific logic - else if (null != _sqlDataReaderRowSource) + else if (_sqlDataReaderRowSource != null) { if (_currentRowMetadata[destRowIndex].IsSqlType) { @@ -1297,7 +1297,7 @@ private void CreateOrValidateConnection(string method) // If we have a transaction, check to ensure that the active // connection property matches the connection associated with // the transaction. - if (null != _externalTransaction && _connection != _externalTransaction.Connection) + if (_externalTransaction != null && _connection != _externalTransaction.Connection) { throw ADP.TransactionConnectionMismatch(); } @@ -1340,7 +1340,7 @@ private void RunParserReliably(BulkCopySimpleResultSet bulkCopyHandler = null) private void CommitTransaction() { - if (null != _internalTransaction) + if (_internalTransaction != null) { SqlInternalConnectionTds internalConnection = _connection.GetOpenTdsConnection(); internalConnection.ThreadHasParserLockForClose = true; // In case of error, let the connection know that we have the lock @@ -1744,7 +1744,7 @@ public void WriteToServer(DataRow[] rows) statistics = SqlStatistics.StartTimer(Statistics); ResetWriteToServerGlobalVariables(); DataTable table = rows[0].Table; - Debug.Assert(null != table, "How can we have rows without a table?"); + Debug.Assert(table != null, "How can we have rows without a table?"); _rowStateToSkip = DataRowState.Deleted; // Don't allow deleted rows _rowSource = rows; _dataTableSource = table; @@ -1790,7 +1790,7 @@ public Task WriteToServerAsync(DataRow[] rows, CancellationToken cancellationTok } DataTable table = rows[0].Table; - Debug.Assert(null != table, "How can we have rows without a table?"); + Debug.Assert(table != null, "How can we have rows without a table?"); _rowStateToSkip = DataRowState.Deleted; // Don't allow deleted rows _rowSource = rows; _dataTableSource = table; 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 b238cef3cc..91d6e3e744 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 @@ -291,7 +291,7 @@ internal string CachedSetOptions } internal bool PendingAsyncOperation { - get { return (null != _cachedAsyncResult); } + get { return _cachedAsyncResult != null; } } internal string EndMethodName { @@ -496,7 +496,7 @@ private SqlCommand(SqlCommand from) : this() // Check to see if the currently set transaction has completed. If so, // null out our local reference. - if (null != _transaction && _transaction.Connection == null) + if (_transaction != null && _transaction.Connection == null) { _transaction = null; } @@ -594,7 +594,7 @@ internal SqlStatistics Statistics { get { - if (null != _activeConnection) + if (_activeConnection != null) { if (_activeConnection.StatisticsEnabled || s_diagnosticListener.IsEnabled(SqlClientCommandAfter.Name)) @@ -615,7 +615,7 @@ internal SqlStatistics Statistics get { // if the transaction object has been zombied, just return null - if ((null != _transaction) && _transaction.Connection == null) + if (_transaction != null && _transaction.Connection == null) { _transaction = null; } @@ -849,7 +849,7 @@ internal void OnStatementCompleted(int recordCount) if (0 <= recordCount) { StatementCompletedEventHandler handler = _statementCompletedEventHandler; - if (null != handler) + if (handler != null) { try { @@ -893,7 +893,7 @@ public override void Prepare() || ((System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters)))) { - if (null != Statistics) + if (Statistics != null) { Statistics.SafeIncrement(ref Statistics._prepares); } @@ -911,7 +911,7 @@ public override void Prepare() GetStateObject(); // Loop through parameters ensuring that we do not have unspecified types, sizes, scales, or precisions - if (null != _parameters) + if (_parameters != null) { int count = _parameters.Count; for (int i = 0; i < count; ++i) @@ -958,8 +958,8 @@ private void InternalPrepare() } Debug.Assert(_execType != EXECTYPE.PREPARED, "Invalid attempt to Prepare already Prepared command!"); Debug.Assert(_activeConnection != null, "must have an open connection to Prepare"); - Debug.Assert(null != _stateObj, "TdsParserStateObject should not be null"); - Debug.Assert(null != _stateObj.Parser, "TdsParser class should not be null in Command.Execute!"); + Debug.Assert(_stateObj != null, "TdsParserStateObject should not be null"); + Debug.Assert(_stateObj.Parser != null, "TdsParser class should not be null in Command.Execute!"); Debug.Assert(_stateObj.Parser == _activeConnection.Parser, "stateobject parser not same as connection parser"); Debug.Assert(false == _inPrepare, "Already in Prepare cycle, this.inPrepare should be false!"); @@ -969,7 +969,7 @@ private void InternalPrepare() _preparedConnectionCloseCount = _activeConnection.CloseCount; _preparedConnectionReconnectCount = _activeConnection.ReconnectCount; - if (null != Statistics) + if (Statistics != null) { Statistics.SafeIncrement(ref Statistics._prepares); } @@ -1065,7 +1065,7 @@ public override void Cancel() _pendingCancel = true; TdsParserStateObject stateObj = _stateObj; - if (null != stateObj) + if (stateObj != null) { stateObj.Cancel(this); } @@ -1624,7 +1624,7 @@ private object InternalEndExecuteNonQuery(IAsyncResult asyncResult, bool isInter { // otherwise, use a full-fledged execute that can handle params and stored procs SqlDataReader reader = CompleteAsyncExecuteReader(isInternal); - if (null != reader) + if (reader != null) { reader.Close(); } @@ -1651,7 +1651,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, bo { SqlClientEventSource.Log.TryTraceEvent("SqlCommand.InternalExecuteNonQuery | INFO | ObjectId {0}, Client Connection Id {1}, AsyncCommandInProgress={2}", _activeConnection?.ObjectID, _activeConnection?.ClientConnectionId, _activeConnection?.AsyncCommandInProgress); - bool isAsync = (null != completion); + bool isAsync = completion != null; usedCache = false; SqlStatistics statistics = Statistics; @@ -1674,7 +1674,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, bo { Debug.Assert(!sendToPipe, "Trying to send non-context command to pipe"); - if (null != statistics) + if (statistics != null) { if (!IsDirty && IsPrepared) { @@ -1699,7 +1699,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, bo SqlClientEventSource.Log.TryTraceEvent("SqlCommand.InternalExecuteNonQuery | INFO | Object Id {0}, RPC execute method name {1}, isAsync {2}, inRetry {3}", ObjectID, methodName, isAsync, inRetry); SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, completion, timeout, out task, out usedCache, asyncWrite, inRetry, methodName); - if (null != reader) + if (reader != null) { if (task != null) { @@ -2000,9 +2000,9 @@ private XmlReader CompleteXmlReader(SqlDataReader ds, bool isAsync = false) XmlReader xr = null; SmiExtendedMetaData[] md = ds.GetInternalSmiMetaData(); - bool isXmlCapable = (null != md && md.Length == 1 && (md[0].SqlDbType == SqlDbType.NText - || md[0].SqlDbType == SqlDbType.NVarChar - || md[0].SqlDbType == SqlDbType.Xml)); + bool isXmlCapable = (md != null && md.Length == 1 && (md[0].SqlDbType == SqlDbType.NText + || md[0].SqlDbType == SqlDbType.NVarChar + || md[0].SqlDbType == SqlDbType.Xml)); if (isXmlCapable) { @@ -2440,7 +2440,7 @@ long firstAttemptStart if (!shouldRetry) { // If we cannot retry, Reset the async state to make sure we leave a clean state. - if (null != _cachedAsyncState) + if (_cachedAsyncState != null) { _cachedAsyncState.ResetAsyncState(); } @@ -3177,7 +3177,7 @@ internal List GetColumnEncryptionCustomKeyStoreProvidersNames() // with the function below, ideally we should have support from the server for this. private static string UnquoteProcedurePart(string part) { - if ((null != part) && (2 <= part.Length)) + if (part != null && (2 <= part.Length)) { if ('[' == part[0] && ']' == part[part.Length - 1]) { @@ -3197,7 +3197,7 @@ private static string UnquoteProcedureName(string name, out object groupNumber) groupNumber = null; // Out param - initialize value to no value. string sproc = name; - if (null != sproc) + if (sproc != null) { if (char.IsDigit(sproc[sproc.Length - 1])) { // If last char is a digit, parse. @@ -3361,7 +3361,7 @@ internal void DeriveParameters() paramsCmd.Parameters.Add(new SqlParameter("@procedure_name", SqlDbType.NVarChar, 255)); paramsCmd.Parameters[0].Value = UnquoteProcedureName(parsedSProc[3], out groupNumber); // ProcedureName is 4rd element in parsed array - if (null != groupNumber) + if (groupNumber != null) { SqlParameter param = paramsCmd.Parameters.Add(new SqlParameter("@group_number", SqlDbType.Int)); param.Value = groupNumber; @@ -3585,7 +3585,7 @@ private void CheckNotificationStateAndAutoEnlist() // There is a variance in order between Start(), SqlDependency(), and Execute. This is the // best way to solve that problem. - if (null != Notification) + if (Notification != null) { if (_sqlDep != null) { @@ -3799,7 +3799,7 @@ private void PrepareTransparentEncryptionFinallyBlock(bool closeDataReader, if (closeDataReader) { // Close the data reader to reset the _stateObj - if (null != describeParameterEncryptionDataReader) + if (describeParameterEncryptionDataReader != null) { describeParameterEncryptionDataReader.Close(); } @@ -4731,7 +4731,7 @@ internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior // task is created in case of pending asynchronous write, returned SqlDataReader should not be utilized until that task is complete internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, TaskCompletionSource completion, int timeout, out Task task, out bool usedCache, bool asyncWrite = false, bool inRetry = false, [CallerMemberName] string method = "") { - bool isAsync = (null != completion); + bool isAsync = completion != null; usedCache = false; task = null; @@ -4755,7 +4755,7 @@ internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior CheckNotificationStateAndAutoEnlist(); // Only call after validate - requires non null connection! SqlStatistics statistics = Statistics; - if (null != statistics) + if (statistics != null) { if ((!this.IsDirty && this.IsPrepared && !_hiddenPrepare) || (this.IsPrepared && _execType == EXECTYPE.PREPAREPENDING)) @@ -4989,7 +4989,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // make sure we have good parameter information // prepare the command // execute - Debug.Assert(null != _activeConnection.Parser, "TdsParser class should not be null in Command.Execute!"); + Debug.Assert(_activeConnection.Parser != null, "TdsParser class should not be null in Command.Execute!"); bool inSchema = (0 != (cmdBehavior & CommandBehavior.SchemaOnly)); @@ -5129,7 +5129,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi } // turn set options ON - if (null != optionSettings) + if (optionSettings != null) { Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(optionSettings, timeout, this.Notification, _stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -5174,7 +5174,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi if (decrementAsyncCountOnFailure) { SqlInternalConnectionTds innerConnectionTds = (_activeConnection.InnerConnection as SqlInternalConnectionTds); - if (null != innerConnectionTds) + if (innerConnectionTds != null) { // it may be closed innerConnectionTds.DecrementAsyncCount(); } @@ -5315,7 +5315,7 @@ private void FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, stri _execType = EXECTYPE.PREPAREPENDING; // reset execution type to pending } - if (null != ds) + if (ds != null) { try { @@ -5419,8 +5419,8 @@ private void ValidateCommand(bool isAsync, [CallerMemberName] string method = "" // Ensure that if column encryption override was used then server supports its if (((SqlCommandColumnEncryptionSetting.UseConnectionSetting == ColumnEncryptionSetting && _activeConnection.IsColumnEncryptionSettingEnabled) || (ColumnEncryptionSetting == SqlCommandColumnEncryptionSetting.Enabled || ColumnEncryptionSetting == SqlCommandColumnEncryptionSetting.ResultSetOnly)) - && null != tdsConnection - && null != tdsConnection.Parser + && tdsConnection != null + && tdsConnection.Parser != null && !tdsConnection.Parser.IsColumnEncryptionSupported) { throw SQL.TceNotSupported(); @@ -5454,7 +5454,7 @@ private void ValidateCommand(bool isAsync, [CallerMemberName] string method = "" _activeConnection.ValidateConnectionForExecute(method, this); // Check to see if the currently set transaction has completed. If so, // null out our local reference. - if (null != _transaction && _transaction.Connection == null) + if (_transaction != null && _transaction.Connection == null) { _transaction = null; } @@ -5469,7 +5469,7 @@ private void ValidateCommand(bool isAsync, [CallerMemberName] string method = "" // if we have a transaction, check to ensure that the active // connection property matches the connection associated with // the transaction - if (null != _transaction && _activeConnection != _transaction.Connection) + if (_transaction != null && _activeConnection != _transaction.Connection) { throw ADP.TransactionConnectionMismatch(); } @@ -5499,7 +5499,7 @@ private void ValidateAsyncCommand() private void GetStateObject(TdsParser parser = null) { Debug.Assert(_stateObj == null, "StateObject not null on GetStateObject"); - Debug.Assert(null != _activeConnection, "no active connection?"); + Debug.Assert(_activeConnection != null, "no active connection?"); if (_pendingCancel) { @@ -5550,7 +5550,7 @@ private void PutStateObject() TdsParserStateObject stateObj = _stateObj; _stateObj = null; - if (null != stateObj) + if (stateObj != null) { stateObj.CloseSession(); } @@ -5640,7 +5640,7 @@ internal void OnReturnStatus(int status) object v = parameter.Value; // if the user bound a sqlint32 (the only valid one for status, use it) - if ((null != v) && (v.GetType() == typeof(SqlInt32))) + if (v != null && (v.GetType() == typeof(SqlInt32))) { parameter.Value = new SqlInt32(status); // value type } @@ -5686,7 +5686,7 @@ internal void OnReturnValue(SqlReturnValue rec, TdsParserStateObject stateObj) SqlParameter thisParam = GetParameterForOutputValueExtraction(parameters, rec.parameter, count); - if (null != thisParam) + if (thisParam != null) { // If the parameter's direction is InputOutput, Output or ReturnValue and it needs to be transparently encrypted/decrypted // then simply decrypt, deserialize and set the value. @@ -5806,7 +5806,7 @@ internal void OnReturnValue(SqlReturnValue rec, TdsParserStateObject stateObj) else if (rec.type == SqlDbType.Xml) { SqlCachedBuffer cachedBuffer = (thisParam.Value as SqlCachedBuffer); - if (null != cachedBuffer) + if (cachedBuffer != null) { thisParam.Value = cachedBuffer.ToString(); } @@ -6101,7 +6101,7 @@ private static int CountSendableParameters(SqlParameterCollection parameters) // Returns total number of parameters private static int GetParameterCount(SqlParameterCollection parameters) { - return (null != parameters) ? parameters.Count : 0; + return parameters != null ? parameters.Count : 0; } // @@ -6436,7 +6436,7 @@ internal string BuildParamList(TdsParser parser, SqlParameterCollection paramete string s = null; // deal with the sql types - if ((null != val) && (DBNull.Value != val)) + if (val != null && (DBNull.Value != val)) { s = (val as string); if (s == null) @@ -6449,7 +6449,7 @@ internal string BuildParamList(TdsParser parser, SqlParameterCollection paramete } } - if (null != s) + if (s != null) { int actualBytes = parser.GetEncodingCharLength(s, sqlParam.GetActualSize(), sqlParam.Offset, null); // if actual number of bytes is greater than the user given number of chars, use actual bytes @@ -6501,7 +6501,7 @@ private static string QuoteIdentifier(ReadOnlySpan strings) { bld.Append('.'); } - if (null != strings[i] && 0 != strings[i].Length) + if (strings[i] != null && 0 != strings[i].Length) { ADP.AppendQuotedString(bld, "[", "]", strings[i]); } @@ -6620,7 +6620,7 @@ internal bool IsDirty // only mark the command as dirty if it is already prepared // but always clear the value if it we are clearing the dirty flag _dirty = value ? IsPrepared : false; - if (null != _parameters) + if (_parameters != null) { _parameters.IsDirty = _dirty; } 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 a9a168f490..7da530b12a 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 @@ -482,7 +482,7 @@ public bool StatisticsEnabled else { // stop - if (null != _statistics) + if (_statistics != null) { if (ConnectionState.Open == State) { @@ -556,7 +556,7 @@ private bool UsesIntegratedSecurity(SqlConnectionString opt) private bool UsesClearUserIdOrPassword(SqlConnectionString opt) { bool result = false; - if (null != opt) + if (opt != null) { result = (!string.IsNullOrEmpty(opt.UserID) || !string.IsNullOrEmpty(opt.Password)); } @@ -662,7 +662,7 @@ public override int ConnectionTimeout get { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; - return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout); + return constr != null ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout; } } @@ -674,7 +674,7 @@ public int CommandTimeout get { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; - return ((null != constr) ? constr.CommandTimeout : SqlConnectionString.DEFAULT.Command_Timeout); + return constr != null ? constr.CommandTimeout : SqlConnectionString.DEFAULT.Command_Timeout; } } @@ -749,14 +749,14 @@ public override string Database SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; - if (null != innerConnection) + if (innerConnection != null) { result = innerConnection.CurrentDatabase; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; - result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog); + result = constr != null ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog; } return result; } @@ -772,7 +772,7 @@ internal string SQLDNSCachingSupportedState SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); string result; - if (null != innerConnection) + if (innerConnection != null) { result = innerConnection.IsSQLDNSCachingSupported ? "true" : "false"; } @@ -795,7 +795,7 @@ internal string SQLDNSCachingSupportedStateBeforeRedirect SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); string result; - if (null != innerConnection) + if (innerConnection != null) { result = innerConnection.IsDNSCachingBeforeRedirectSupported ? "true" : "false"; } @@ -820,14 +820,14 @@ public override string DataSource SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; - if (null != innerConnection) + if (innerConnection != null) { result = innerConnection.CurrentDataSource; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; - result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source); + result = constr != null ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source; } return result; } @@ -847,14 +847,14 @@ public int PacketSize SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); int result; - if (null != innerConnection) + if (innerConnection != null) { result = innerConnection.PacketSize; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; - result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size); + result = constr != null ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size; } return result; } @@ -870,7 +870,7 @@ public Guid ClientConnectionId { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); - if (null != innerConnection) + if (innerConnection != null) { return innerConnection.ClientConnectionId; } @@ -879,7 +879,7 @@ public Guid ClientConnectionId Task reconnectTask = _currentReconnectionTask; // Connection closed but previously open should return the correct ClientConnectionId DbConnectionClosedPreviouslyOpened innerConnectionClosed = (InnerConnection as DbConnectionClosedPreviouslyOpened); - if ((reconnectTask != null && !reconnectTask.IsCompleted) || null != innerConnectionClosed) + if ((reconnectTask != null && !reconnectTask.IsCompleted) || innerConnectionClosed != null) { return _originalConnectionId; } @@ -1256,7 +1256,7 @@ public static void ClearPool(SqlConnection connection) ADP.CheckArgumentNull(connection, nameof(connection)); DbConnectionOptions connectionOptions = connection.UserConnectionOptions; - if (null != connectionOptions) + if (connectionOptions != null) { SqlConnectionFactory.SingletonInstance.ClearPool(connection); } @@ -1325,7 +1325,7 @@ public override void Close() CloseInnerConnection(); GC.SuppressFinalize(this); - if (null != Statistics) + if (Statistics != null) { _statistics._closeTimestamp = ADP.TimerCurrent(); } @@ -2172,7 +2172,7 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) { SqlClientEventSource.Log.TryTraceEvent("SqlConnection.OnInfoMessage | API | Info | Object Id {0}, Message '{1}'", ObjectID, imevent.Message); SqlInfoMessageEventHandler handler = InfoMessage; - if (null != handler) + if (handler != null) { notified = true; try @@ -2361,7 +2361,7 @@ internal Task RegisterForConnectionCloseNotification(Task outerTask, ob /// public void ResetStatistics() { - if (null != Statistics) + if (Statistics != null) { Statistics.Reset(); if (ConnectionState.Open == State) @@ -2375,7 +2375,7 @@ public void ResetStatistics() /// public IDictionary RetrieveStatistics() { - if (null != Statistics) + if (Statistics != null) { UpdateStatistics(); return Statistics.GetDictionary(); 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 04c2938969..d84b433d68 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 @@ -85,7 +85,7 @@ override protected DbConnectionInternal CreateConnection(DbConnectionOptions opt redirectedUserInstance = true; string instanceName; - if (pool == null || (null != pool && pool.Count <= 0)) + if (pool == null || (pool != null && pool.Count <= 0)) { // Non-pooled or pooled and no connections in the pool. SqlInternalConnectionTds sseConnection = null; try @@ -104,7 +104,7 @@ override protected DbConnectionInternal CreateConnection(DbConnectionOptions opt throw SQL.NonLocalSSEInstance(); } - if (null != pool) + if (pool != null) { // Pooled connection - cache result SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo; // No lock since we are already in creation mutex @@ -113,7 +113,7 @@ override protected DbConnectionInternal CreateConnection(DbConnectionOptions opt } finally { - if (null != sseConnection) + if (sseConnection != null) { sseConnection.Dispose(); } @@ -222,7 +222,7 @@ internal static SqlConnectionString FindSqlConnectionOptions(SqlConnectionPoolKe override internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection) { SqlConnection c = (connection as SqlConnection); - if (null != c) + if (c != null) { return c.PoolGroup; } @@ -232,7 +232,7 @@ override internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection conn override internal DbConnectionInternal GetInnerConnection(DbConnection connection) { SqlConnection c = (connection as SqlConnection); - if (null != c) + if (c != null) { return c.InnerConnection; } @@ -242,7 +242,7 @@ override internal DbConnectionInternal GetInnerConnection(DbConnection connectio override protected int GetObjectId(DbConnection connection) { SqlConnection c = (connection as SqlConnection); - if (null != c) + if (c != null) { return c.ObjectID; } @@ -252,7 +252,7 @@ override protected int GetObjectId(DbConnection connection) override internal void PermissionDemand(DbConnection outerConnection) { SqlConnection c = (outerConnection as SqlConnection); - if (null != c) + if (c != null) { c.PermissionDemand(); } @@ -261,7 +261,7 @@ override internal void PermissionDemand(DbConnection outerConnection) override internal void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) { SqlConnection c = (outerConnection as SqlConnection); - if (null != c) + if (c != null) { c.PoolGroup = poolGroup; } @@ -270,7 +270,7 @@ override internal void SetConnectionPoolGroup(DbConnection outerConnection, DbCo override internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) { SqlConnection c = (owningObject as SqlConnection); - if (null != c) + if (c != null) { c.SetInnerConnectionEvent(to); } @@ -279,7 +279,7 @@ override internal void SetInnerConnectionEvent(DbConnection owningObject, DbConn override internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) { SqlConnection c = (owningObject as SqlConnection); - if (null != c) + if (c != null) { return c.SetInnerConnectionFrom(to, from); } @@ -289,7 +289,7 @@ override internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConne override internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) { SqlConnection c = (owningObject as SqlConnection); - if (null != c) + if (c != null) { c.SetInnerConnectionTo(to); } 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 7ae6247a9d..d3750ac56f 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 @@ -54,7 +54,7 @@ internal DbConnectionOptions ConnectionOptions get { DbConnectionPoolGroup poolGroup = PoolGroup; - return ((null != poolGroup) ? poolGroup.ConnectionOptions : null); + return poolGroup != null ? poolGroup.ConnectionOptions : null; } } @@ -63,7 +63,7 @@ private string ConnectionString_Get() SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions connectionOptions = UserConnectionOptions; - return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); + return connectionOptions != null ? connectionOptions.UsersConnectionString(hidePassword) : ""; } private void ConnectionString_Set(DbConnectionPoolKey key) @@ -108,7 +108,7 @@ internal DbConnectionPoolGroup PoolGroup } set { - Debug.Assert(null != value, "null poolGroup"); + Debug.Assert(value != null, "null poolGroup"); _poolGroup = value; } } @@ -226,13 +226,13 @@ internal void PermissionDemand() { Debug.Assert(DbConnectionClosedConnecting.SingletonInstance == _innerConnection, "not connecting"); DbConnectionPoolGroup poolGroup = PoolGroup; - DbConnectionOptions connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null); + DbConnectionOptions connectionOptions = poolGroup != null ? poolGroup.ConnectionOptions : null; if (connectionOptions == null || connectionOptions.IsEmpty) { throw ADP.NoConnectionString(); } DbConnectionOptions userConnectionOptions = UserConnectionOptions; - Debug.Assert(null != userConnectionOptions, "null UserConnectionOptions"); + Debug.Assert(userConnectionOptions != null, "null UserConnectionOptions"); } internal void RemoveWeakReference(object value) @@ -242,8 +242,8 @@ internal void RemoveWeakReference(object value) internal void SetInnerConnectionEvent(DbConnectionInternal to) { - Debug.Assert(null != _innerConnection, "null InnerConnection"); - Debug.Assert(null != to, "to null InnerConnection"); + Debug.Assert(_innerConnection != null, "null InnerConnection"); + Debug.Assert(to != null, "to null InnerConnection"); ConnectionState originalState = _innerConnection.State & ConnectionState.Open; ConnectionState currentState = to.State & ConnectionState.Open; @@ -276,17 +276,17 @@ internal void SetInnerConnectionEvent(DbConnectionInternal to) internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionInternal from) { - Debug.Assert(null != _innerConnection, "null InnerConnection"); - Debug.Assert(null != from, "from null InnerConnection"); - Debug.Assert(null != to, "to null InnerConnection"); + Debug.Assert(_innerConnection != null, "null InnerConnection"); + Debug.Assert(from != null, "from null InnerConnection"); + Debug.Assert(to != null, "to null InnerConnection"); bool result = (from == Interlocked.CompareExchange(ref _innerConnection, to, from)); return result; } internal void SetInnerConnectionTo(DbConnectionInternal to) { - Debug.Assert(null != _innerConnection, "null InnerConnection"); - Debug.Assert(null != to, "to null InnerConnection"); + Debug.Assert(_innerConnection != null, "null InnerConnection"); + Debug.Assert(to != null, "to null InnerConnection"); _innerConnection = to; } } 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 13ec2b5596..bc6d66ecae 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 @@ -270,7 +270,7 @@ internal virtual SmiExtendedMetaData[] GetInternalSmiMetaData() SmiExtendedMetaData[] metaDataReturn = null; _SqlMetaDataSet metaData = this.MetaData; - if (null != metaData && 0 < metaData.Length) + if (metaData != null && 0 < metaData.Length) { metaDataReturn = new SmiExtendedMetaData[metaData.VisibleColumnCount]; int returnIndex = 0; @@ -318,8 +318,8 @@ internal virtual SmiExtendedMetaData[] GetInternalSmiMetaData() length, colMetaData.precision, colMetaData.scale, - (null != collation) ? collation.LCID : _defaultLCID, - (null != collation) ? collation.SqlCompareOptions : SqlCompareOptions.None, + collation != null ? collation.LCID : _defaultLCID, + collation != null ? collation.SqlCompareOptions : SqlCompareOptions.None, colMetaData.udt?.Type, false, // isMultiValued null, // fieldmetadata @@ -354,8 +354,10 @@ override public int RecordsAffected { get { - if (null != _command) + if (_command != null) + { return _command.InternalRecordsAffected; + } // cached locally for after Close() when command is nulled out return _recordsAffected; @@ -429,7 +431,7 @@ override public object this[string name] internal void Bind(TdsParserStateObject stateObj) { - Debug.Assert(null != stateObj, "null stateobject"); + Debug.Assert(stateObj != null, "null stateobject"); Debug.Assert(_snapshot == null, "Should not change during execution of asynchronous command"); @@ -446,7 +448,7 @@ internal void Bind(TdsParserStateObject stateObj) internal DataTable BuildSchemaTable() { _SqlMetaDataSet md = this.MetaData; - Debug.Assert(null != md, "BuildSchemaTable - unexpected null metadata information"); + Debug.Assert(md != null, "BuildSchemaTable - unexpected null metadata information"); DataTable schemaTable = new DataTable("SchemaTable"); schemaTable.Locale = CultureInfo.InvariantCulture; @@ -747,7 +749,7 @@ internal void Cancel(SqlCommand command) { Debug.Assert(command == _command, "Calling command from an object that isn't this reader's command"); TdsParserStateObject stateObj = _stateObj; - if (null != stateObj) + if (stateObj != null) { stateObj.Cancel(command); } @@ -1052,7 +1054,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) // IsClosed may be true if CloseReaderFromConnection was called - in which case, the session has already been closed - if ((!wasClosed) && (null != stateObj)) + if (!wasClosed && stateObj != null) { if (!cleanDataFailed) { @@ -1235,7 +1237,7 @@ private string GetDataTypeNameInternal(_SqlMetaData metaData) virtual internal SqlBuffer.StorageType GetVariantInternalStorageType(int i) { - Debug.Assert(null != _data, "Attempting to get variant internal storage type"); + Debug.Assert(_data != null, "Attempting to get variant internal storage type"); Debug.Assert(i < _data.Length, "Reading beyond data length?"); return _data[i].VariantInternalStorageType; @@ -1482,10 +1484,10 @@ public override DataTable GetSchemaTable() statistics = SqlStatistics.StartTimer(Statistics); if (_metaData == null || _metaData.schemaTable == null) { - if (null != this.MetaData) + if (this.MetaData != null) { _metaData.schemaTable = BuildSchemaTable(); - Debug.Assert(null != _metaData.schemaTable, "No schema information yet!"); + Debug.Assert(_metaData.schemaTable != null, "No schema information yet!"); } } return _metaData?.schemaTable; @@ -3138,7 +3140,7 @@ private MetaType GetVersionedMetaType(MetaType actualMetaType) private TdsOperationStatus TryHasMoreResults(out bool moreResults) { - if (null != _parser) + if (_parser != null) { bool moreRows; TdsOperationStatus result = TryHasMoreRows(out moreRows); @@ -3154,7 +3156,7 @@ private TdsOperationStatus TryHasMoreResults(out bool moreResults) return TdsOperationStatus.Done; } - Debug.Assert(null != _command, "unexpected null command from the data reader!"); + Debug.Assert(_command != null, "unexpected null command from the data reader!"); while (_stateObj.HasPendingData) { @@ -3223,7 +3225,7 @@ private TdsOperationStatus TryHasMoreResults(out bool moreResults) private TdsOperationStatus TryHasMoreRows(out bool moreRows) { - if (null != _parser) + if (_parser != null) { if (_sharedState._dataReady) { @@ -3396,7 +3398,7 @@ private TdsOperationStatus TryNextResult(out bool more) return TdsOperationStatus.Done; } - if (null != _parser) + if (_parser != null) { // if there are more rows, then skip them, the user wants the next result bool moreRows = true; @@ -3413,7 +3415,7 @@ private TdsOperationStatus TryNextResult(out bool more) } // we may be done, so continue only if we have not detached ourselves from the parser - if (null != _parser) + if (_parser != null) { bool moreResults; result = TryHasMoreResults(out moreResults); @@ -3541,7 +3543,7 @@ private TdsOperationStatus TryReadInternal(bool setTimeout, out bool more) TdsOperationStatus result; statistics = SqlStatistics.StartTimer(Statistics); - if (null != _parser) + if (_parser != null) { if (setTimeout) { @@ -3768,7 +3770,7 @@ private TdsOperationStatus TryReadColumn(int i, bool setTimeout, bool allowParti return result; } - Debug.Assert(null != _data[i], " data buffer is null?"); + Debug.Assert(_data[i] != null, " data buffer is null?"); return TdsOperationStatus.Done; } @@ -4104,7 +4106,7 @@ private bool WillHaveEnoughData(int targetColumn, bool headerOnly = false) // clean remainder bytes for the column off the wire private TdsOperationStatus TryResetBlobState() { - Debug.Assert(null != _stateObj, "null state object"); // _parser may be null at this point + Debug.Assert(_stateObj != null, "null state object"); // _parser may be null at this point AssertReaderState(requireData: true, permitAsync: true); Debug.Assert(_sharedState._nextColumnHeaderToRead <= _metaData.Length, "_sharedState._nextColumnHeaderToRead too large"); TdsOperationStatus result; @@ -4171,7 +4173,7 @@ private void CloseActiveSequentialStreamAndTextReader() private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateObj) { // turn off any set options - if (null != parser && null != _resetOptionsString) + if (parser != null && _resetOptionsString != null) { // It is possible for this to be called during connection close on a // broken connection, so check state first. @@ -4200,7 +4202,7 @@ internal TdsOperationStatus TrySetAltMetaDataSet(_SqlMetaDataSet metaDataSet, bo } _altMetaDataSetCollection.SetAltMetaData(metaDataSet); _metaDataConsumed = metaDataConsumed; - if (_metaDataConsumed && null != _parser) + if (_metaDataConsumed && _parser != null) { byte b; TdsOperationStatus result = _stateObj.TryPeekByte(out b); @@ -4283,7 +4285,7 @@ internal TdsOperationStatus TrySetMetaData(_SqlMetaDataSet metaData, bool moreIn _fieldNameLookup = null; - if (null != metaData) + if (metaData != null) { TdsOperationStatus result; // we are done consuming metadata only if there is no moreInfo @@ -4364,7 +4366,7 @@ private void SetTimeout(long timeoutMilliseconds) // WebData 111653,112003 -- we now set timeouts per operation, not // per command (it's not supposed to be a cumulative per command). TdsParserStateObject stateObj = _stateObj; - if (null != stateObj) + if (stateObj != null) { stateObj.SetTimeoutMilliseconds(timeoutMilliseconds); } @@ -5830,15 +5832,15 @@ public ReadOnlyCollection GetColumnSchema() statistics = SqlStatistics.StartTimer(Statistics); if (_metaData == null || _metaData.dbColumnSchema == null) { - if (null != this.MetaData) + if (this.MetaData != null) { _metaData.dbColumnSchema = BuildColumnSchema(); - Debug.Assert(null != _metaData.dbColumnSchema, "No schema information yet!"); + Debug.Assert(_metaData.dbColumnSchema != null, "No schema information yet!"); // filter table? } } - if (null != _metaData) + if (_metaData != null) { return _metaData.dbColumnSchema; } 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 08ba5ec80e..0de99051f3 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 @@ -34,7 +34,7 @@ sealed internal partial class SqlDelegatedTransaction : IPromotableSinglePhaseNo internal SqlDelegatedTransaction(SqlInternalConnection connection, Transaction tx) { - Debug.Assert(null != connection, "null connection?"); + Debug.Assert(connection != null, "null connection?"); _connection = connection; _atomicTransaction = tx; _active = false; @@ -142,7 +142,7 @@ public byte[] Promote() Exception promoteException; byte[] returnValue = null; - if (null != connection) + if (connection != null) { SqlConnection usersConnection = connection.Connection; SqlClientEventSource.Log.TryTraceEvent("SqlDelegatedTransaction.Promote | RES | CPOOL | Object Id {0}, Client Connection Id {1}, promoting transaction.", ObjectID, usersConnection?.ClientConnectionId); @@ -249,10 +249,10 @@ public byte[] Promote() // Called by transaction to initiate abort sequence public void Rollback(SinglePhaseEnlistment enlistment) { - Debug.Assert(null != enlistment, "null enlistment?"); + Debug.Assert(enlistment != null, "null enlistment?"); SqlInternalConnection connection = GetValidConnection(); - if (null != connection) + if (connection != null) { SqlConnection usersConnection = connection.Connection; SqlClientEventSource.Log.TryTraceEvent("SqlDelegatedTransaction.Rollback | RES | CPOOL | Object Id {0}, Client Connection Id {1}, rolling back transaction.", ObjectID, usersConnection?.ClientConnectionId); @@ -336,10 +336,10 @@ public void Rollback(SinglePhaseEnlistment enlistment) // Called by the transaction to initiate commit sequence public void SinglePhaseCommit(SinglePhaseEnlistment enlistment) { - Debug.Assert(null != enlistment, "null enlistment?"); + Debug.Assert(enlistment != null, "null enlistment?"); SqlInternalConnection connection = GetValidConnection(); - if (null != connection) + if (connection != null) { SqlConnection usersConnection = connection.Connection; SqlClientEventSource.Log.TryTraceEvent("SqlDelegatedTransaction.SinglePhaseCommit | RES | CPOOL | Object Id {0}, Client Connection Id {1}, committing transaction.", ObjectID, usersConnection?.ClientConnectionId); @@ -504,11 +504,11 @@ private void ValidateActiveOnConnection(SqlInternalConnection connection) { // Invalid indicates something BAAAD happened (Commit after TransactionEnded, for instance) // Doom anything remotely involved. - if (null != connection) + if (connection != null) { connection.DoomThisConnection(); } - if (connection != _connection && null != _connection) + if (connection != _connection && _connection != null) { _connection.DoomThisConnection(); } 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 d1abdb310f..f4df2b11f9 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 @@ -745,7 +745,7 @@ public override void Dispose() TdsParser parser = Interlocked.Exchange(ref _parser, null); // guard against multiple concurrent dispose calls -- Delegated Transactions might cause this. Debug.Assert(parser != null && _fConnectionOpen || parser == null && !_fConnectionOpen, "Unexpected state on dispose"); - if (null != parser) + if (parser != null) { parser.Disconnect(); } @@ -772,7 +772,7 @@ internal override void ValidateConnectionForExecute(SqlCommand command) SqlDataReader reader = null; if (parser.MARSOn) { - if (null != command) + if (command != null) { // command can't have datareader already associated with it reader = FindLiveReader(command); } @@ -786,7 +786,7 @@ internal override void ValidateConnectionForExecute(SqlCommand command) reader = FindLiveReader(null); } - if (null != reader) + if (reader != null) { // if MARS is on, then a datareader associated with the command exists // or if MARS is off, then a datareader exists @@ -882,7 +882,7 @@ protected override void Activate(Transaction transaction) // Regardless of whether we're required to automatically enlist, // when there is not a current transaction, we cannot leave the // connection enlisted in a transaction. - if (null != transaction) + if (transaction != null) { if (ConnectionOptions.Enlist) { @@ -913,7 +913,7 @@ protected override void InternalDeactivate() // transaction is completed and we can do it all then. if (!IsNonPoolableTransactionRoot) { - Debug.Assert(null != _parser || IsConnectionDoomed, "Deactivating a disposed connection?"); + Debug.Assert(_parser != null || IsConnectionDoomed, "Deactivating a disposed connection?"); if (_parser != null) { _parser.Deactivate(IsConnectionDoomed); @@ -971,7 +971,7 @@ internal override void DisconnectTransaction(SqlInternalTransaction internalTran { TdsParser parser = Parser; - if (null != parser) + if (parser != null) { parser.DisconnectTransaction(internalTransaction); } @@ -1120,7 +1120,7 @@ bool isDelegateControlRequest // an object that the ExecTMReq will also lock, but since we're on // the same thread, the lock is a no-op. - if (null != internalTransaction && internalTransaction.IsDelegated) + if (internalTransaction != null && internalTransaction.IsDelegated) { if (_parser.MARSOn) { @@ -1169,7 +1169,7 @@ internal override void DelegatedTransactionEnded() protected override byte[] GetDTCAddress() { byte[] dtcAddress = _parser.GetDTCAddress(ConnectionOptions.ConnectTimeout, _parser.GetSession(this)); - Debug.Assert(null != dtcAddress, "null dtcAddress?"); + Debug.Assert(dtcAddress != null, "null dtcAddress?"); return dtcAddress; } @@ -1391,7 +1391,7 @@ private void OpenLoginEnlist(TimeoutTimer timeout, ServerInfo dataSource = new ServerInfo(connectionOptions); string failoverPartner; - if (null != PoolGroupProviderInfo) + if (PoolGroupProviderInfo != null) { useFailoverPartner = PoolGroupProviderInfo.UseFailoverPartner; failoverPartner = PoolGroupProviderInfo.FailoverPartner; @@ -1544,7 +1544,7 @@ private void LoginNoFailover(ServerInfo serverInfo, newSecurePassword, connectionOptions.MultiSubnetFailover ? intervalTimer : timeout); - if (connectionOptions.MultiSubnetFailover && null != ServerProvidedFailOverPartner) + if (connectionOptions.MultiSubnetFailover && ServerProvidedFailOverPartner != null) { // connection succeeded: trigger exception if server sends failover partner and MultiSubnetFailover is used throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: true, internalConnection: this); @@ -1611,7 +1611,7 @@ private void LoginNoFailover(ServerInfo serverInfo, // We only get here when we failed to connect, but are going to re-try // Switch to failover logic if the server provided a partner - if (null != ServerProvidedFailOverPartner) + if (ServerProvidedFailOverPartner != null) { if (connectionOptions.MultiSubnetFailover) { @@ -1645,7 +1645,7 @@ private void LoginNoFailover(ServerInfo serverInfo, } _activeDirectoryAuthTimeoutRetryHelper.State = ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn; - if (null != PoolGroupProviderInfo) + if (PoolGroupProviderInfo != null) { // We must wait for CompleteLogin to finish for to have the // env change from the server to know its designated failover @@ -1760,7 +1760,7 @@ TimeoutTimer timeout if (useFailoverHost) { // Primary server may give us a different failover partner than the connection string indicates. Update it - if (null != ServerProvidedFailOverPartner && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) + if (ServerProvidedFailOverPartner != null && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) { SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); failoverServerInfo.SetDerivedNames(string.Empty, ServerProvidedFailOverPartner); @@ -1850,7 +1850,7 @@ TimeoutTimer timeout throw SQL.InvalidPartnerConfiguration(failoverHost, CurrentDatabase); } - if (null != PoolGroupProviderInfo) + if (PoolGroupProviderInfo != null) { // We must wait for CompleteLogin to finish for to have the // env change from the server to know its designated failover @@ -2011,7 +2011,7 @@ internal void BreakConnection() var connection = Connection; SqlClientEventSource.Log.TryTraceEvent(" {0}, Breaking connection.", ObjectID); DoomThisConnection(); // Mark connection as unusable, so it will be destroyed - if (null != connection) + if (connection != null) { connection.Close(); } @@ -2895,7 +2895,7 @@ private ServerInfo(SqlConnectionString userOptions, string serverName) { //----------------- // Preconditions - Debug.Assert(null != userOptions); + Debug.Assert(userOptions != null); //----------------- //Method body @@ -2914,7 +2914,7 @@ internal ServerInfo(SqlConnectionString userOptions, RoutingInfo routing, string { //----------------- // Preconditions - Debug.Assert(null != userOptions && null != routing); + Debug.Assert(userOptions != null && routing != null); //----------------- //Method body 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 58b253499b..4cee4ff95c 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 @@ -233,14 +233,14 @@ internal SqlInternalTransaction CurrentTransaction Debug.Assert(value == _currentTransaction || _currentTransaction == null || value == null - || (null != _currentTransaction && !_currentTransaction.IsLocal), "attempting to change current transaction?"); + || (_currentTransaction != null && !_currentTransaction.IsLocal), "attempting to change current transaction?"); // If there is currently a transaction active, we don't want to // change it; this can occur when there is a delegated transaction // and the user attempts to do an API begin transaction; in these // cases, it's safe to ignore the set. - if ((_currentTransaction == null && null != value) - || (null != _currentTransaction && value == null)) + if ((_currentTransaction == null && value != null) + || (_currentTransaction != null && value == null)) { _currentTransaction = value; } @@ -293,7 +293,7 @@ internal SqlInternalTransaction PendingTransaction } set { - Debug.Assert(null != value, "setting a non-null PendingTransaction?"); + Debug.Assert(value != null, "setting a non-null PendingTransaction?"); _pendingTransaction = value; } } @@ -486,7 +486,7 @@ internal void Connect( _server = serverInfo.ResolvedServerName; - if (null != connHandler.PoolGroupProviderInfo) + if (connHandler.PoolGroupProviderInfo != null) { // If we are pooling, check to see if we were processing an // alias which has changed, which means we need to clean out @@ -1185,7 +1185,7 @@ internal void Deactivate(bool connectionIsDoomed) Debug.Assert(connectionIsDoomed || _pendingTransaction == null, "pending transaction at disconnect?"); - if (!connectionIsDoomed && null != _physicalStateObj) + if (!connectionIsDoomed && _physicalStateObj != null) { if (_physicalStateObj.HasPendingData) { @@ -1208,7 +1208,7 @@ internal void Deactivate(bool connectionIsDoomed) // transaction manager completes the transaction. SqlInternalTransaction currentTransaction = CurrentTransaction; - if (null != currentTransaction && currentTransaction.HasParentTransaction) + if (currentTransaction != null && currentTransaction.HasParentTransaction) { currentTransaction.CloseFromConnection(); Debug.Assert(CurrentTransaction == null, "rollback didn't clear current transaction?"); @@ -1220,7 +1220,7 @@ internal void Deactivate(bool connectionIsDoomed) // Used to close the connection and then free the memory allocated for the netlib connection. internal void Disconnect() { - if (null != _sessionPool) + if (_sessionPool != null) { // MARSOn may be true, but _sessionPool not yet created _sessionPool.Dispose(); @@ -1252,7 +1252,7 @@ internal void Disconnect() } // Not allocated until MARS is actually enabled in SNI. - if (null != _pMarsPhysicalConObj) + if (_pMarsPhysicalConObj != null) { _pMarsPhysicalConObj.Dispose(); } @@ -1313,7 +1313,7 @@ internal void RollbackOrphanedAPITransactions() // Any active, non-distributed transaction must be rolled back. SqlInternalTransaction currentTransaction = CurrentTransaction; - if (null != currentTransaction && currentTransaction.HasParentTransaction && currentTransaction.IsOrphaned) + if (currentTransaction != null && currentTransaction.HasParentTransaction && currentTransaction.IsOrphaned) { currentTransaction.CloseFromConnection(); Debug.Assert(CurrentTransaction == null, "rollback didn't clear current transaction?"); @@ -2138,7 +2138,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle // a reader we need to throw the error but not halt further processing. We used to // halt processing. - if (null != dataStream) + if (dataStream != null) { if (!dataStream.IsInitialized) { @@ -2166,7 +2166,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle case TdsEnums.SQLCOLINFO: { - if (null != dataStream) + if (dataStream != null) { _SqlMetaDataSet metaDataSet; result = TryProcessColInfo(dataStream.MetaData, dataStream, stateObj, out metaDataSet); @@ -2260,7 +2260,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle _currentTransaction = _pendingTransaction; _pendingTransaction = null; - if (null != _currentTransaction) + if (_currentTransaction != null) { _currentTransaction.TransactionId = env._newLongValue; // this is defined as a ULongLong in the server and in the TDS Spec. } @@ -2269,7 +2269,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle TransactionType transactionType = (TdsEnums.ENV_BEGINTRAN == env._type) ? TransactionType.LocalFromTSQL : TransactionType.Distributed; _currentTransaction = new SqlInternalTransaction(_connHandler, transactionType, null, env._newLongValue); } - if (null != _statistics && !_statisticsIsInTransaction) + if (_statistics != null && !_statisticsIsInTransaction) { _statistics.SafeIncrement(ref _statistics._transactions); } @@ -2286,7 +2286,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle case TdsEnums.ENV_ROLLBACKTRAN: // When we get notification of a completed transaction // we null out the current transaction. - if (null != _currentTransaction) + if (_currentTransaction != null) { #if DEBUG // Check null for case where Begin and Rollback obtained in the same message. @@ -2419,7 +2419,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle { return result; } - if (null != dataStream) + if (dataStream != null) { result = dataStream.TrySetSensitivityClassification(sensitivityClassification); if (result != TdsOperationStatus.Done) @@ -2436,7 +2436,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle } } - if (null != dataStream) + if (dataStream != null) { result = dataStream.TrySetMetaData(stateObj._cleanupMetaData, (TdsEnums.SQLTABNAME == peekedToken || TdsEnums.SQLCOLINFO == peekedToken)); if (result != TdsOperationStatus.Done) @@ -2444,7 +2444,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle return result; } } - else if (null != bulkCopyHandler) + else if (bulkCopyHandler != null) { bulkCopyHandler.SetMetaData(stateObj._cleanupMetaData); } @@ -2472,7 +2472,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle } } - if (null != bulkCopyHandler) + if (bulkCopyHandler != null) { result = TryProcessRow(stateObj._cleanupMetaData, bulkCopyHandler.CreateRowBuffer(), bulkCopyHandler.CreateIndexMap(), stateObj); if (result != TdsOperationStatus.Done) @@ -2537,7 +2537,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle } case TdsEnums.SQLTABNAME: { - if (null != dataStream) + if (dataStream != null) { MultiPartTableName[] tableNames; result = TryProcessTableName(tokenLength, stateObj, out tableNames); @@ -2586,7 +2586,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle } stateObj._cleanupAltMetaDataSetArray.SetAltMetaData(cleanupAltMetaDataSet); - if (null != dataStream) + if (dataStream != null) { byte metadataConsumedByte; result = stateObj.TryPeekByte(out metadataConsumedByte); @@ -2665,7 +2665,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle if (!stateObj.HasPendingData) { - if (null != CurrentTransaction) + if (CurrentTransaction != null) { CurrentTransaction.Activate(); } @@ -3153,7 +3153,7 @@ private TdsOperationStatus TryProcessDone(SqlCommand cmd, SqlDataReader reader, stateObj.HasReceivedAttention = true; Debug.Assert(stateObj._inBytesUsed == stateObj._inBytesRead && stateObj._inBytesPacket == 0, "DONE_ATTN received with more data left on wire"); } - if ((null != cmd) && (TdsEnums.DONE_COUNT == (status & TdsEnums.DONE_COUNT))) + if (cmd != null && (TdsEnums.DONE_COUNT == (status & TdsEnums.DONE_COUNT))) { if (curCmd != TdsEnums.SELECT) { @@ -3187,7 +3187,7 @@ private TdsOperationStatus TryProcessDone(SqlCommand cmd, SqlDataReader reader, { stateObj.AddError(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, _server, SQLMessage.SevereError(), "", 0, exception: null, batchIndex: cmd?.GetCurrentBatchIndex() ?? -1)); - if (null != reader) + if (reader != null) { if (!reader.IsInitialized) { @@ -3203,7 +3203,7 @@ private TdsOperationStatus TryProcessDone(SqlCommand cmd, SqlDataReader reader, { stateObj.AddError(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.SevereError(), "", 0, exception: null, batchIndex: cmd?.GetCurrentBatchIndex() ?? -1)); - if (null != reader) + if (reader != null) { if (!reader.IsInitialized) { @@ -3246,7 +3246,7 @@ private void ProcessSqlStatistics(ushort curCmd, ushort status, int count) { // SqlStatistics bookkeeping stuff // - if (null != _statistics) + if (_statistics != null) { // any done after row(s) counts as a resultset if (_statistics.WaitForDoneAfterRow) @@ -4733,7 +4733,7 @@ internal void ThrowUnsupportedCollationEncountered(TdsParserStateObject stateObj { stateObj.AddError(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, _server, SQLMessage.CultureIdError(), "", 0)); - if (null != stateObj) + if (stateObj != null) { DrainData(stateObj); @@ -7711,7 +7711,7 @@ struct { private void WriteDecimal(decimal value, TdsParserStateObject stateObj) { stateObj._decimalBits = decimal.GetBits(value); - Debug.Assert(null != stateObj._decimalBits, "decimalBits should be filled in at TdsExecuteRPC time"); + Debug.Assert(stateObj._decimalBits != null, "decimalBits should be filled in at TdsExecuteRPC time"); /* Returns a binary representation of a Decimal. The return value is an integer @@ -7746,7 +7746,7 @@ struct { private void WriteIdentifier(string s, TdsParserStateObject stateObj) { - if (null != s) + if (s != null) { stateObj.WriteByte(checked((byte)s.Length)); WriteString(s, stateObj); @@ -7759,7 +7759,7 @@ private void WriteIdentifier(string s, TdsParserStateObject stateObj) private void WriteIdentifierWithShortLength(string s, TdsParserStateObject stateObj) { - if (null != s) + if (s != null) { WriteShort(checked((short)s.Length), stateObj); WriteString(s, stateObj); @@ -8779,7 +8779,7 @@ internal byte[] GetDTCAddress(int timeout, TdsParserStateObject stateObj) { Debug.Assert(SniContext.Snix_Read == stateObj.SniContext, $"The SniContext should be Snix_Read but it actually is {stateObj.SniContext}"); - if (null != dtcReader && dtcReader.Read()) + if (dtcReader != null && dtcReader.Read()) { Debug.Assert(dtcReader.GetName(0) == "TM Address", "TdsParser: GetDTCAddress did not return 'TM Address'"); @@ -8895,7 +8895,7 @@ internal SqlDataReader TdsExecuteTransactionManagerRequest( returnReader = true; break; case TdsEnums.TransactionManagerRequestType.Propagate: - if (null != buffer) + if (buffer != null) { WriteShort(buffer.Length, stateObj); stateObj.WriteByteArray(buffer, buffer.Length, 0); @@ -8906,7 +8906,7 @@ internal SqlDataReader TdsExecuteTransactionManagerRequest( } break; case TdsEnums.TransactionManagerRequestType.Begin: - Debug.Assert(null != transaction, "Should have specified an internalTransaction when doing a BeginTransaction request!"); + Debug.Assert(transaction != null, "Should have specified an internalTransaction when doing a BeginTransaction request!"); // Only assign the passed in transaction if it is not equal to the current transaction. // And, if it is not equal, the current actually should be null. Anything else @@ -9749,7 +9749,7 @@ private Task TDSExecuteRPCAddParameter(TdsParserStateObject stateObj, SqlParamet udtVal = _connHandler.Connection.GetBytes(value, out format, out maxsize); } - Debug.Assert(null != udtVal, "GetBytes returned null instance. Make sure that it always returns non-null value"); + Debug.Assert(udtVal != null, "GetBytes returned null instance. Make sure that it always returns non-null value"); size = udtVal.Length; if (size >= maxSupportedSize && maxsize != -1) @@ -10480,7 +10480,7 @@ internal void LoadColumnEncryptionKeys(_SqlMetaDataSet metadataCollection, SqlCo { for (int col = 0; col < metadataCollection.Length; col++) { - if (null != metadataCollection[col]) + if (metadataCollection[col] != null) { _SqlMetaData md = metadataCollection[col]; if (md.isEncrypted) @@ -10720,8 +10720,8 @@ internal void WriteBulkCopyMetaData(_SqlMetaDataSet metadataCollection, int coun /// internal bool ShouldEncryptValuesForBulkCopy() { - if (null != _connHandler && - null != _connHandler.ConnectionOptions && + if (_connHandler != null && + _connHandler.ConnectionOptions != null && SqlConnectionColumnEncryptionSetting.Enabled == _connHandler.ConnectionOptions.ColumnEncryptionSetting) { return true; @@ -11048,16 +11048,11 @@ private Task WriteBulkCopyValueSetupContinuation(Task internalWriteTask, Encodin private void WriteMarsHeaderData(TdsParserStateObject stateObj, SqlInternalTransaction transaction) { // Function to send over additional payload header data for 2005 and beyond only. - - // These are not necessary - can have local started in distributed. - // Debug.Assert(!(null != sqlTransaction && null != distributedTransaction), "Error to have local (api started) and distributed transaction at the same time!"); - // Debug.Assert(!(null != _userStartedLocalTransaction && null != distributedTransaction), "Error to have local (started outside of the api) and distributed transaction at the same time!"); - // We may need to update the mars header length if mars header is changed in the future WriteShort(TdsEnums.HEADERTYPE_MARS, stateObj); - if (null != transaction && SqlInternalTransaction.NullTransactionId != transaction.TransactionId) + if (transaction != null && SqlInternalTransaction.NullTransactionId != transaction.TransactionId) { WriteLong(transaction.TransactionId, stateObj); WriteInt(stateObj.IncrementAndObtainOpenResultCount(transaction), stateObj); @@ -11072,7 +11067,7 @@ private void WriteMarsHeaderData(TdsParserStateObject stateObj, SqlInternalTrans private int GetNotificationHeaderSize(SqlNotificationRequest notificationRequest) { - if (null != notificationRequest) + if (notificationRequest != null) { string callbackId = notificationRequest.UserData; string service = notificationRequest.Options; @@ -11128,16 +11123,16 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio // We may need to update the notification header length if the header is changed in the future - Debug.Assert(null != notificationRequest, "notificationRequest is null"); + Debug.Assert(notificationRequest != null, "notificationRequest is null"); string callbackId = notificationRequest.UserData; string service = notificationRequest.Options; int timeout = notificationRequest.Timeout; // we did verification in GetNotificationHeaderSize, so just assert here. - Debug.Assert(null != callbackId, "CallbackId is null"); + Debug.Assert(callbackId != null, "CallbackId is null"); Debug.Assert(ushort.MaxValue >= callbackId.Length, "CallbackId length is out of range"); - Debug.Assert(null != service, "Service is null"); + Debug.Assert(service != null, "Service is null"); Debug.Assert(ushort.MaxValue >= service.Length, "Service length is out of range"); Debug.Assert(-1 <= timeout, "Timeout"); @@ -11995,7 +11990,7 @@ private Task WriteValue(object value, MetaType type, byte scale, int actualLengt // chunk writes needed, please use WritePlpBytes/WritePlpChars private Task WriteUnterminatedValue(object value, MetaType type, byte scale, int actualLength, int encodingByteSize, int offset, TdsParserStateObject stateObj, int paramSize, bool isDataFeed) { - Debug.Assert((null != value) && (DBNull.Value != value), "unexpected missing or empty object"); + Debug.Assert(value != null && (DBNull.Value != value), "unexpected missing or empty object"); // parameters are always sent over as BIG or N types switch (type.NullableType) @@ -12264,7 +12259,7 @@ private void WriteEncryptionMetadata(SqlColumnEncryptionInputParameterInfo colum // chunk writes needed, please use WritePlpBytes/WritePlpChars private byte[] SerializeUnencryptedValue(object value, MetaType type, byte scale, int actualLength, int offset, bool isDataFeed, byte normalizationVersion, TdsParserStateObject stateObj) { - Debug.Assert((null != value) && (DBNull.Value != value), "unexpected missing or empty object"); + Debug.Assert(value != null && (DBNull.Value != value), "unexpected missing or empty object"); if (normalizationVersion != 0x01) { diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserHelperClasses.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserHelperClasses.cs index 8654aa4c54..9dcdc70afa 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserHelperClasses.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserHelperClasses.cs @@ -726,7 +726,7 @@ internal string TableName private void ParseMultipartName() { - if (null != _multipartName) + if (_multipartName != null) { string[] parts = MultipartIdentifier.ParseMultipartIdentifier(_multipartName, "[\"", "]\"", Strings.SQL_TDSParserTableName, false); _serverName = parts[0]; diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.netcore.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.netcore.cs index 6451eca869..087cfb1e2e 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.netcore.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.netcore.cs @@ -41,14 +41,14 @@ internal static void PrepareConstrainedRegions() internal TdsParserStateObject(TdsParser parser, TdsParserStateObject physicalConnection, bool async) { // Construct a MARS session - Debug.Assert(null != parser, "no parser?"); + Debug.Assert(parser != null, "no parser?"); _parser = parser; _onTimeoutAsync = OnTimeoutAsync; SniContext = SniContext.Snix_GetMarsSession; - Debug.Assert(null != _parser._physicalStateObj, "no physical session?"); - Debug.Assert(null != _parser._physicalStateObj._inBuff, "no in buffer?"); - Debug.Assert(null != _parser._physicalStateObj._outBuff, "no out buffer?"); + Debug.Assert(_parser._physicalStateObj != null, "no physical session?"); + Debug.Assert(_parser._physicalStateObj._inBuff != null, "no in buffer?"); + Debug.Assert(_parser._physicalStateObj._outBuff != null, "no out buffer?"); Debug.Assert(_parser._physicalStateObj._outBuff.Length == _parser._physicalStateObj._inBuff.Length, "Unexpected unequal buffers."); @@ -1357,7 +1357,7 @@ private Task WriteSni(bool canAccumulate) private void SniReadStatisticsAndTracing() { SqlStatistics statistics = Parser.Statistics; - if (null != statistics) + if (statistics != null) { if (statistics.WaitForReply) { @@ -1373,7 +1373,7 @@ private void SniReadStatisticsAndTracing() private void SniWriteStatisticsAndTracing() { SqlStatistics statistics = _parser.Statistics; - if (null != statistics) + if (statistics != null) { statistics.SafeIncrement(ref statistics._buffersSent); statistics.SafeAdd(ref statistics._bytesSent, _outBytesUsed); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectNative.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectNative.cs index 611a003177..20f578fa2f 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectNative.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectNative.cs @@ -233,7 +233,7 @@ internal override void Dispose() DisposeCounters(); - if (null != sessionHandle || null != packetHandle) + if (sessionHandle != null || packetHandle != null) { packetHandle?.Dispose(); asyncAttnPacket?.Dispose(); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Common/src/Microsoft/Data/Common/NameValuePermission.cs b/src/Microsoft.Data.SqlClient/netfx/src/Common/src/Microsoft/Data/Common/NameValuePermission.cs index 4a3055a777..a7ad9be288 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Common/src/Microsoft/Data/Common/NameValuePermission.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Common/src/Microsoft/Data/Common/NameValuePermission.cs @@ -17,7 +17,7 @@ sealed internal class NameValuePermission : IComparable // value nodes link to key nodes private string _value; - // value node with (null != _restrictions) are allowed to match connection strings + // value node with (_restrictions != null) are allowed to match connection strings private DBConnectionString _entry; private NameValuePermission[] _tree; // with branches @@ -44,12 +44,12 @@ private NameValuePermission(NameValuePermission permit) _value = permit._value; _entry = permit._entry; _tree = permit._tree; - if (null != _tree) + if (_tree != null) { NameValuePermission[] tree = (_tree.Clone() as NameValuePermission[]); for (int i = 0; i < tree.Length; ++i) { - if (null != tree[i]) + if (tree[i] != null) { // WebData 98488 tree[i] = tree[i].CopyNameValue(); // deep copy } @@ -65,11 +65,11 @@ int IComparable.CompareTo(object a) static internal void AddEntry(NameValuePermission kvtree, ArrayList entries, DBConnectionString entry) { - Debug.Assert(null != entry, "null DBConnectionString"); + Debug.Assert(entry != null, "null DBConnectionString"); - if (null != entry.KeyChain) + if (entry.KeyChain != null) { - for (NameValuePair keychain = entry.KeyChain; null != keychain; keychain = keychain.Next) + for (NameValuePair keychain = entry.KeyChain; keychain != null; keychain = keychain.Next) { NameValuePermission kv; @@ -84,17 +84,17 @@ static internal void AddEntry(NameValuePermission kvtree, ArrayList entries, DBC kv = kvtree.CheckKeyForValue(keychain.Value); if (kv == null) { - DBConnectionString insertValue = ((null != keychain.Next) ? null : entry); + DBConnectionString insertValue = keychain.Next != null ? null : entry; kv = new NameValuePermission(keychain.Value, insertValue); kvtree.Add(kv); // add directly into live tree - if (null != insertValue) + if (insertValue != null) { entries.Add(insertValue); } } else if (keychain.Next == null) { // shorter chain potential - if (null != kv._entry) + if (kv._entry != null) { Debug.Assert(entries.Contains(kv._entry), "entries doesn't contain entry"); entries.Remove(kv._entry); @@ -112,7 +112,7 @@ static internal void AddEntry(NameValuePermission kvtree, ArrayList entries, DBC else { // global restrictions, MDAC 84443 DBConnectionString kentry = kvtree._entry; - if (null != kentry) + if (kentry != null) { Debug.Assert(entries.Contains(kentry), "entries doesn't contain entry"); entries.Remove(kentry); @@ -135,25 +135,25 @@ internal void Intersect(ArrayList entries, NameValuePermission target) } else { - if (null != _entry) + if (_entry != null) { entries.Remove(_entry); _entry = _entry.Intersect(target._entry); entries.Add(_entry); } - else if (null != target._entry) + else if (target._entry != null) { _entry = target._entry.Intersect(null); entries.Add(_entry); } - if (null != _tree) + if (_tree != null) { int count = _tree.Length; for (int i = 0; i < _tree.Length; ++i) { NameValuePermission kvtree = target.CheckKeyForValue(_tree[i]._value); - if (null != kvtree) + if (kvtree != null) { // does target tree contain our value _tree[i].Intersect(entries, kvtree); } @@ -172,7 +172,7 @@ internal void Intersect(ArrayList entries, NameValuePermission target) NameValuePermission[] kvtree = new NameValuePermission[count]; for (int i = 0, j = 0; i < _tree.Length; ++i) { - if (null != _tree[i]) + if (_tree[i] != null) { kvtree[j++] = _tree[i]; } @@ -186,7 +186,7 @@ internal void Intersect(ArrayList entries, NameValuePermission target) private void Add(NameValuePermission permit) { NameValuePermission[] tree = _tree; - int length = ((null != tree) ? tree.Length : 0); + int length = tree != null ? tree.Length : 0; NameValuePermission[] newtree = new NameValuePermission[1 + length]; for (int i = 0; i < newtree.Length - 1; ++i) { @@ -205,7 +205,7 @@ internal bool CheckValueForKeyPermit(DBConnectionString parsetable) } bool hasMatch = false; NameValuePermission[] keytree = _tree; // _tree won't mutate but Add will replace it - if (null != keytree) + if (keytree != null) { hasMatch = parsetable.IsEmpty; // MDAC 86773 if (!hasMatch) @@ -215,7 +215,7 @@ internal bool CheckValueForKeyPermit(DBConnectionString parsetable) for (int i = 0; i < keytree.Length; ++i) { NameValuePermission permitKey = keytree[i]; - if (null != permitKey) + if (permitKey != null) { string keyword = permitKey._value; #if DEBUG @@ -227,7 +227,7 @@ internal bool CheckValueForKeyPermit(DBConnectionString parsetable) // keyword is restricted to certain values NameValuePermission permitValue = permitKey.CheckKeyForValue(valueInQuestion); - if (null != permitValue) + if (permitValue != null) { //value does match - continue the chain down that branch if (permitValue.CheckValueForKeyPermit(parsetable)) @@ -256,7 +256,7 @@ internal bool CheckValueForKeyPermit(DBConnectionString parsetable) } DBConnectionString entry = _entry; - if (null != entry) + if (entry != null) { // also checking !hasMatch is tempting, but wrong // user can safely extend their restrictions for current rule to include missing keyword @@ -271,7 +271,7 @@ internal bool CheckValueForKeyPermit(DBConnectionString parsetable) private NameValuePermission CheckKeyForValue(string keyInQuestion) { NameValuePermission[] valuetree = _tree; // _tree won't mutate but Add will replace it - if (null != valuetree) + if (valuetree != null) { for (int i = 0; i < valuetree.Length; ++i) { 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 8a31b9679c..66c46602c5 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 @@ -66,7 +66,7 @@ internal DBConnectionString(DbConnectionOptions connectionOptions) private DBConnectionString(DbConnectionOptions connectionOptions, string restrictions, KeyRestrictionBehavior behavior, Dictionary synonyms, bool mustCloneDictionary) { // used by DBDataPermission - Debug.Assert(null != connectionOptions, "null connectionOptions"); + Debug.Assert(connectionOptions != null, "null connectionOptions"); switch (behavior) { case KeyRestrictionBehavior.PreventUsage: @@ -163,7 +163,7 @@ internal string Restrictions if (restrictions == null) { string[] restrictionValues = _restrictionValues; - if ((null != restrictionValues) && (0 < restrictionValues.Length)) + if (restrictionValues != null && (0 < restrictionValues.Length)) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < restrictionValues.Length; ++i) @@ -183,7 +183,7 @@ internal string Restrictions restrictions = builder.ToString(); } } - return ((null != restrictions) ? restrictions : ""); + return (restrictions != null ? restrictions : ""); } } @@ -380,7 +380,7 @@ internal bool IsSupersetOf(DBConnectionString entry) case KeyRestrictionBehavior.AllowOnly: // every key must either be in the restricted connection string or in the allowed keywords // keychain may contain duplicates, but it is better than GetEnumerator on _parsetable.Keys - for (NameValuePair current = entry.KeyChain; null != current; current = current.Next) + for (NameValuePair current = entry.KeyChain; current != null; current = current.Next) { if (!ContainsKey(current.Name) && IsRestrictedKeyword(current.Name)) { @@ -390,7 +390,7 @@ internal bool IsSupersetOf(DBConnectionString entry) break; case KeyRestrictionBehavior.PreventUsage: // every key can not be in the restricted keywords (even if in the restricted connection string) - if (null != _restrictionValues) + if (_restrictionValues != null) { foreach (string restriction in _restrictionValues) { @@ -423,7 +423,7 @@ static private string[] NewRestrictionAllowOnly(string[] allowonly, string[] pre } } string[] restrictionValues = null; - if (null != newlist) + if (newlist != null) { restrictionValues = newlist.ToArray(); } @@ -457,8 +457,8 @@ static private string[] NewRestrictionIntersect(string[] a, string[] b) static private string[] NoDuplicateUnion(string[] a, string[] b) { #if DEBUG - Debug.Assert(null != a && 0 < a.Length, "empty a"); - Debug.Assert(null != b && 0 < b.Length, "empty b"); + Debug.Assert(a != null && 0 < a.Length, "empty a"); + Debug.Assert(b != null && 0 < b.Length, "empty b"); Verify(a); Verify(b); #endif @@ -501,7 +501,7 @@ private static string[] ParseRestrictions(string restrictions, Dictionary KeyName='{0}'", keyname); #endif - string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144 + string realkeyname = synonyms != null ? (string)synonyms[keyname] : keyname; // MDAC 85144 if (ADP.IsEmpty(realkeyname)) { throw ADP.KeywordNotSupported(keyname); @@ -540,7 +540,7 @@ static internal string[] RemoveDuplicates(string[] restrictions) count = 0; for (int i = 0; i < restrictions.Length; ++i) { - if (null != restrictions[i]) + if (restrictions[i] != null) { tmp[count++] = restrictions[i]; } @@ -555,7 +555,7 @@ static internal string[] RemoveDuplicates(string[] restrictions) [ConditionalAttribute("DEBUG")] private static void Verify(string[] restrictionValues) { - if (null != restrictionValues) + if (restrictionValues != null) { for (int i = 1; i < restrictionValues.Length; ++i) { 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 a17621c613..e240c3d822 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 @@ -59,7 +59,7 @@ internal string ExpandKeyword(string keyword, string replacementValue) int copyPosition = 0; StringBuilder builder = new(_usersConnectionString.Length); - for (NameValuePair current = _keyChain; null != current; current = current.Next) + for (NameValuePair current = _keyChain; current != null; current = current.Next) { if ((current.Name == keyword) && (current.Value == this[keyword])) { @@ -92,7 +92,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key { throw ADP.InvalidKeyname(keyName); } - if ((null != keyValue) && !IsValueValidInternal(keyValue)) + if (keyValue != null && !IsValueValidInternal(keyValue)) { throw ADP.InvalidValue(keyName); } @@ -112,7 +112,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key } builder.Append("="); - if (null != keyValue) + if (keyValue != null) { // else =; if (useOdbcRules) { @@ -165,7 +165,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key internal static string ExpandDataDirectory(string keyword, string value, ref string datadir) { string fullPath = null; - if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) + if (value != null && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) { string rootFolderPath = datadir; @@ -174,7 +174,7 @@ internal static string ExpandDataDirectory(string keyword, string value, ref str // find the replacement path object rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory"); rootFolderPath = (rootFolderObject as string); - if ((null != rootFolderObject) && rootFolderPath == null) + if (rootFolderObject != null && rootFolderPath == null) { throw ADP.InvalidDataDirectory(); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/GreenMethods.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/GreenMethods.cs index b23728ba29..43099a0bff 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/GreenMethods.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/GreenMethods.cs @@ -33,7 +33,7 @@ internal static object MicrosoftDataSqlClientSqlProviderServices_Instance() { Type t = Type.GetType(MicrosoftDataSqlClientSqlProviderServices_TypeName, false); - if (null != t) + if (t != null) { MicrosoftDataSqlClientSqlProviderServices_Instance_FieldInfo = t.GetField("Instance", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static); } @@ -46,7 +46,7 @@ internal static object MicrosoftDataSqlClientSqlProviderServices_Instance() private static object MicrosoftDataSqlClientSqlProviderServices_Instance_GetValue() { object result = null; - if (null != MicrosoftDataSqlClientSqlProviderServices_Instance_FieldInfo) + if (MicrosoftDataSqlClientSqlProviderServices_Instance_FieldInfo != null) { result = MicrosoftDataSqlClientSqlProviderServices_Instance_FieldInfo.GetValue(null); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeMethodWrapper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeMethodWrapper.cs index bf28304b91..c3e74715ad 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeMethodWrapper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeMethodWrapper.cs @@ -130,7 +130,7 @@ internal static bool NativeSetData(void* passedData, int passedSize) { data = Marshal.AllocHGlobal(passedSize).ToPointer(); - Trace.Assert(null != data); + Trace.Assert(data != null); System.Buffer.MemoryCopy(passedData, data, passedSize, passedSize); @@ -1410,10 +1410,10 @@ internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref Sni_Consumer_Info native_consumerInfo) { native_consumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize; - native_consumerInfo.fnReadComp = null != consumerInfo.readDelegate + native_consumerInfo.fnReadComp = consumerInfo.readDelegate != null ? Marshal.GetFunctionPointerForDelegate(consumerInfo.readDelegate) : IntPtr.Zero; - native_consumerInfo.fnWriteComp = null != consumerInfo.writeDelegate + native_consumerInfo.fnWriteComp = consumerInfo.writeDelegate != null ? Marshal.GetFunctionPointerForDelegate(consumerInfo.writeDelegate) : IntPtr.Zero; native_consumerInfo.ConsumerKey = consumerInfo.key; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs index 3e44134e7f..590561d7fc 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbBuffer.cs @@ -159,7 +159,7 @@ internal byte[] ReadBytes(int offset, byte[] destination, int startIndex, int le offset += BaseOffset; Validate(offset, length); Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); - Debug.Assert(null != destination, "null destination"); + Debug.Assert(destination != null, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; @@ -192,7 +192,7 @@ internal char[] ReadChars(int offset, char[] destination, int startIndex, int le offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); - Debug.Assert(null != destination, "null destination"); + Debug.Assert(destination != null, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; @@ -251,7 +251,7 @@ internal void ReadInt16Array(int offset, short[] destination, int startIndex, in offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); - Debug.Assert(null != destination, "null destination"); + Debug.Assert(destination != null, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; @@ -303,7 +303,7 @@ internal void ReadInt32Array(int offset, int[] destination, int startIndex, int offset += BaseOffset; Validate(offset, 4 * length); Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); - Debug.Assert(null != destination, "null destination"); + Debug.Assert(destination != null, "null destination"); Debug.Assert(startIndex + length <= destination.Length, "destination too small"); bool mustRelease = false; @@ -396,7 +396,7 @@ override protected bool ReleaseHandle() private void StructureToPtr(int offset, object structure) { - Debug.Assert(null != structure, "null structure"); + Debug.Assert(structure != null, "null structure"); offset += BaseOffset; ValidateCheck(offset, Marshal.SizeOf(structure.GetType())); Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); @@ -448,7 +448,7 @@ internal void WriteBytes(int offset, byte[] source, int startIndex, int length) offset += BaseOffset; Validate(offset, length); Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); - Debug.Assert(null != source, "null source"); + Debug.Assert(source != null, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; @@ -474,7 +474,7 @@ internal void WriteCharArray(int offset, char[] source, int startIndex, int leng offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); - Debug.Assert(null != source, "null source"); + Debug.Assert(source != null, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; @@ -529,7 +529,7 @@ internal void WriteInt16Array(int offset, short[] source, int startIndex, int le offset += BaseOffset; Validate(offset, 2 * length); Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); - Debug.Assert(null != source, "null source"); + Debug.Assert(source != null, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; @@ -579,7 +579,7 @@ internal void WriteInt32Array(int offset, int[] source, int startIndex, int leng offset += BaseOffset; Validate(offset, 4 * length); Debug.Assert(0 == offset % ADP.s_ptrSize, "invalid alignment"); - Debug.Assert(null != source, "null source"); + Debug.Assert(source != null, "null source"); Debug.Assert(startIndex + length <= source.Length, "source too small"); bool mustRelease = false; 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 e83373dae1..d310981a4d 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 @@ -71,7 +71,7 @@ public void ClearAllPools() foreach (KeyValuePair entry in connectionPoolGroups) { DbConnectionPoolGroup poolGroup = entry.Value; - if (null != poolGroup) + if (poolGroup != null) { poolGroup.Clear(); } @@ -86,7 +86,7 @@ public void ClearPool(DbConnection connection) using (TryEventScope.Create(" {0}", GetObjectId(connection))) { DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); - if (null != poolGroup) + if (poolGroup != null) { poolGroup.Clear(); } @@ -123,15 +123,15 @@ virtual protected DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal i internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) { - Debug.Assert(null != owningConnection, "null owningConnection?"); - Debug.Assert(null != poolGroup, "null poolGroup?"); + Debug.Assert(owningConnection != null, "null owningConnection?"); + Debug.Assert(poolGroup != null, "null poolGroup?"); DbConnectionOptions connectionOptions = poolGroup.ConnectionOptions; DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo; DbConnectionPoolKey poolKey = poolGroup.PoolKey; DbConnectionInternal newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions); - if (null != newConnection) + if (newConnection != null) { PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakeNonPooledObject(owningConnection, PerformanceCounters); @@ -142,12 +142,12 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) { - Debug.Assert(null != pool, "null pool?"); + Debug.Assert(pool != null, "null pool?"); DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo; DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions); - if (null != newConnection) + if (newConnection != null) { PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakePooledConnection(pool); @@ -196,7 +196,7 @@ static Task GetCompletedTask() internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection) { - Debug.Assert(null != owningConnection, "null owningConnection?"); + Debug.Assert(owningConnection != null, "null owningConnection?"); DbConnectionPoolGroup poolGroup; DbConnectionPool connectionPool; @@ -379,8 +379,8 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti { // if poolgroup is disabled, it will be replaced with a new entry - Debug.Assert(null != owningObject, "null owningObject?"); - Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?"); + Debug.Assert(owningObject != null, "null owningObject?"); + Debug.Assert(connectionPoolGroup != null, "null connectionPoolGroup?"); // It is possible that while the outer connection object has // been sitting around in a closed and unused state in some long @@ -391,7 +391,7 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti // re-create the pool entry whenever it's disabled. // however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work - if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) + if (connectionPoolGroup.IsDisabled && connectionPoolGroup.PoolGroupOptions != null) { SqlClientEventSource.Log.TryTraceEvent(" {0}, DisabledPoolGroup={1}", ObjectID, connectionPoolGroup.ObjectID); @@ -400,10 +400,10 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti // get the string to hash on again DbConnectionOptions connectionOptions = connectionPoolGroup.ConnectionOptions; - Debug.Assert(null != connectionOptions, "prevent expansion of connectionString"); + Debug.Assert(connectionOptions != null, "prevent expansion of connectionString"); connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions); - Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?"); + Debug.Assert(connectionPoolGroup != null, "null connectionPoolGroup?"); SetConnectionPoolGroup(owningObject, connectionPoolGroup); } DbConnectionPool connectionPool = connectionPoolGroup.GetConnectionPool(this); @@ -419,7 +419,7 @@ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, D DbConnectionPoolGroup connectionPoolGroup; Dictionary connectionPoolGroups = _connectionPoolGroups; - if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))) + if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && connectionPoolGroup.PoolGroupOptions != null)) { // If we can't find an entry for the connection string in // our collection of pool entries, then we need to create a @@ -451,7 +451,7 @@ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, D // We don't support connection pooling on Win9x; it lacks too many of the APIs we require. if (poolOptions == null && ADP.s_isWindowsNT) { - if (null != connectionPoolGroup) + if (connectionPoolGroup != null) { // reusing existing pool option in case user originally used SetConnectionPoolOptions poolOptions = connectionPoolGroup.PoolGroupOptions; @@ -489,8 +489,8 @@ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, D Debug.Assert(!connectionPoolGroup.IsDisabled, "Disabled pool entry discovered"); } } - Debug.Assert(null != connectionPoolGroup, "how did we not create a pool entry?"); - Debug.Assert(null != userConnectionOptions, "how did we not have user connection options?"); + Debug.Assert(connectionPoolGroup != null, "how did we not create a pool entry?"); + Debug.Assert(userConnectionOptions != null, "how did we not have user connection options?"); } else if (userConnectionOptions == null) { @@ -537,7 +537,7 @@ private void PruneConnectionPoolGroups(object state) DbConnectionPool[] poolsToRelease = _poolsToRelease.ToArray(); foreach (DbConnectionPool pool in poolsToRelease) { - if (null != pool) + if (pool != null) { pool.Clear(); @@ -562,7 +562,7 @@ private void PruneConnectionPoolGroups(object state) DbConnectionPoolGroup[] poolGroupsToRelease = _poolGroupsToRelease.ToArray(); foreach (DbConnectionPoolGroup poolGroup in poolGroupsToRelease) { - if (null != poolGroup) + if (poolGroup != null) { int poolsLeft = poolGroup.Clear(); // may add entries to _poolsToRelease @@ -587,7 +587,7 @@ private void PruneConnectionPoolGroups(object state) foreach (KeyValuePair entry in connectionPoolGroups) { - if (null != entry.Value) + if (entry.Value != null) { Debug.Assert(!entry.Value.IsDisabled, "Disabled pool entry discovered"); @@ -614,7 +614,7 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) // Queue the pool up for release -- we'll clear it out and dispose // of it as the last part of the pruning timer callback so we don't // do it with the pool entry or the pool collection locked. - Debug.Assert(null != pool, "null pool?"); + Debug.Assert(pool != null, "null pool?"); // set the pool to the shutdown state to force all active // connections to be automatically disposed when they @@ -634,7 +634,7 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { - Debug.Assert(null != poolGroup, "null poolGroup?"); + Debug.Assert(poolGroup != null, "null poolGroup?"); 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 7fa6e88e27..336cb876ab 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 @@ -92,8 +92,8 @@ protected internal Transaction EnlistedTransaction set { Transaction currentEnlistedTransaction = _enlistedTransaction; - if ((currentEnlistedTransaction == null && (null != value)) - || ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value))) + if ((currentEnlistedTransaction == null && value != null) + || (currentEnlistedTransaction != null && !currentEnlistedTransaction.Equals(value))) { // WebData 20000024 // Pay attention to the order here: @@ -108,7 +108,7 @@ protected internal Transaction EnlistedTransaction Transaction previousTransactionClone = null; try { - if (null != value) + if (value != null) { valueClone = value.Clone(); } @@ -143,12 +143,12 @@ protected internal Transaction EnlistedTransaction // we really need to dispose our clones; they may have // native resources and GC may not happen soon enough. // VSDevDiv 479564: don't dispose if still holding reference in _enlistedTransaction - if (null != previousTransactionClone && + if (previousTransactionClone != null && !Object.ReferenceEquals(previousTransactionClone, _enlistedTransaction)) { previousTransactionClone.Dispose(); } - if (null != valueClone && !Object.ReferenceEquals(valueClone, _enlistedTransaction)) + if (valueClone != null && !Object.ReferenceEquals(valueClone, _enlistedTransaction)) { valueClone.Dispose(); } @@ -159,7 +159,7 @@ protected internal Transaction EnlistedTransaction // against multiple concurrent calls to enlist, which really // isn't supported anyway. - if (null != value) + if (value != null) { SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Enlisting.", ObjectID, value.GetHashCode()); TransactionOutcomeEnlist(value); @@ -450,7 +450,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac // if the DbConnectionInternal derived class needs to close the connection it should // delegate to the DbConnection if one exists or directly call dispose // DbConnection owningObject = (DbConnection)Owner; - // if (null != owningObject) { + // if (owningObject != null) { // owningObject.Close(); // force the closed state on the outer object. // } // else { @@ -460,8 +460,8 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac //////////////////////////////////////////////////////////////// // DON'T MESS WITH THIS CODE UNLESS YOU KNOW WHAT YOU'RE DOING! //////////////////////////////////////////////////////////////// - Debug.Assert(null != owningObject, "null owningObject"); - Debug.Assert(null != connectionFactory, "null connectionFactory"); + Debug.Assert(owningObject != null, "null owningObject"); + Debug.Assert(connectionFactory != null, "null connectionFactory"); SqlClientEventSource.Log.TryPoolerTraceEvent(" {0} Closing.", ObjectID); // if an exception occurs after the state change but before the try block @@ -489,7 +489,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac // The singleton closed classes won't have owners and // connection pools, and we won't want to put them back // into the pool. - if (null != connectionPool) + if (connectionPool != null) { connectionPool.PutObject(this, owningObject); // PutObject calls Deactivate for us... // NOTE: Before we leave the PutObject call, another @@ -719,7 +719,7 @@ internal void MakePooledConnection(DbConnectionPool connectionPool) internal void NotifyWeakReference(int message) { DbReferenceCollection referenceCollection = ReferenceCollection; - if (null != referenceCollection) + if (referenceCollection != null) { referenceCollection.Notify(message); } @@ -840,7 +840,7 @@ internal void PostPop(DbConnection newOwner) 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) + if (Pool != null) { if (0 != _pooledCount) { @@ -856,7 +856,7 @@ internal void PostPop(DbConnection newOwner) internal void RemoveWeakReference(object value) { DbReferenceCollection referenceCollection = ReferenceCollection; - if (null != referenceCollection) + if (referenceCollection != null) { referenceCollection.Remove(value); } @@ -929,7 +929,7 @@ internal void CleanupConnectionOnTransactionCompletion(Transaction transaction) DetachTransaction(transaction, false); DbConnectionPool pool = Pool; - if (null != pool) + if (pool != null) { pool.TransactionEnded(transaction, this); } 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 71f8b3ff2f..dc80876cd1 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 @@ -43,7 +43,7 @@ internal TransactedConnectionList(int initialAllocation, Transaction tx) : base( internal void Dispose() { - if (null != _transaction) + if (_transaction != null) { _transaction.Dispose(); } @@ -77,7 +77,7 @@ sealed private class TransactedConnectionPool internal TransactedConnectionPool(DbConnectionPool pool) { - Debug.Assert(null != pool, "null pool?"); + Debug.Assert(pool != null, "null pool?"); _pool = pool; _transactedCxns = new Dictionary(); SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Constructed for connection pool {1}", ObjectID, _pool.ObjectID); @@ -101,7 +101,7 @@ internal DbConnectionPool Pool internal DbConnectionInternal GetTransactedObject(Transaction transaction) { - Debug.Assert(null != transaction, "null transaction?"); + Debug.Assert(transaction != null, "null transaction?"); DbConnectionInternal transactedObject = null; @@ -137,7 +137,7 @@ internal DbConnectionInternal GetTransactedObject(Transaction transaction) } } - if (null != transactedObject) + if (transactedObject != null) { SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } @@ -146,8 +146,8 @@ internal DbConnectionInternal GetTransactedObject(Transaction transaction) internal void PutTransactedObject(Transaction transaction, DbConnectionInternal transactedObject) { - Debug.Assert(null != transaction, "null transaction?"); - Debug.Assert(null != transactedObject, "null transactedObject?"); + Debug.Assert(transaction != null, "null transaction?"); + Debug.Assert(transactedObject != null, "null transactedObject?"); TransactedConnectionList connections; bool txnFound = false; @@ -219,7 +219,7 @@ internal void PutTransactedObject(Transaction transaction, DbConnectionInternal } finally { - if (null != transactionClone) + if (transactionClone != null) { if (newConnections != null) { @@ -485,9 +485,9 @@ internal DbConnectionPool( DbConnectionPoolProviderInfo connectionPoolProviderInfo) { Debug.Assert(ADP.s_isWindowsNT, "Attempting to construct a connection pool on Win9x?"); - Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup"); + Debug.Assert(connectionPoolGroup != null, "null connectionPoolGroup"); - if ((null != identity) && identity.IsRestricted) + if (identity != null && identity.IsRestricted) { throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToPoolOnRestrictedToken); } @@ -647,7 +647,7 @@ internal bool UseLoadBalancing private bool UsingIntegrateSecurity { - get { return (null != _identity && DbConnectionPoolIdentity.NoIdentity != _identity); } + get { return _identity != null && DbConnectionPoolIdentity.NoIdentity != _identity; } } private void CleanupCallback(Object state) @@ -771,7 +771,7 @@ internal void Clear() { obj = _objectList[i]; - if (null != obj) + if (obj != null) { obj.DoNotPoolThisConnection(); } @@ -1014,7 +1014,7 @@ private void DeactivateObject(DbConnectionInternal obj) // thread. Transaction transaction = obj.EnlistedTransaction; - if (null != transaction) + if (transaction != null) { // NOTE: we're not locking on _state, so it's possible that its // value could change between the conditional check and here. @@ -1421,7 +1421,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj { // SQLBUDT #386664 - ensure that we release this waiter, regardless // of any exceptions that may be thrown. - if (null != obj) + if (obj != null) { Interlocked.Decrement(ref _waitCount); } @@ -1536,7 +1536,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 (obj != null && obj.IsAccessTokenExpired) { DestroyObject(obj); obj = null; @@ -1544,7 +1544,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj } while (obj == null); } - if (null != obj) + if (obj != null) { PrepareConnection(owningObject, obj, transaction); } @@ -1622,7 +1622,7 @@ private DbConnectionInternal GetFromGeneralPool() // checked bits. The assert is benign, so we're commenting it out. //Debug.Assert(obj != null, "GetFromGeneralPool called with nothing in the pool!"); - if (null != obj) + if (obj != null) { SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Popped from general pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfFreeConnections.Decrement(); @@ -1635,11 +1635,11 @@ private DbConnectionInternal GetFromTransactedPool(out Transaction transaction) transaction = ADP.GetCurrentTransaction(); DbConnectionInternal obj = null; - if (null != transaction && null != _transactedConnectionPool) + if (transaction != null && _transactedConnectionPool != null) { obj = _transactedConnectionPool.GetTransactedObject(transaction); - if (null != obj) + if (obj != null) { SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Popped from transacted pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfFreeConnections.Decrement(); @@ -1739,7 +1739,7 @@ private void PoolCreateRequest(object state) // We do not need to check error flag here, since we know if // CreateObject returned null, we are in error case. - if (null != newObj) + if (newObj != null) { PutNewObject(newObj); } @@ -1799,7 +1799,7 @@ private void PoolCreateRequest(object state) internal void PutNewObject(DbConnectionInternal obj) { - Debug.Assert(null != obj, "why are we adding a null object to the pool?"); + Debug.Assert(obj != null, "why are we adding a null object to the pool?"); // VSTFDEVDIV 742887 - When another thread is clearing this pool, it // will set _cannotBePooled for all connections in this pool without prejudice which @@ -1816,7 +1816,7 @@ internal void PutNewObject(DbConnectionInternal obj) internal void PutObject(DbConnectionInternal obj, object owningObject) { - Debug.Assert(null != obj, "null obj?"); + Debug.Assert(obj != null, "null obj?"); PerformanceCounters.SoftDisconnectsPerSecond.Increment(); @@ -1844,7 +1844,7 @@ internal void PutObject(DbConnectionInternal obj, object owningObject) internal void PutObjectFromTransactedPool(DbConnectionInternal obj) { - Debug.Assert(null != obj, "null pooledObject?"); + Debug.Assert(obj != null, "null pooledObject?"); Debug.Assert(obj.EnlistedTransaction == null, "pooledObject is still enlisted?"); // called by the transacted connection pool , once it's removed the @@ -1892,7 +1892,7 @@ private bool ReclaimEmancipatedObjects() { DbConnectionInternal obj = _objectList[i]; - if (null != obj) + if (obj != null) { bool locked = false; @@ -1962,7 +1962,7 @@ internal void Shutdown() // deactivate timer callbacks Timer t = _cleanupTimer; _cleanupTimer = null; - if (null != t) + if (t != null) { t.Dispose(); } @@ -1974,8 +1974,8 @@ internal void Shutdown() // other objects is unnecessary (hence the asymmetry of Ended but no Begin) internal void TransactionEnded(Transaction transaction, DbConnectionInternal transactedObject) { - Debug.Assert(null != transaction, "null transaction?"); - Debug.Assert(null != transactedObject, "null transactedObject?"); + Debug.Assert(transaction != null, "null transaction?"); + Debug.Assert(transactedObject != null, "null transactedObject?"); // Note: connection may still be associated with transaction due to Explicit Unbinding requirement. SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); @@ -1985,7 +1985,7 @@ internal void TransactionEnded(Transaction transaction, DbConnectionInternal tra // the connection from it's list, then we put the connection back in // general circulation. TransactedConnectionPool transactedConnectionPool = _transactedConnectionPool; - if (null != transactedConnectionPool) + if (transactedConnectionPool != null) { transactedConnectionPool.TransactionEnded(transaction, transactedObject); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolCounters.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolCounters.cs index 9ebe2b48f1..72823f2c5a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolCounters.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolCounters.cs @@ -123,7 +123,7 @@ internal Counter(string categoryName, string instanceName, string counterName, P internal void Decrement() { PerformanceCounter instance = _instance; - if (null != instance) + if (instance != null) { instance.Decrement(); } @@ -134,7 +134,7 @@ internal void Dispose() { // TODO: race condition, Dispose at the same time as Increment/Decrement PerformanceCounter instance = _instance; _instance = null; - if (null != instance) + if (instance != null) { instance.RemoveInstance(); // should we be calling instance.Close? @@ -146,7 +146,7 @@ internal void Dispose() internal void Increment() { PerformanceCounter instance = _instance; - if (null != instance) + if (instance != null) { instance.Increment(); } @@ -229,7 +229,7 @@ private string GetAssemblyName() // First try GetEntryAssembly name, then AppDomain.FriendlyName. Assembly assembly = Assembly.GetEntryAssembly(); - if (null != assembly) + if (assembly != null) { AssemblyName name = assembly.GetName(); if (name != null) @@ -253,7 +253,7 @@ private string GetInstanceName() if (ADP.IsEmpty(instanceName)) { AppDomain appDomain = AppDomain.CurrentDomain; - if (null != appDomain) + if (appDomain != null) { instanceName = appDomain.FriendlyName; } @@ -315,7 +315,7 @@ public void Dispose() [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] private void SafeDispose(Counter counter) { // WebData 103603 - if (null != counter) + if (counter != null) { counter.Dispose(); } @@ -324,7 +324,7 @@ private void SafeDispose(Counter counter) [PrePrepareMethod] void ExceptionEventHandler(object sender, UnhandledExceptionEventArgs e) { - if ((null != e) && e.IsTerminating) + if (e != null && e.IsTerminating) { Dispose(); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs index 2bbf57eb76..ef79538a0e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.cs @@ -70,7 +70,7 @@ static private byte[] CreateWellKnownSid(WellKnownSidType sidType) override public bool Equals(object value) { bool result = ((this == NoIdentity) || (this == value)); - if (!result && (null != value)) + if (!result && value != null) { DbConnectionPoolIdentity that = ((DbConnectionPoolIdentity)value); result = ((this._sidString == that._sidString) && (this._isRestricted == that._isRestricted) && (this._isNetwork == that._isNetwork)); 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 b908356739..fff42157fd 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 @@ -199,7 +199,7 @@ private static T FetchConfigurationSection(string name) { Type t = typeof(T); object section = ConfigurationManager.GetSection(name); - if (null != section) + if (section != null) { if (section is ConfigurationSection configSection && configSection.GetType() == t) { 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 1ba7f9a6a1..0f43f46da1 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 @@ -401,7 +401,7 @@ internal SqlStatistics Statistics { get { - if (null != _connection) + if (_connection != null) { if (_connection.StatisticsEnabled) { @@ -723,7 +723,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i { updateBulkCommandText.Append(" COLLATE " + collation_name.Value); // VSTFDEVDIV 461426: compare collations only if the collation value was set on the metadata - if (null != _sqlDataReaderRowSource && metadata.collation != null) + if (_sqlDataReaderRowSource != null && metadata.collation != null) { // On SqlDataReader we can verify the sourcecolumn collation! int sourceColumnId = _localColumnMappings[assocId]._internalSourceColumnOrdinal; @@ -888,7 +888,7 @@ private void Dispose(bool disposing) try { Debug.Assert(_internalTransaction == null, "Internal transaction exists during dispose"); - if (null != _internalTransaction) + if (_internalTransaction != null) { _internalTransaction.Rollback(); _internalTransaction.Dispose(); @@ -964,7 +964,7 @@ private object GetValueFromSourceRow(int destRowIndex, out bool isSqlType, out b } } // SqlDataReader-specific logic - else if (null != _sqlDataReaderRowSource) + else if (_sqlDataReaderRowSource != null) { if (_currentRowMetadata[destRowIndex].IsSqlType) { @@ -1343,7 +1343,7 @@ private void CreateOrValidateConnection(string method) // If we have a transaction, check to ensure that the active // connection property matches the connection associated with // the transaction. - if (null != _externalTransaction && _connection != _externalTransaction.Connection) + if (_externalTransaction != null && _connection != _externalTransaction.Connection) { throw ADP.TransactionConnectionMismatch(); } @@ -1386,7 +1386,7 @@ private void RunParserReliably(BulkCopySimpleResultSet bulkCopyHandler = null) private void CommitTransaction() { - if (null != _internalTransaction) + if (_internalTransaction != null) { SqlInternalConnectionTds internalConnection = _connection.GetOpenTdsConnection(); internalConnection.ThreadHasParserLockForClose = true; // In case of error, let the connection know that we have the lock @@ -1811,7 +1811,7 @@ public void WriteToServer(DataRow[] rows) statistics = SqlStatistics.StartTimer(Statistics); ResetWriteToServerGlobalVariables(); DataTable table = rows[0].Table; - Debug.Assert(null != table, "How can we have rows without a table?"); + Debug.Assert(table != null, "How can we have rows without a table?"); _rowStateToSkip = DataRowState.Deleted; // Don't allow deleted rows _rowSource = rows; _dataTableSource = table; @@ -1866,7 +1866,7 @@ public Task WriteToServerAsync(DataRow[] rows, CancellationToken cancellationTok } DataTable table = rows[0].Table; - Debug.Assert(null != table, "How can we have rows without a table?"); + Debug.Assert(table != null, "How can we have rows without a table?"); _rowStateToSkip = DataRowState.Deleted; // Don't allow deleted rows _rowSource = rows; _dataTableSource = table; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientPermission.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientPermission.cs index 163319dd7d..7672804655 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientPermission.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientPermission.cs @@ -50,7 +50,7 @@ internal SqlClientPermission(SqlClientPermissionAttribute permissionAttribute) : internal SqlClientPermission(SqlConnectionString constr) : base(PermissionState.None) { // for Open - if (null != constr) + if (constr != null) { AllowBlankPassword = constr.HasBlankPassword; // MDAC 84563 AddPermissionEntry(new DBConnectionString(constr)); @@ -114,11 +114,11 @@ private void CopyFrom(SqlClientPermission permission) { if (!_IsUnrestricted) { - if (null != permission._keyvalues) + if (permission._keyvalues != null) { _keyvalues = (ArrayList)permission._keyvalues.Clone(); - if (null != permission._keyvaluetree) + if (permission._keyvaluetree != null) { _keyvaluetree = permission._keyvaluetree.CopyNameValue(); } @@ -151,7 +151,7 @@ override public IPermission Intersect(IPermission target) SqlClientPermission newPermission = (SqlClientPermission)operand.Copy(); newPermission.AllowBlankPassword &= AllowBlankPassword; - if ((null != _keyvalues) && (null != newPermission._keyvalues)) + if (_keyvalues != null && newPermission._keyvalues != null) { newPermission._keyvalues.Clear(); @@ -198,11 +198,11 @@ override public bool IsSubsetOf(IPermission target) { if (!IsUnrestricted() && (!AllowBlankPassword || superset.AllowBlankPassword) && - (_keyvalues == null || (null != superset._keyvaluetree))) + (_keyvalues == null || superset._keyvaluetree != null)) { subset = true; - if (null != _keyvalues) + if (_keyvalues != null) { foreach (DBConnectionString kventry in _keyvalues) { @@ -239,7 +239,7 @@ override public IPermission Union(IPermission target) { newPermission.AllowBlankPassword |= AllowBlankPassword; - if (null != _keyvalues) + if (_keyvalues != null) { foreach (DBConnectionString entry in _keyvalues) { @@ -252,7 +252,7 @@ override public IPermission Union(IPermission target) private string DecodeXmlValue(string value) { - if ((null != value) && (0 < value.Length)) + if (value != null && (0 < value.Length)) { value = value.Replace(""", "\""); value = value.Replace("'", "\'"); @@ -265,7 +265,7 @@ private string DecodeXmlValue(string value) private string EncodeXmlValue(string value) { - if ((null != value) && (0 < value.Length)) + if (value != null && (0 < value.Length)) { value = value.Replace('\0', ' '); // assumption that '\0' will only be at end of string value = value.Trim(); @@ -295,34 +295,34 @@ override public void FromXml(SecurityElement securityElement) throw ADP.NotAPermissionElement(); } String version = securityElement.Attribute(XmlStr._Version); - if ((null != version) && !version.Equals(XmlStr._VersionNumber)) + if (version != null && !version.Equals(XmlStr._VersionNumber)) { throw ADP.InvalidXMLBadVersion(); } string unrestrictedValue = securityElement.Attribute(XmlStr._Unrestricted); - _IsUnrestricted = (null != unrestrictedValue) && Boolean.Parse(unrestrictedValue); + _IsUnrestricted = unrestrictedValue != null && Boolean.Parse(unrestrictedValue); Clear(); // MDAC 83105 if (!_IsUnrestricted) { string allowNull = securityElement.Attribute(XmlStr._AllowBlankPassword); - AllowBlankPassword = (null != allowNull) && Boolean.Parse(allowNull); + AllowBlankPassword = allowNull != null && Boolean.Parse(allowNull); ArrayList children = securityElement.Children; - if (null != children) + if (children != null) { foreach (SecurityElement keyElement in children) { tag = keyElement.Tag; - if ((XmlStr._add == tag) || ((null != tag) && (XmlStr._add == tag.ToLower(CultureInfo.InvariantCulture)))) + if (XmlStr._add == tag || (tag != null && XmlStr._add == tag.ToLower(CultureInfo.InvariantCulture))) { string constr = keyElement.Attribute(XmlStr._ConnectionString); string restrt = keyElement.Attribute(XmlStr._KeyRestrictions); string behavr = keyElement.Attribute(XmlStr._KeyRestrictionBehavior); KeyRestrictionBehavior behavior = KeyRestrictionBehavior.AllowOnly; - if (null != behavr) + if (behavr != null) { behavior = (KeyRestrictionBehavior)Enum.Parse(typeof(KeyRestrictionBehavior), behavr, true); } @@ -360,7 +360,7 @@ override public SecurityElement ToXml() { root.AddAttribute(XmlStr._AllowBlankPassword, AllowBlankPassword.ToString(CultureInfo.InvariantCulture)); - if (null != _keyvalues) + if (_keyvalues != null) { foreach (DBConnectionString value in _keyvalues) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientWrapperSmiStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientWrapperSmiStream.cs index 8a7b1ee275..a728b608ed 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientWrapperSmiStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientWrapperSmiStream.cs @@ -16,8 +16,8 @@ internal class SqlClientWrapperSmiStream : Stream internal SqlClientWrapperSmiStream(SmiEventSink_Default sink, SmiStream stream) { - Debug.Assert(null != sink); - Debug.Assert(null != stream); + Debug.Assert(sink != null); + Debug.Assert(stream != null); _sink = sink; _stream = stream; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientWrapperSmiStreamChars.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientWrapperSmiStreamChars.cs index 2cbba15d72..99eeb4d91c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientWrapperSmiStreamChars.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlClientWrapperSmiStreamChars.cs @@ -19,8 +19,8 @@ internal class SqlClientWrapperSmiStreamChars : SqlStreamChars internal SqlClientWrapperSmiStreamChars(SmiEventSink_Default sink, SmiStream stream) { - Debug.Assert(null != sink); - Debug.Assert(null != stream); + Debug.Assert(sink != null); + Debug.Assert(stream != null); _sink = sink; _stream = stream; } 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 e2206ee955..ba860f106f 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 @@ -215,7 +215,7 @@ internal string CachedSetOptions } internal bool PendingAsyncOperation { - get { return (null != _cachedAsyncResult); } + get { return (_cachedAsyncResult != null); } } internal string EndMethodName { @@ -257,7 +257,7 @@ internal void SetActiveConnectionAndResult(TaskCompletionSource completi _cachedAsyncCloseCount = activeConnection.CloseCount; _cachedAsyncResult = completion; - if (null != activeConnection && !parser.MARSOn) + if (activeConnection != null && !parser.MARSOn) { if (activeConnection.AsyncCommandInProgress) throw SQL.MARSUnsupportedOnConnection(); @@ -379,7 +379,7 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp if (SqlClientEventSource.Log.IsAdvancedTraceOn()) { - if (null != metaData) + if (metaData != null) { for (int i = 0; i < metaData.Length; i++) { @@ -518,7 +518,7 @@ private SqlCommand(SqlCommand from) : this() // Check to see if the currently set transaction has completed. If so, // null out our local reference. - if (null != _transaction && _transaction.Connection == null) + if (_transaction != null && _transaction.Connection == null) { _transaction = null; } @@ -689,7 +689,7 @@ internal SqlStatistics Statistics { get { - if (null != _activeConnection) + if (_activeConnection != null) { if (_activeConnection.StatisticsEnabled) { @@ -711,7 +711,7 @@ internal SqlStatistics Statistics get { // if the transaction object has been zombied, just return null - if ((null != _transaction) && _transaction.Connection == null) + if (_transaction != null && _transaction.Connection == null) { _transaction = null; } @@ -987,7 +987,7 @@ internal void OnStatementCompleted(int recordCount) if (0 <= recordCount) { StatementCompletedEventHandler handler = _statementCompletedEventHandler; - if (null != handler) + if (handler != null) { try { @@ -1022,7 +1022,7 @@ public override void Prepare() _pendingCancel = false; // Context connection's prepare is a no-op - if (null != _activeConnection && _activeConnection.IsContextConnection) + if (_activeConnection != null && _activeConnection.IsContextConnection) { return; } @@ -1046,7 +1046,7 @@ public override void Prepare() ) { - if (null != Statistics) + if (Statistics != null) { Statistics.SafeIncrement(ref Statistics._prepares); } @@ -1068,7 +1068,7 @@ public override void Prepare() GetStateObject(); // Loop through parameters ensuring that we do not have unspecified types, sizes, scales, or precisions - if (null != _parameters) + if (_parameters != null) { int count = _parameters.Count; for (int i = 0; i < count; ++i) @@ -1148,8 +1148,8 @@ private void InternalPrepare() } Debug.Assert(_execType != EXECTYPE.PREPARED, "Invalid attempt to Prepare already Prepared command!"); Debug.Assert(_activeConnection != null, "must have an open connection to Prepare"); - Debug.Assert(null != _stateObj, "TdsParserStateObject should not be null"); - Debug.Assert(null != _stateObj.Parser, "TdsParser class should not be null in Command.Execute!"); + Debug.Assert(_stateObj != null, "TdsParserStateObject should not be null"); + Debug.Assert(_stateObj.Parser != null, "TdsParser class should not be null in Command.Execute!"); Debug.Assert(_stateObj.Parser == _activeConnection.Parser, "stateobject parser not same as connection parser"); Debug.Assert(false == _inPrepare, "Already in Prepare cycle, this.inPrepare should be false!"); @@ -1159,7 +1159,7 @@ private void InternalPrepare() _preparedConnectionCloseCount = _activeConnection.CloseCount; _preparedConnectionReconnectCount = _activeConnection.ReconnectCount; - if (null != Statistics) + if (Statistics != null) { Statistics.SafeIncrement(ref Statistics._prepares); } @@ -1283,7 +1283,7 @@ public override void Cancel() _pendingCancel = true; TdsParserStateObject stateObj = _stateObj; - if (null != stateObj) + if (stateObj != null) { stateObj.Cancel(ObjectID); } @@ -1727,7 +1727,7 @@ private void BeginExecuteNonQueryInternalReadStage(TaskCompletionSource { // Similarly, if an exception occurs put the stateObj back into the pool. // and reset async cache information to allow a second async execute - if (null != _cachedAsyncState) + if (_cachedAsyncState != null) { _cachedAsyncState.ResetAsyncState(); } @@ -1985,7 +1985,7 @@ private object InternalEndExecuteNonQuery(IAsyncResult asyncResult, string endMe else { // otherwise, use a full-fledged execute that can handle params and stored procs SqlDataReader reader = CompleteAsyncExecuteReader(isInternal); - if (null != reader) + if (reader != null) { reader.Close(); } @@ -2036,7 +2036,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st { SqlClientEventSource.Log.TryTraceEvent("SqlCommand.InternalExecuteNonQuery | INFO | ObjectId {0}, Client Connection Id {1}, AsyncCommandInProgress={2}", _activeConnection?.ObjectID, _activeConnection?.ClientConnectionId, _activeConnection?.AsyncCommandInProgress); - bool async = (null != completion); + bool async = completion != null; usedCache = false; SqlStatistics statistics = Statistics; @@ -2070,7 +2070,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st // only send over SQL Batch command if we are not a stored proc and have no parameters and not in batch RPC mode if (_activeConnection.IsContextConnection) { - if (null != statistics) + if (statistics != null) { statistics.SafeIncrement(ref statistics._unpreparedExecs); } @@ -2083,7 +2083,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st else if (!ShouldUseEnclaveBasedWorkflow && !_batchRPCMode && (System.Data.CommandType.Text == this.CommandType) && (0 == GetParameterCount(_parameters))) { Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); - if (null != statistics) + if (statistics != null) { if (!this.IsDirty && this.IsPrepared) { @@ -2107,7 +2107,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st 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) + if (reader != null) { if (task != null) { @@ -2338,7 +2338,7 @@ private void BeginExecuteXmlReaderInternalReadStage(TaskCompletionSource { // Similarly, if an exception occurs put the stateObj back into the pool. // and reset async cache information to allow a second async execute - if (null != _cachedAsyncState) + if (_cachedAsyncState != null) { _cachedAsyncState.ResetAsyncState(); } @@ -2437,9 +2437,9 @@ private XmlReader CompleteXmlReader(SqlDataReader ds, bool async = false) XmlReader xr = null; SmiExtendedMetaData[] md = ds.GetInternalSmiMetaData(); - bool isXmlCapable = (null != md && md.Length == 1 && (md[0].SqlDbType == SqlDbType.NText - || md[0].SqlDbType == SqlDbType.NVarChar - || md[0].SqlDbType == SqlDbType.Xml)); + bool isXmlCapable = (md != null && md.Length == 1 && (md[0].SqlDbType == SqlDbType.NText + || md[0].SqlDbType == SqlDbType.NVarChar + || md[0].SqlDbType == SqlDbType.Xml)); if (isXmlCapable) { @@ -2846,7 +2846,7 @@ private bool TriggerInternalEndAndRetryIfNecessary(CommandBehavior behavior, obj if (!shouldRetry) { // If we cannot retry, Reset the async state to make sure we leave a clean state. - if (null != _cachedAsyncState) + if (_cachedAsyncState != null) { _cachedAsyncState.ResetAsyncState(); } @@ -2974,7 +2974,7 @@ private void BeginExecuteReaderInternalReadStage(TaskCompletionSource co { // Similarly, if an exception occurs put the stateObj back into the pool. // and reset async cache information to allow a second async execute - if (null != _cachedAsyncState) + if (_cachedAsyncState != null) { _cachedAsyncState.ResetAsyncState(); } @@ -3434,7 +3434,7 @@ internal List GetColumnEncryptionCustomKeyStoreProvidersNames() // with the function below, ideally we should have support from the server for this. private static string UnquoteProcedurePart(string part) { - if ((null != part) && (2 <= part.Length)) + if (part != null && (2 <= part.Length)) { if ('[' == part[0] && ']' == part[part.Length - 1]) { @@ -3454,7 +3454,7 @@ private static string UnquoteProcedureName(string name, out object groupNumber) groupNumber = null; // Out param - initialize value to no value. string sproc = name; - if (null != sproc) + if (sproc != null) { if (char.IsDigit(sproc[sproc.Length - 1])) { // If last char is a digit, parse. @@ -3626,7 +3626,7 @@ internal void DeriveParameters() paramsCmd.Parameters.Add(new SqlParameter("@procedure_name", SqlDbType.NVarChar, 255)); paramsCmd.Parameters[0].Value = UnquoteProcedureName(parsedSProc[3], out groupNumber); // ProcedureName is 4rd element in parsed array - if (null != groupNumber) + if (groupNumber != null) { SqlParameter param = paramsCmd.Parameters.Add(new SqlParameter("@group_number", SqlDbType.Int)); param.Value = groupNumber; @@ -3856,7 +3856,7 @@ private void CheckNotificationStateAndAutoEnlist() // Map to dependency by ID set in context data. SqlDependency dependency = SqlDependencyPerAppDomainDispatcher.SingletonInstance.LookupDependencyEntry(notifyContext); - if (null != dependency) + if (dependency != null) { // Add this command to the dependency. dependency.AddCommandDependency(this); @@ -3873,7 +3873,7 @@ private void CheckNotificationStateAndAutoEnlist() // There is a variance in order between Start(), SqlDependency(), and Execute. This is the // best way to solve that problem. - if (null != Notification) + if (Notification != null) { if (_sqlDep != null) { @@ -4082,7 +4082,7 @@ private void RunExecuteNonQuerySmi(bool sendToPipe) finally { TdsParser.ReliabilitySection.Assert("unreliable call to RunExecuteNonQuerySmi"); // you need to setup for a thread abort somewhere before you call this method - if (null != eventStream && processFinallyBlock) + if (eventStream != null && processFinallyBlock) { eventStream.Close(EventSink); } @@ -4168,7 +4168,7 @@ private void PrepareTransparentEncryptionFinallyBlock(bool closeDataReader, if (closeDataReader) { // Close the data reader to reset the _stateObj - if (null != describeParameterEncryptionDataReader) + if (describeParameterEncryptionDataReader != null) { describeParameterEncryptionDataReader.Close(); } @@ -5135,7 +5135,7 @@ internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior // task is created in case of pending asynchronous write, returned SqlDataReader should not be utilized until that task is complete internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, bool returnStream, string method, TaskCompletionSource completion, int timeout, out Task task, out bool usedCache, bool asyncWrite = false, bool inRetry = false) { - bool async = (null != completion); + bool async = completion != null; usedCache = false; task = null; @@ -5175,7 +5175,7 @@ internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection); SqlStatistics statistics = Statistics; - if (null != statistics) + if (statistics != null) { if ((!this.IsDirty && this.IsPrepared && !_hiddenPrepare) || (this.IsPrepared && _execType == EXECTYPE.PREPAREPENDING)) @@ -5458,7 +5458,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi // make sure we have good parameter information // prepare the command // execute - Debug.Assert(null != _activeConnection.Parser, "TdsParser class should not be null in Command.Execute!"); + Debug.Assert(_activeConnection.Parser != null, "TdsParser class should not be null in Command.Execute!"); bool inSchema = (0 != (cmdBehavior & CommandBehavior.SchemaOnly)); @@ -5606,7 +5606,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi } // turn set options ON - if (null != optionSettings) + if (optionSettings != null) { Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(optionSettings, timeout, this.Notification, _stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -5662,7 +5662,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi if (decrementAsyncCountOnFailure) { SqlInternalConnectionTds innerConnectionTds = (_activeConnection.InnerConnection as SqlInternalConnectionTds); - if (null != innerConnectionTds) + if (innerConnectionTds != null) { // it may be closed innerConnectionTds.DecrementAsyncCount(); } @@ -5749,7 +5749,7 @@ private SqlDataReader RunExecuteReaderSmi(CommandBehavior cmdBehavior, RunBehavi throw; } - if (null != eventStream) + if (eventStream != null) { eventStream.Close(EventSink); // UNDONE: should cancel instead! } @@ -5837,7 +5837,7 @@ private void FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, stri _execType = EXECTYPE.PREPAREPENDING; // reset execution type to pending } - if (null != ds) + if (ds != null) { ds.Close(); } @@ -5953,8 +5953,8 @@ private void ValidateCommand(string method, bool async) // Ensure that if column encryption override was used then server supports its if (((SqlCommandColumnEncryptionSetting.UseConnectionSetting == ColumnEncryptionSetting && _activeConnection.IsColumnEncryptionSettingEnabled) || (ColumnEncryptionSetting == SqlCommandColumnEncryptionSetting.Enabled || ColumnEncryptionSetting == SqlCommandColumnEncryptionSetting.ResultSetOnly)) - && null != tdsConnection - && null != tdsConnection.Parser + && tdsConnection != null + && tdsConnection.Parser != null && !tdsConnection.Parser.IsColumnEncryptionSupported) { throw SQL.TceNotSupported(); @@ -6028,7 +6028,7 @@ private void ValidateCommand(string method, bool async) } // Check to see if the currently set transaction has completed. If so, // null out our local reference. - if (null != _transaction && _transaction.Connection == null) + if (_transaction != null && _transaction.Connection == null) { _transaction = null; } @@ -6043,7 +6043,7 @@ private void ValidateCommand(string method, bool async) // if we have a transaction, check to ensure that the active // connection property matches the connection associated with // the transaction - if (null != _transaction && _activeConnection != _transaction.Connection) + if (_transaction != null && _activeConnection != _transaction.Connection) { throw ADP.TransactionConnectionMismatch(); } @@ -6086,7 +6086,7 @@ private void ValidateAsyncCommand() private void GetStateObject(TdsParser parser = null) { Debug.Assert(_stateObj == null, "StateObject not null on GetStateObject"); - Debug.Assert(null != _activeConnection, "no active connection?"); + Debug.Assert(_activeConnection != null, "no active connection?"); if (_pendingCancel) { @@ -6177,7 +6177,7 @@ private void PutStateObject() TdsParserStateObject stateObj = _stateObj; _stateObj = null; - if (null != stateObj) + if (stateObj != null) { stateObj.CloseSession(); } @@ -6272,7 +6272,7 @@ internal void OnReturnStatus(int status) object v = parameter.Value; // if the user bound a sqlint32 (the only valid one for status, use it) - if ((null != v) && (v.GetType() == typeof(SqlInt32))) + if (v != null && (v.GetType() == typeof(SqlInt32))) { parameter.Value = new SqlInt32(status); // value type } @@ -6318,7 +6318,7 @@ internal void OnReturnValue(SqlReturnValue rec, TdsParserStateObject stateObj) SqlParameter thisParam = GetParameterForOutputValueExtraction(parameters, rec.parameter, count); - if (null != thisParam) + if (thisParam != null) { // If the parameter's direction is InputOutput, Output or ReturnValue and it needs to be transparently encrypted/decrypted // then simply decrypt, deserialize and set the value. @@ -6438,7 +6438,7 @@ internal void OnReturnValue(SqlReturnValue rec, TdsParserStateObject stateObj) else if (rec.type == SqlDbType.Xml) { SqlCachedBuffer cachedBuffer = (thisParam.Value as SqlCachedBuffer); - if (null != cachedBuffer) + if (cachedBuffer != null) { thisParam.Value = cachedBuffer.ToString(); } @@ -6457,7 +6457,7 @@ internal void OnReturnValue(SqlReturnValue rec, TdsParserStateObject stateObj) internal void OnParametersAvailableSmi(SmiParameterMetaData[] paramMetaData, ITypedGettersV3 parameterValues) { - Debug.Assert(null != paramMetaData); + Debug.Assert(paramMetaData != null); for (int index = 0; index < paramMetaData.Length; index++) { @@ -6479,7 +6479,7 @@ internal void OnParameterAvailableSmi(SmiParameterMetaData metaData, ITypedGette int count = GetParameterCount(parameters); SqlParameter param = GetParameterForOutputValueExtraction(parameters, name, count); - if (null != param) + if (param != null) { param.LocaleId = (int)metaData.LocaleId; param.CompareInfo = metaData.CompareOptions; @@ -6495,7 +6495,7 @@ internal void OnParameterAvailableSmi(SmiParameterMetaData metaData, ITypedGette result = ValueUtilsSmi.GetOutputParameterV3Smi( OutParamEventSink, parameterValues, ordinal, metaData, _smiRequestContext, buffer); } - if (null != result) + if (result != null) { param.Value = result; } @@ -6804,7 +6804,7 @@ private int CountSendableParameters(SqlParameterCollection parameters) // Returns total number of parameters private static int GetParameterCount(SqlParameterCollection parameters) { - return (null != parameters) ? parameters.Count : 0; + return parameters != null ? parameters.Count : 0; } // @@ -7143,7 +7143,7 @@ internal string BuildParamList(TdsParser parser, SqlParameterCollection paramete string s = null; // deal with the sql types - if ((null != val) && (DBNull.Value != val)) + if (val != null && (DBNull.Value != val)) { s = (val as string); if (s == null) @@ -7156,7 +7156,7 @@ internal string BuildParamList(TdsParser parser, SqlParameterCollection paramete } } - if (null != s) + if (s != null) { int actualBytes = parser.GetEncodingCharLength(s, sqlParam.GetActualSize(), sqlParam.Offset, null); // if actual number of bytes is greater than the user given number of chars, use actual bytes @@ -7208,7 +7208,7 @@ private static string QuoteIdentifier(string[] strings, int offset, int length) { bld.Append('.'); } - if (null != strings[i] && 0 != strings[i].Length) + if (strings[i] != null && 0 != strings[i].Length) { ADP.AppendQuotedString(bld, "[", "]", strings[i]); } @@ -7327,7 +7327,7 @@ internal bool IsDirty // only mark the command as dirty if it is already prepared // but always clear the value if it we are clearing the dirty flag _dirty = value ? IsPrepared : false; - if (null != _parameters) + if (_parameters != null) { _parameters.IsDirty = _dirty; } @@ -7537,7 +7537,7 @@ private SmiRequestExecutor SetUpSmiRequest(SqlInternalConnectionSmi innerConnect // strings, the user could extend the length and overwrite // the buffer. - if (null != Notification) + if (Notification != null) { throw SQL.NotificationsNotAvailableOnContextConnection(); } @@ -7662,7 +7662,7 @@ private SmiRequestExecutor SetUpSmiRequest(SqlInternalConnectionSmi innerConnect // Size limiting for larger values will happen due to MaxLength // NOTE: assumes xml and udt types are handled in parameter value coercion // since server does not allow these types in a variant - if (null != value) + if (value != null) { MetaType mt = MetaType.GetMetaTypeFromValue(value); @@ -7677,7 +7677,7 @@ private SmiRequestExecutor SetUpSmiRequest(SqlInternalConnectionSmi innerConnect case SqlDbType.Xml: // Xml is an issue for non-SqlXml types - if (null != value && ExtendedClrTypeCode.SqlXml != typeCode) + if (value != null && ExtendedClrTypeCode.SqlXml != typeCode) { throw SQL.ParameterSizeRestrictionFailure(index); } 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 f9bfc41275..62145bc69e 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 @@ -513,7 +513,7 @@ public bool StatisticsEnabled else { // stop - if (null != _statistics) + if (_statistics != null) { if (ConnectionState.Open == State) { @@ -653,7 +653,7 @@ private bool UsesIntegratedSecurity(SqlConnectionString opt) private bool UsesClearUserIdOrPassword(SqlConnectionString opt) { bool result = false; - if (null != opt) + if (opt != null) { result = (!ADP.IsEmpty(opt.UserID) || !ADP.IsEmpty(opt.Password)); } @@ -789,7 +789,7 @@ public int CommandTimeout get { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; - return ((null != constr) ? constr.CommandTimeout : SqlConnectionString.DEFAULT.Command_Timeout); + return constr != null ? constr.CommandTimeout : SqlConnectionString.DEFAULT.Command_Timeout; } } @@ -879,7 +879,7 @@ override public int ConnectionTimeout get { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; - return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout); + return constr != null ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout; } } @@ -898,14 +898,14 @@ override public string Database SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; - if (null != innerConnection) + if (innerConnection != null) { result = innerConnection.CurrentDatabase; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; - result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog); + result = constr != null ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog; } return result; } @@ -922,7 +922,7 @@ internal string SQLDNSCachingSupportedState SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); string result; - if (null != innerConnection) + if (innerConnection != null) { result = innerConnection.IsSQLDNSCachingSupported ? "true" : "false"; } @@ -946,7 +946,7 @@ internal string SQLDNSCachingSupportedStateBeforeRedirect SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); string result; - if (null != innerConnection) + if (innerConnection != null) { result = innerConnection.IsDNSCachingBeforeRedirectSupported ? "true" : "false"; } @@ -972,14 +972,14 @@ override public string DataSource SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; - if (null != innerConnection) + if (innerConnection != null) { result = innerConnection.CurrentDataSource; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; - result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source); + result = constr != null ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source; } return result; } @@ -1006,14 +1006,14 @@ public int PacketSize SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); int result; - if (null != innerConnection) + if (innerConnection != null) { result = innerConnection.PacketSize; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; - result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size); + result = constr != null ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size; } return result; } @@ -1032,7 +1032,7 @@ public Guid ClientConnectionId SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); - if (null != innerConnection) + if (innerConnection != null) { return innerConnection.ClientConnectionId; } @@ -1041,7 +1041,7 @@ public Guid ClientConnectionId Task reconnectTask = _currentReconnectionTask; // Connection closed but previously open should return the correct ClientConnectionId DbConnectionClosedPreviouslyOpened innerConnectionClosed = (InnerConnection as DbConnectionClosedPreviouslyOpened); - if ((reconnectTask != null && !reconnectTask.IsCompleted) || null != innerConnectionClosed) + if ((reconnectTask != null && !reconnectTask.IsCompleted) || innerConnectionClosed != null) { return _originalConnectionId; } @@ -1123,7 +1123,7 @@ public string WorkstationId // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; - string result = ((null != constr) ? constr.WorkstationId : null); + string result = constr != null ? constr.WorkstationId : null; if (result == null) { // getting machine name requires Environment.Permission @@ -1534,7 +1534,7 @@ static public void ClearPool(SqlConnection connection) ADP.CheckArgumentNull(connection, "connection"); DbConnectionOptions connectionOptions = connection.UserConnectionOptions; - if (null != connectionOptions) + if (connectionOptions != null) { connectionOptions.DemandPermission(); if (connection.IsContextConnection) @@ -1609,7 +1609,7 @@ override public void Close() CloseInnerConnection(); GC.SuppressFinalize(this); - if (null != Statistics) + if (Statistics != null) { _statistics._closeTimestamp = ADP.TimerCurrent(); } @@ -2542,12 +2542,12 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent) internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) { - Debug.Assert(null != imevent, "null SqlInfoMessageEventArgs"); - var imeventValue = (null != imevent) ? imevent.Message : ""; + Debug.Assert(imevent != null, "null SqlInfoMessageEventArgs"); + var imeventValue = imevent != null ? imevent.Message : ""; SqlClientEventSource.Log.TryTraceEvent(" {0}, Message='{1}'", ObjectID, imeventValue); SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage]; - if (null != handler) + if (handler != null) { notified = true; try @@ -2628,8 +2628,10 @@ private void CheckSQLDebugOnConnect() // if SQLDebug has never been called, it is a noop. internal void CheckSQLDebug() { - if (null != _sdc) + if (_sdc != null) + { CheckSQLDebug(_sdc); + } } // SxS: using GetCurrentThreadId @@ -2639,7 +2641,7 @@ internal void CheckSQLDebug() private void CheckSQLDebug(SqlDebugContext sdc) { // check to see if debugging has been activated - Debug.Assert(null != sdc, "SQL Debug: invalid null debugging context!"); + Debug.Assert(sdc != null, "SQL Debug: invalid null debugging context!"); #pragma warning disable 618 uint tid = (uint)AppDomain.GetCurrentThreadId(); // Sql Debugging doesn't need fiber support; @@ -2747,7 +2749,7 @@ private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, s if (option == TdsEnums.SQLDEBUG_ON) { // debug data - p = new SqlParameter(null, SqlDbType.VarBinary, (null != data) ? data.Length : 0); + p = new SqlParameter(null, SqlDbType.VarBinary, data != null ? data.Length : 0); p.Value = data; c.Parameters.Add(p); } @@ -2951,7 +2953,7 @@ public void ResetStatistics() throw SQL.NotAvailableOnContextConnection(); } - if (null != Statistics) + if (Statistics != null) { Statistics.Reset(); if (ConnectionState.Open == State) @@ -2970,7 +2972,7 @@ public IDictionary RetrieveStatistics() throw SQL.NotAvailableOnContextConnection(); } - if (null != Statistics) + if (Statistics != null) { UpdateStatistics(); return Statistics.GetDictionary(); @@ -3294,8 +3296,10 @@ bool ISQLDebug.SQLDebug(int dwpidDebugger, int dwpidDebuggee, [MarshalAs(Unmanag byte[] rgbMachineName = cp.GetBytes(pszMachineName); byte[] rgbSDIDLLName = cp.GetBytes(pszSDIDLLName); - if (null != rgbData && cbData > TdsEnums.SDCI_MAX_DATA) + if (rgbData != null && cbData > TdsEnums.SDCI_MAX_DATA) + { return false; + } string mapFileName; @@ -3360,7 +3364,7 @@ bool ISQLDebug.SQLDebug(int dwpidDebugger, int dwpidDebuggee, [MarshalAs(Unmanag offset += TdsEnums.SDCI_MAX_DLLNAME; Marshal.WriteInt32(pMemMap, offset, (int)cbData); offset += 4; - if (null != rgbData) + if (rgbData != null) { Marshal.Copy(rgbData, 0, ADP.IntPtrOffset(pMemMap, offset), (int)cbData); } 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 f0c8f403b2..7951a1a8ac 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 @@ -92,7 +92,7 @@ override protected DbConnectionInternal CreateConnection(DbConnectionOptions opt redirectedUserInstance = true; string instanceName; - if (pool == null || (null != pool && pool.Count <= 0)) + if (pool == null || (pool != null && pool.Count <= 0)) { // Non-pooled or pooled and no connections in the pool. SqlInternalConnectionTds sseConnection = null; @@ -113,7 +113,7 @@ override protected DbConnectionInternal CreateConnection(DbConnectionOptions opt throw SQL.NonLocalSSEInstance(); } - if (null != pool) + if (pool != null) { // Pooled connection - cache result SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo; // No lock since we are already in creation mutex @@ -122,7 +122,7 @@ override protected DbConnectionInternal CreateConnection(DbConnectionOptions opt } finally { - if (null != sseConnection) + if (sseConnection != null) { sseConnection.Dispose(); } @@ -248,7 +248,7 @@ private SqlInternalConnectionSmi GetContextConnection(SqlConnectionString option // context connections are automatically re-useable if they exist unless they've been doomed. if (result == null || result.IsConnectionDoomed) { - if (null != result) + if (result != null) { result.Dispose(); // A doomed connection is a messy thing. Dispose of it promptly in nearest receptacle. } @@ -265,7 +265,7 @@ private SqlInternalConnectionSmi GetContextConnection(SqlConnectionString option override internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection) { SqlConnection c = (connection as SqlConnection); - if (null != c) + if (c != null) { return c.PoolGroup; } @@ -275,7 +275,7 @@ override internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection conn override internal DbConnectionInternal GetInnerConnection(DbConnection connection) { SqlConnection c = (connection as SqlConnection); - if (null != c) + if (c != null) { return c.InnerConnection; } @@ -285,7 +285,7 @@ override internal DbConnectionInternal GetInnerConnection(DbConnection connectio override protected int GetObjectId(DbConnection connection) { SqlConnection c = (connection as SqlConnection); - if (null != c) + if (c != null) { return c.ObjectID; } @@ -295,7 +295,7 @@ override protected int GetObjectId(DbConnection connection) override internal void PermissionDemand(DbConnection outerConnection) { SqlConnection c = (outerConnection as SqlConnection); - if (null != c) + if (c != null) { c.PermissionDemand(); } @@ -304,7 +304,7 @@ override internal void PermissionDemand(DbConnection outerConnection) override internal void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) { SqlConnection c = (outerConnection as SqlConnection); - if (null != c) + if (c != null) { c.PoolGroup = poolGroup; } @@ -313,7 +313,7 @@ override internal void SetConnectionPoolGroup(DbConnection outerConnection, DbCo override internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) { SqlConnection c = (owningObject as SqlConnection); - if (null != c) + if (c != null) { c.SetInnerConnectionEvent(to); } @@ -322,7 +322,7 @@ override internal void SetInnerConnectionEvent(DbConnection owningObject, DbConn override internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) { SqlConnection c = (owningObject as SqlConnection); - if (null != c) + if (c != null) { return c.SetInnerConnectionFrom(to, from); } @@ -332,7 +332,7 @@ override internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConne override internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) { SqlConnection c = (owningObject as SqlConnection); - if (null != c) + if (c != null) { c.SetInnerConnectionTo(to); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs index 72f4a27b6a..54d31d5301 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs @@ -80,7 +80,7 @@ internal DbConnectionOptions ConnectionOptions get { Microsoft.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup; - return ((null != poolGroup) ? poolGroup.ConnectionOptions : null); + return poolGroup != null ? poolGroup.ConnectionOptions : null; } } @@ -89,7 +89,7 @@ private string ConnectionString_Get() SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions connectionOptions = UserConnectionOptions; - return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); + return connectionOptions != null ? connectionOptions.UsersConnectionString(hidePassword) : ""; } private void ConnectionString_Set(string value) @@ -153,7 +153,7 @@ internal Microsoft.Data.ProviderBase.DbConnectionPoolGroup PoolGroup set { // when a poolgroup expires and the connection eventually activates, the pool entry will be replaced - Debug.Assert(null != value, "null poolGroup"); + Debug.Assert(value != null, "null poolGroup"); _poolGroup = value; } } @@ -243,7 +243,7 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection enlisting in a transaction.", ObjectID); Transaction indigoTransaction = null; - if (null != transaction) + if (transaction != null) { indigoTransaction = TransactionInterop.GetTransactionFromDtcTransaction((IDtcTransaction)transaction); } @@ -342,14 +342,14 @@ internal void PermissionDemand() Debug.Assert(DbConnectionClosedConnecting.SingletonInstance == _innerConnection, "not connecting"); Microsoft.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup; - DbConnectionOptions connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null); + DbConnectionOptions connectionOptions = poolGroup != null ? poolGroup.ConnectionOptions : null; if (connectionOptions == null || connectionOptions.IsEmpty) { throw ADP.NoConnectionString(); } DbConnectionOptions userConnectionOptions = UserConnectionOptions; - Debug.Assert(null != userConnectionOptions, "null UserConnectionOptions"); + Debug.Assert(userConnectionOptions != null, "null UserConnectionOptions"); userConnectionOptions.DemandPermission(); } @@ -364,8 +364,8 @@ internal void RemoveWeakReference(object value) internal void SetInnerConnectionEvent(DbConnectionInternal to) { // Set's the internal connection without verifying that it's a specific value - Debug.Assert(null != _innerConnection, "null InnerConnection"); - Debug.Assert(null != to, "to null InnerConnection"); + Debug.Assert(_innerConnection != null, "null InnerConnection"); + Debug.Assert(to != null, "to null InnerConnection"); ConnectionState originalState = _innerConnection.State & ConnectionState.Open; ConnectionState currentState = to.State & ConnectionState.Open; @@ -406,9 +406,9 @@ internal void SetInnerConnectionEvent(DbConnectionInternal to) internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionInternal from) { // Set's the internal connection, verifying that it's a specific value before doing so. - Debug.Assert(null != _innerConnection, "null InnerConnection"); - Debug.Assert(null != from, "from null InnerConnection"); - Debug.Assert(null != to, "to null InnerConnection"); + Debug.Assert(_innerConnection != null, "null InnerConnection"); + Debug.Assert(from != null, "from null InnerConnection"); + Debug.Assert(to != null, "to null InnerConnection"); bool result = (from == Interlocked.CompareExchange(ref _innerConnection, to, from)); return result; @@ -419,8 +419,8 @@ internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionIntern internal void SetInnerConnectionTo(DbConnectionInternal to) { // Set's the internal connection without verifying that it's a specific value - Debug.Assert(null != _innerConnection, "null InnerConnection"); - Debug.Assert(null != to, "to null InnerConnection"); + Debug.Assert(_innerConnection != null, "null InnerConnection"); + Debug.Assert(to != null, "to null InnerConnection"); _innerConnection = to; } 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 2c5a144bd7..617e1a3b57 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 @@ -293,7 +293,7 @@ internal _SqlMetaDataSet MetaData catch (System.OutOfMemoryException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -302,7 +302,7 @@ internal _SqlMetaDataSet MetaData catch (System.StackOverflowException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -311,7 +311,7 @@ internal _SqlMetaDataSet MetaData catch (System.Threading.ThreadAbortException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -327,7 +327,7 @@ internal virtual SmiExtendedMetaData[] GetInternalSmiMetaData() SmiExtendedMetaData[] metaDataReturn = null; _SqlMetaDataSet metaData = this.MetaData; - if (null != metaData && 0 < metaData.Length) + if (metaData != null && 0 < metaData.Length) { metaDataReturn = new SmiExtendedMetaData[metaData.VisibleColumnCount]; int returnIndex = 0; @@ -374,8 +374,8 @@ internal virtual SmiExtendedMetaData[] GetInternalSmiMetaData() length, colMetaData.precision, colMetaData.scale, - (null != collation) ? collation.LCID : _defaultLCID, - (null != collation) ? collation.SqlCompareOptions : SqlCompareOptions.None, + collation != null ? collation.LCID : _defaultLCID, + collation != null ? collation.SqlCompareOptions : SqlCompareOptions.None, colMetaData.udt?.Type, false, // isMultiValued null, // fieldmetadata @@ -410,8 +410,10 @@ override public int RecordsAffected { get { - if (null != _command) + if (_command != null) + { return _command.InternalRecordsAffected; + } // cached locally for after Close() when command is nulled out return _recordsAffected; @@ -484,7 +486,7 @@ override public object this[string name] internal void Bind(TdsParserStateObject stateObj) { - Debug.Assert(null != stateObj, "null stateobject"); + Debug.Assert(stateObj != null, "null stateobject"); Debug.Assert(_snapshot == null, "Should not change during execution of asynchronous command"); stateObj.Owner = this; @@ -499,7 +501,7 @@ internal void Bind(TdsParserStateObject stateObj) internal DataTable BuildSchemaTable() { _SqlMetaDataSet md = this.MetaData; - Debug.Assert(null != md, "BuildSchemaTable - unexpected null metadata information"); + Debug.Assert(md != null, "BuildSchemaTable - unexpected null metadata information"); DataTable schemaTable = new DataTable("SchemaTable"); schemaTable.Locale = CultureInfo.InvariantCulture; @@ -799,7 +801,7 @@ internal DataTable BuildSchemaTable() internal void Cancel(int objectID) { TdsParserStateObject stateObj = _stateObj; - if (null != stateObj) + if (stateObj != null) { stateObj.Cancel(objectID); } @@ -1139,7 +1141,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) { _isClosed = true; aborting = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -1149,7 +1151,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) { _isClosed = true; aborting = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -1159,7 +1161,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) { _isClosed = true; aborting = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -1218,7 +1220,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) { #endif //DEBUG // IsClosed may be true if CloseReaderFromConnection was called - in which case, the session has already been closed - if ((!wasClosed) && (null != stateObj)) + if (!wasClosed && stateObj != null) { if (!cleanDataFailed) { @@ -1246,7 +1248,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) } catch (System.OutOfMemoryException e) { - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -1254,7 +1256,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) } catch (System.StackOverflowException e) { - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -1262,7 +1264,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) } catch (System.Threading.ThreadAbortException e) { - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -1436,7 +1438,7 @@ private string GetDataTypeNameInternal(_SqlMetaData metaData) virtual internal SqlBuffer.StorageType GetVariantInternalStorageType(int i) { - Debug.Assert(null != _data, "Attempting to get variant internal storage type"); + Debug.Assert(_data != null, "Attempting to get variant internal storage type"); Debug.Assert(i < _data.Length, "Reading beyond data length?"); return _data[i].VariantInternalStorageType; @@ -1556,7 +1558,7 @@ override public string GetName(int i) { CheckMetaDataIsReady(columnIndex: i); - Debug.Assert(null != _metaData[i].column, "MDAC 66681"); + Debug.Assert(_metaData[i].column != null, "MDAC 66681"); return _metaData[i].column; } @@ -1676,10 +1678,10 @@ override public DataTable GetSchemaTable() statistics = SqlStatistics.StartTimer(Statistics); if (_metaData == null || _metaData._schemaTable == null) { - if (null != this.MetaData) + if (this.MetaData != null) { _metaData._schemaTable = BuildSchemaTable(); - Debug.Assert(null != _metaData._schemaTable, "No schema information yet!"); + Debug.Assert(_metaData._schemaTable != null, "No schema information yet!"); } } return _metaData?._schemaTable; @@ -2074,7 +2076,7 @@ private TdsOperationStatus TryGetBytesInternal(int i, long dataIndex, byte[] buf catch (System.OutOfMemoryException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -2083,7 +2085,7 @@ private TdsOperationStatus TryGetBytesInternal(int i, long dataIndex, byte[] buf catch (System.StackOverflowException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -2092,7 +2094,7 @@ private TdsOperationStatus TryGetBytesInternal(int i, long dataIndex, byte[] buf catch (System.Threading.ThreadAbortException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -2211,7 +2213,7 @@ internal TdsOperationStatus TryGetBytesInternalSequential(int i, byte[] buffer, catch (System.OutOfMemoryException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -2220,7 +2222,7 @@ internal TdsOperationStatus TryGetBytesInternalSequential(int i, byte[] buffer, catch (System.StackOverflowException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -2229,7 +2231,7 @@ internal TdsOperationStatus TryGetBytesInternalSequential(int i, byte[] buffer, catch (System.Threading.ThreadAbortException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -2608,7 +2610,7 @@ private long GetCharsFromPlpData(int i, long dataIndex, char[] buffer, int buffe catch (System.OutOfMemoryException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -2617,7 +2619,7 @@ private long GetCharsFromPlpData(int i, long dataIndex, char[] buffer, int buffe catch (System.StackOverflowException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -2626,7 +2628,7 @@ private long GetCharsFromPlpData(int i, long dataIndex, char[] buffer, int buffe catch (System.Threading.ThreadAbortException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -3485,7 +3487,7 @@ private MetaType GetVersionedMetaType(MetaType actualMetaType) private TdsOperationStatus TryHasMoreResults(out bool moreResults) { - if (null != _parser) + if (_parser != null) { bool moreRows; TdsOperationStatus result = TryHasMoreRows(out moreRows); @@ -3501,7 +3503,7 @@ private TdsOperationStatus TryHasMoreResults(out bool moreResults) return TdsOperationStatus.Done; } - Debug.Assert(null != _command, "unexpected null command from the data reader!"); + Debug.Assert(_command != null, "unexpected null command from the data reader!"); while (_stateObj.HasPendingData) { @@ -3576,7 +3578,7 @@ private TdsOperationStatus TryHasMoreResults(out bool moreResults) private TdsOperationStatus TryHasMoreRows(out bool moreRows) { - if (null != _parser) + if (_parser != null) { if (_sharedState._dataReady) { @@ -3789,7 +3791,7 @@ private TdsOperationStatus TryNextResult(out bool more) return TdsOperationStatus.Done; } - if (null != _parser) + if (_parser != null) { // if there are more rows, then skip them, the user wants the next result bool moreRows = true; @@ -3806,7 +3808,7 @@ private TdsOperationStatus TryNextResult(out bool more) } // we may be done, so continue only if we have not detached ourselves from the parser - if (null != _parser) + if (_parser != null) { bool moreResults; result = TryHasMoreResults(out moreResults); @@ -3902,7 +3904,7 @@ private TdsOperationStatus TryNextResult(out bool more) catch (System.OutOfMemoryException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -3911,7 +3913,7 @@ private TdsOperationStatus TryNextResult(out bool more) catch (System.StackOverflowException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -3920,7 +3922,7 @@ private TdsOperationStatus TryNextResult(out bool more) catch (System.Threading.ThreadAbortException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -3977,7 +3979,7 @@ private TdsOperationStatus TryReadInternal(bool setTimeout, out bool more) #endif //DEBUG statistics = SqlStatistics.StartTimer(Statistics); - if (null != _parser) + if (_parser != null) { if (setTimeout) { @@ -4221,7 +4223,7 @@ private TdsOperationStatus TryReadColumn(int i, bool setTimeout, bool allowParti return result; } - Debug.Assert(null != _data[i], " data buffer is null?"); + Debug.Assert(_data[i] != null, " data buffer is null?"); } #if DEBUG finally @@ -4233,7 +4235,7 @@ private TdsOperationStatus TryReadColumn(int i, bool setTimeout, bool allowParti catch (System.OutOfMemoryException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -4242,7 +4244,7 @@ private TdsOperationStatus TryReadColumn(int i, bool setTimeout, bool allowParti catch (System.StackOverflowException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -4251,7 +4253,7 @@ private TdsOperationStatus TryReadColumn(int i, bool setTimeout, bool allowParti catch (System.Threading.ThreadAbortException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -4322,7 +4324,7 @@ private TdsOperationStatus TryReadColumnHeader(int i) catch (System.OutOfMemoryException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -4331,7 +4333,7 @@ private TdsOperationStatus TryReadColumnHeader(int i) catch (System.StackOverflowException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -4340,7 +4342,7 @@ private TdsOperationStatus TryReadColumnHeader(int i) catch (System.Threading.ThreadAbortException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -4648,7 +4650,7 @@ private bool WillHaveEnoughData(int targetColumn, bool headerOnly = false) // clean remainder bytes for the column off the wire private TdsOperationStatus TryResetBlobState() { - Debug.Assert(null != _stateObj, "null state object"); // _parser may be null at this point + Debug.Assert(_stateObj != null, "null state object"); // _parser may be null at this point AssertReaderState(requireData: true, permitAsync: true); Debug.Assert(_sharedState._nextColumnHeaderToRead <= _metaData.Length, "_sharedState._nextColumnHeaderToRead too large"); TdsOperationStatus result; @@ -4715,7 +4717,7 @@ private void CloseActiveSequentialStreamAndTextReader() private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateObj) { // turn off any set options - if (null != parser && null != _resetOptionsString) + if (parser != null && _resetOptionsString != null) { // It is possible for this to be called during connection close on a // broken connection, so check state first. @@ -4744,7 +4746,7 @@ internal TdsOperationStatus TrySetAltMetaDataSet(_SqlMetaDataSet metaDataSet, bo } _altMetaDataSetCollection.SetAltMetaData(metaDataSet); _metaDataConsumed = metaDataConsumed; - if (_metaDataConsumed && null != _parser) + if (_metaDataConsumed && _parser != null) { byte b; TdsOperationStatus result = _stateObj.TryPeekByte(out b); @@ -4827,7 +4829,7 @@ internal TdsOperationStatus TrySetMetaData(_SqlMetaDataSet metaData, bool moreIn _fieldNameLookup = null; - if (null != metaData) + if (metaData != null) { // we are done consuming metadata only if there is no moreInfo if (!moreInfo) @@ -4912,7 +4914,7 @@ private void SetTimeout(long timeoutMilliseconds) // WebData 111653,112003 -- we now set timeouts per operation, not // per command (it's not supposed to be a cumulative per command). TdsParserStateObject stateObj = _stateObj; - if (null != stateObj) + if (stateObj != null) { stateObj.SetTimeoutMilliseconds(timeoutMilliseconds); } 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 f58a8c19bd..e72c240f23 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 @@ -168,7 +168,7 @@ public override Task GetFieldValueAsync(int ordinal, CancellationToken can override internal SqlBuffer.StorageType GetVariantInternalStorageType(int ordinal) { - Debug.Assert(null != _currentColumnValuesV3, "Attempting to get variant internal storage type without calling GetValue first"); + Debug.Assert(_currentColumnValuesV3 != null, "Attempting to get variant internal storage type without calling GetValue first"); if (IsDBNull(ordinal)) { return SqlBuffer.StorageType.Empty; 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 3503b38632..1782538ae3 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 @@ -41,7 +41,7 @@ internal int ObjectID internal SqlDelegatedTransaction(SqlInternalConnection connection, Transaction tx) { - Debug.Assert(null != connection, "null connection?"); + Debug.Assert(connection != null, "null connection?"); _connection = connection; _atomicTransaction = tx; _active = false; @@ -165,7 +165,7 @@ public Byte[] Promote() Exception promoteException; byte[] returnValue = null; - if (null != connection) + if (connection != null) { SqlConnection usersConnection = connection.Connection; SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, promoting transaction.", ObjectID, connection.ObjectID); @@ -288,10 +288,10 @@ public Byte[] Promote() // Called by transaction to initiate abort sequence public void Rollback(SinglePhaseEnlistment enlistment) { - Debug.Assert(null != enlistment, "null enlistment?"); + Debug.Assert(enlistment != null, "null enlistment?"); SqlInternalConnection connection = GetValidConnection(); - if (null != connection) + if (connection != null) { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); @@ -383,10 +383,10 @@ public void Rollback(SinglePhaseEnlistment enlistment) // Called by the transaction to initiate commit sequence public void SinglePhaseCommit(SinglePhaseEnlistment enlistment) { - Debug.Assert(null != enlistment, "null enlistment?"); + Debug.Assert(enlistment != null, "null enlistment?"); SqlInternalConnection connection = GetValidConnection(); - if (null != connection) + if (connection != null) { SqlConnection usersConnection = connection.Connection; SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, committing transaction.", ObjectID, connection.ObjectID); @@ -565,11 +565,11 @@ private void ValidateActiveOnConnection(SqlInternalConnection connection) { // Invalid indicates something BAAAD happened (Commit after TransactionEnded, for instance) // Doom anything remotely involved. - if (null != connection) + if (connection != null) { connection.DoomThisConnection(); } - if (connection != _connection && null != _connection) + if (connection != _connection && _connection != null) { _connection.DoomThisConnection(); } 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 77f83a2546..8a164eba37 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 @@ -42,11 +42,11 @@ override protected void DispatchMessages(bool ignoreNonFatalMessages) // with info messages here. SqlException exception = ProcessMessages(false, ignoreNonFatalMessages); - if (null != exception) + if (exception != null) { // SQLBUVSTS 225982, query for connection once to avoid race condition between GC (that may collect the connection) and the user thread SqlConnection connection = _connection.Connection; - if (null != connection && connection.FireInfoMessageEventOnUserErrors) + if (connection != null && connection.FireInfoMessageEventOnUserErrors) { connection.OnInfoMessage(new SqlInfoMessageEventArgs(exception)); } @@ -59,7 +59,7 @@ override protected void DispatchMessages(bool ignoreNonFatalMessages) internal EventSink(SqlInternalConnectionSmi connection) { - Debug.Assert(null != connection, "null connection?"); + Debug.Assert(connection != null, "null connection?"); _connection = connection; } @@ -110,13 +110,13 @@ internal override void TransactionStarted(long transactionId) internal SqlInternalConnectionSmi(SqlConnectionString connectionOptions, SmiContext smiContext) : base(connectionOptions) { - Debug.Assert(null != smiContext, "null smiContext?"); + Debug.Assert(smiContext != null, "null smiContext?"); _smiContext = smiContext; _smiContext.OutOfScope += new EventHandler(OnOutOfScope); _smiConnection = _smiContext.ContextConnection; - Debug.Assert(null != _smiConnection, "null SmiContext.ContextConnection?"); + Debug.Assert(_smiConnection != null, "null SmiContext.ContextConnection?"); _smiEventSink = new EventSink(this); SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, constructed new SMI internal connection", ObjectID); @@ -269,11 +269,15 @@ internal void AutomaticEnlistment() Transaction currentSystemTransaction = ADP.GetCurrentTransaction(); // NOTE: Must be first to ensure _smiContext.ContextTransaction is set! Transaction contextTransaction = _smiContext.ContextTransaction; // returns the transaction that was handed to SysTx that wraps the ContextTransactionId. long contextTransactionId = _smiContext.ContextTransactionId; - SqlClientEventSource.Log.TryAdvancedTraceEvent(" {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, + contextTransaction != null ? contextTransaction.GetHashCode() : 0, + currentSystemTransaction != null ? currentSystemTransaction.GetHashCode() : 0); if (SqlInternalTransaction.NullTransactionId != contextTransactionId) { - if (null != currentSystemTransaction && contextTransaction != currentSystemTransaction) + if (currentSystemTransaction != null && contextTransaction != currentSystemTransaction) { throw SQL.NestedTransactionScopesNotSupported(); // can't use TransactionScope(RequiresNew) inside a Sql Transaction. } @@ -311,7 +315,7 @@ override protected void InternalDeactivate() base.Enlist(null); } - if (null != _currentTransaction) + if (_currentTransaction != null) { if (_currentTransaction.IsContext) { @@ -361,8 +365,15 @@ override internal void ExecuteTransaction( SqlInternalTransaction internalTransaction, bool isDelegateControlRequest) { - 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); + SqlClientEventSource.Log.TryAdvancedTraceEvent( + " {0}, transactionRequest={1}, " + + "transactionName='{2}', isolationLevel={3}, internalTransaction=#{4} transactionId=0x{5}.", + ObjectID, + transactionRequest, + transactionName, + iso, + internalTransaction != null ? internalTransaction.ObjectID : 0, + internalTransaction != null ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); switch (transactionRequest) { @@ -378,28 +389,28 @@ override internal void ExecuteTransaction( _pendingTransaction = null; } - Debug.Assert(_smiEventSink.HasMessages || null != _currentTransaction, "begin transaction without TransactionStarted event?"); + Debug.Assert(_smiEventSink.HasMessages || _currentTransaction != null, "begin transaction without TransactionStarted event?"); break; case TransactionRequest.Commit: - Debug.Assert(null != _currentTransaction, "commit transaction without TransactionStarted event?"); + Debug.Assert(_currentTransaction != null, "commit transaction without TransactionStarted event?"); _smiConnection.CommitTransaction(_currentTransaction.TransactionId, _smiEventSink); break; case TransactionRequest.Promote: - Debug.Assert(null != _currentTransaction, "promote transaction without TransactionStarted event?"); + Debug.Assert(_currentTransaction != null, "promote transaction without TransactionStarted event?"); PromotedDTCToken = _smiConnection.PromoteTransaction(_currentTransaction.TransactionId, _smiEventSink); break; case TransactionRequest.Rollback: case TransactionRequest.IfRollback: - Debug.Assert(null != _currentTransaction, "rollback/ifrollback transaction without TransactionStarted event?"); + Debug.Assert(_currentTransaction != null, "rollback/ifrollback transaction without TransactionStarted event?"); _smiConnection.RollbackTransaction(_currentTransaction.TransactionId, transactionName, _smiEventSink); break; case TransactionRequest.Save: - Debug.Assert(null != _currentTransaction, "save transaction without TransactionStarted event?"); + Debug.Assert(_currentTransaction != null, "save transaction without TransactionStarted event?"); _smiConnection.CreateTransactionSavePoint(_currentTransaction.TransactionId, transactionName, _smiEventSink); break; @@ -417,7 +428,7 @@ override protected byte[] GetDTCAddress() _smiEventSink.ProcessMessagesAndThrow(); - if (null != whereAbouts) + if (whereAbouts != null) { SqlClientEventSource.Log.TryAdvancedTraceEvent(" whereAbouts = {0}, Length = {1}", whereAbouts, (ushort)whereAbouts.Length); } @@ -435,7 +446,7 @@ internal void GetCurrentTransactionPair(out long transactionId, out Transaction // due to background SqlDelegatedTransaction processing. Lock the connection to prevent that. lock (this) { - transactionId = (null != CurrentTransaction) ? CurrentTransaction.TransactionId : 0; + transactionId = CurrentTransaction != null ? CurrentTransaction.TransactionId : 0; transaction = null; if (0 != transactionId) { @@ -458,7 +469,7 @@ private void OnOutOfScope(object s, EventArgs e) try { - if (null != owningObject && 1 == _isInUse) + if (owningObject != null && 1 == _isInUse) { // SQLBU 369953 // for various reasons, the owning object may no longer be connection to this @@ -478,7 +489,7 @@ private void OnOutOfScope(object s, EventArgs e) override protected void PropagateTransactionCookie(byte[] transactionCookie) { - if (null != transactionCookie) + if (transactionCookie != null) { SqlClientEventSource.Log.TryAdvancedTraceEvent(" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); } @@ -499,7 +510,7 @@ private void TransactionEndedByServer(long transactionId, TransactionState trans // Basically, we have to make the delegated transaction (if there is one) aware of the situation. SqlDelegatedTransaction delegatedTransaction = DelegatedTransaction; - if (null != delegatedTransaction) + if (delegatedTransaction != null) { delegatedTransaction.Transaction.Rollback(); // just to make sure... DelegatedTransaction = null; // He's dead, Jim. @@ -514,7 +525,7 @@ private void TransactionEnded(long transactionId, TransactionState transactionSt // When we get notification of a completed transaction // we null out the current transaction. - if (null != _currentTransaction) + if (_currentTransaction != null) { #if DEBUG // Check null for case where Begin and Rollback obtained in the same message. @@ -539,7 +550,7 @@ private void TransactionStarted(long transactionId, bool isDistributed) _currentTransaction = _pendingTransaction; _pendingTransaction = null; - if (null != _currentTransaction) + if (_currentTransaction != null) { _currentTransaction.TransactionId = transactionId; // this is defined as a ULongLong in the server and in the TDS Spec. } @@ -554,7 +565,7 @@ private void TransactionStarted(long transactionId, bool isDistributed) override internal void ValidateConnectionForExecute(SqlCommand command) { SqlDataReader reader = FindLiveReader(null); - if (null != reader) + if (reader != null) { // if MARS is on, then a datareader associated with the command exists // or if MARS is off, then a datareader exists 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 7b7bc80962..0aaa4a6d93 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 @@ -868,7 +868,7 @@ override public void Dispose() TdsParser parser = Interlocked.Exchange(ref _parser, null); // guard against multiple concurrent dispose calls -- Delegated Transactions might cause this. Debug.Assert(parser != null && _fConnectionOpen || parser == null && !_fConnectionOpen, "Unexpected state on dispose"); - if (null != parser) + if (parser != null) { parser.Disconnect(); } @@ -895,7 +895,7 @@ override internal void ValidateConnectionForExecute(SqlCommand command) SqlDataReader reader = null; if (parser.MARSOn) { - if (null != command) + if (command != null) { // command can't have datareader already associated with it reader = FindLiveReader(command); } @@ -909,7 +909,7 @@ override internal void ValidateConnectionForExecute(SqlCommand command) reader = FindLiveReader(null); } - if (null != reader) + if (reader != null) { // if MARS is on, then a datareader associated with the command exists // or if MARS is off, then a datareader exists @@ -1024,7 +1024,7 @@ override protected void Activate(Transaction transaction) // Regardless of whether we're required to automatically enlist, // when there is not a current transaction, we cannot leave the // connection enlisted in a transaction. - if (null != transaction) + if (transaction != null) { if (ConnectionOptions.Enlist) { @@ -1055,7 +1055,7 @@ override protected void InternalDeactivate() // transaction is completed and we can do it all then. if (!IsNonPoolableTransactionRoot) { - Debug.Assert(null != _parser || IsConnectionDoomed, "Deactivating a disposed connection?"); + Debug.Assert(_parser != null || IsConnectionDoomed, "Deactivating a disposed connection?"); if (_parser != null) { @@ -1140,7 +1140,7 @@ override internal void DisconnectTransaction(SqlInternalTransaction internalTran { TdsParser parser = Parser; - if (null != parser) + if (parser != null) { parser.DisconnectTransaction(internalTransaction); } @@ -1269,7 +1269,7 @@ internal void ExecuteTransactionPre2005( // to be created, and we set that on the parser. if (TransactionRequest.Begin == transactionRequest) { - Debug.Assert(null != internalTransaction, "Begin Transaction request without internal transaction"); + Debug.Assert(internalTransaction != null, "Begin Transaction request without internal transaction"); _parser.CurrentTransaction = internalTransaction; } } @@ -1386,7 +1386,7 @@ internal void ExecuteTransaction2005( // an object that the ExecTMReq will also lock, but since we're on // the same thread, the lock is a no-op. - if (null != internalTransaction && internalTransaction.IsDelegated) + if (internalTransaction != null && internalTransaction.IsDelegated) { if (_parser.MARSOn) { @@ -1436,7 +1436,7 @@ override internal void DelegatedTransactionEnded() override protected byte[] GetDTCAddress() { byte[] dtcAddress = _parser.GetDTCAddress(ConnectionOptions.ConnectTimeout, _parser.GetSession(this)); - Debug.Assert(null != dtcAddress, "null dtcAddress?"); + Debug.Assert(dtcAddress != null, "null dtcAddress?"); return dtcAddress; } @@ -1664,7 +1664,7 @@ private void OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectio ServerInfo dataSource = new ServerInfo(connectionOptions); string failoverPartner; - if (null != PoolGroupProviderInfo) + if (PoolGroupProviderInfo != null) { useFailoverPartner = PoolGroupProviderInfo.UseFailoverPartner; failoverPartner = PoolGroupProviderInfo.FailoverPartner; @@ -1715,7 +1715,7 @@ private void OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectio throw SQL.ROR_FailoverNotSupportedConnString(); } - if (null != ServerProvidedFailOverPartner) + if (ServerProvidedFailOverPartner != null) { throw SQL.ROR_FailoverNotSupportedServer(this); } @@ -1866,7 +1866,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt isFirstTransparentAttempt: isFirstTransparentAttempt, disableTnir: disableTnir); - if (connectionOptions.MultiSubnetFailover && null != ServerProvidedFailOverPartner) + if (connectionOptions.MultiSubnetFailover && ServerProvidedFailOverPartner != null) { // connection succeeded: trigger exception if server sends failover partner and MultiSubnetFailover is used. throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: true, internalConnection: this); @@ -1935,7 +1935,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt // We only get here when we failed to connect, but are going to re-try // Switch to failover logic if the server provided a partner - if (null != ServerProvidedFailOverPartner) + if (ServerProvidedFailOverPartner != null) { if (connectionOptions.MultiSubnetFailover) { @@ -1970,7 +1970,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt } _activeDirectoryAuthTimeoutRetryHelper.State = ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn; - if (null != PoolGroupProviderInfo) + if (PoolGroupProviderInfo != null) { // We must wait for CompleteLogin to finish for to have the // env change from the server to know its designated failover @@ -2117,7 +2117,7 @@ TimeoutTimer timeout } // Primary server may give us a different failover partner than the connection string indicates. Update it - if (null != ServerProvidedFailOverPartner && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) + if (ServerProvidedFailOverPartner != null && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) { SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); failoverServerInfo.SetDerivedNames(protocol, ServerProvidedFailOverPartner); @@ -2238,7 +2238,7 @@ TimeoutTimer timeout throw SQL.InvalidPartnerConfiguration(failoverHost, CurrentDatabase); } - if (null != PoolGroupProviderInfo) + if (PoolGroupProviderInfo != null) { // We must wait for CompleteLogin to finish for to have the // env change from the server to know its designated failover @@ -2328,7 +2328,7 @@ private void AttemptOneLogin(ServerInfo serverInfo, string newPassword, SecureSt internal void FailoverPermissionDemand() { - if (null != PoolGroupProviderInfo) + if (PoolGroupProviderInfo != null) { PoolGroupProviderInfo.FailoverPermissionDemand(); } @@ -2443,7 +2443,7 @@ internal void BreakConnection() SqlClientEventSource.Log.TryTraceEvent(" {0}, Breaking connection.", ObjectID); DoomThisConnection(); // Mark connection as unusable, so it will be destroyed - if (null != connection) + if (connection != null) { connection.Close(); } @@ -3323,7 +3323,7 @@ private ServerInfo(SqlConnectionString userOptions, string serverName) { //----------------- // Preconditions - Debug.Assert(null != userOptions); + Debug.Assert(userOptions != null); //----------------- //Method body @@ -3342,7 +3342,7 @@ internal ServerInfo(SqlConnectionString userOptions, RoutingInfo routing, string { //----------------- // Preconditions - Debug.Assert(null != userOptions && null != routing); + Debug.Assert(userOptions != null && routing != null); //----------------- //Method body 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 d855c4ea87..fb0884bb36 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 @@ -349,14 +349,14 @@ internal SqlInternalTransaction CurrentTransaction Debug.Assert(value == _currentTransaction || _currentTransaction == null || value == null - || (null != _currentTransaction && !_currentTransaction.IsLocal), "attempting to change current transaction?"); + || (_currentTransaction != null && !_currentTransaction.IsLocal), "attempting to change current transaction?"); // If there is currently a transaction active, we don't want to // change it; this can occur when there is a delegated transaction // and the user attempts to do an API begin transaction; in these // cases, it's safe to ignore the set. - if ((_currentTransaction == null && null != value) || - (null != _currentTransaction && value == null)) + if ((_currentTransaction == null && value != null) || + (_currentTransaction != null && value == null)) { _currentTransaction = value; } @@ -415,7 +415,7 @@ internal SqlInternalTransaction PendingTransaction } set { - Debug.Assert(null != value, "setting a non-null PendingTransaction?"); + Debug.Assert(value != null, "setting a non-null PendingTransaction?"); _pendingTransaction = value; } } @@ -670,7 +670,7 @@ internal void Connect(ServerInfo serverInfo, _server = serverInfo.ResolvedServerName; - if (null != connHandler.PoolGroupProviderInfo) + if (connHandler.PoolGroupProviderInfo != null) { // If we are pooling, check to see if we were processing an // alias which has changed, which means we need to clean out @@ -1623,7 +1623,7 @@ internal void Deactivate(bool connectionIsDoomed) Debug.Assert(connectionIsDoomed || _pendingTransaction == null, "pending transaction at disconnect?"); - if (!connectionIsDoomed && null != _physicalStateObj) + if (!connectionIsDoomed && _physicalStateObj != null) { if (_physicalStateObj.HasPendingData) { @@ -1646,7 +1646,7 @@ internal void Deactivate(bool connectionIsDoomed) // transaction manager completes the transaction. SqlInternalTransaction currentTransaction = CurrentTransaction; - if (null != currentTransaction && currentTransaction.HasParentTransaction) + if (currentTransaction != null && currentTransaction.HasParentTransaction) { currentTransaction.CloseFromConnection(); Debug.Assert(CurrentTransaction == null, "rollback didn't clear current transaction?"); @@ -1658,7 +1658,7 @@ internal void Deactivate(bool connectionIsDoomed) // Used to close the connection and then free the memory allocated for the netlib connection. internal void Disconnect() { - if (null != _sessionPool) + if (_sessionPool != null) { // MARSOn may be true, but _sessionPool not yet created _sessionPool.Dispose(); @@ -1690,7 +1690,7 @@ internal void Disconnect() } // Not allocated until MARS is actually enabled in SNI. - if (null != _pMarsPhysicalConObj) + if (_pMarsPhysicalConObj != null) { _pMarsPhysicalConObj.Dispose(); } @@ -1746,7 +1746,7 @@ internal void RollbackOrphanedAPITransactions() // Any active, non-distributed transaction must be rolled back. SqlInternalTransaction currentTransaction = CurrentTransaction; - if (null != currentTransaction && currentTransaction.HasParentTransaction && currentTransaction.IsOrphaned) + if (currentTransaction != null && currentTransaction.HasParentTransaction && currentTransaction.IsOrphaned) { currentTransaction.CloseFromConnection(); Debug.Assert(CurrentTransaction == null, "rollback didn't clear current transaction?"); @@ -2583,7 +2583,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle // halt processing and that was a bug preventing the user from // processing subsequent results. - if (null != dataStream) + if (dataStream != null) { // Webdata 104560 if (!dataStream.IsInitialized) { @@ -2611,7 +2611,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle case TdsEnums.SQLCOLINFO: { - if (null != dataStream) + if (dataStream != null) { _SqlMetaDataSet metaDataSet; result = TryProcessColInfo(dataStream.MetaData, dataStream, stateObj, out metaDataSet); @@ -2706,7 +2706,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle _currentTransaction = _pendingTransaction; _pendingTransaction = null; - if (null != _currentTransaction) + if (_currentTransaction != null) { _currentTransaction.TransactionId = env._newLongValue; // this is defined as a ULongLong in the server and in the TDS Spec. } @@ -2715,7 +2715,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle TransactionType transactionType = (TdsEnums.ENV_BEGINTRAN == env._type) ? TransactionType.LocalFromTSQL : TransactionType.Distributed; _currentTransaction = new SqlInternalTransaction(_connHandler, transactionType, null, env._newLongValue); } - if (null != _statistics && !_statisticsIsInTransaction) + if (_statistics != null && !_statisticsIsInTransaction) { _statistics.SafeIncrement(ref _statistics._transactions); } @@ -2733,7 +2733,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle case TdsEnums.ENV_ROLLBACKTRAN: // When we get notification of a completed transaction // we null out the current transaction. - if (null != _currentTransaction) + if (_currentTransaction != null) { #if DEBUG // Check null for case where Begin and Rollback obtained in the same message. @@ -2871,7 +2871,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle { return result; } - if (null != dataStream) + if (dataStream != null) { result = dataStream.TrySetSensitivityClassification(sensitivityClassification); if (result != TdsOperationStatus.Done) @@ -2888,7 +2888,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle } } - if (null != dataStream) + if (dataStream != null) { result = dataStream.TrySetMetaData(stateObj._cleanupMetaData, (TdsEnums.SQLTABNAME == peekedToken || TdsEnums.SQLCOLINFO == peekedToken)); if (result != TdsOperationStatus.Done) @@ -2896,7 +2896,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle return result; } } - else if (null != bulkCopyHandler) + else if (bulkCopyHandler != null) { bulkCopyHandler.SetMetaData(stateObj._cleanupMetaData); } @@ -2924,7 +2924,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle } } - if (null != bulkCopyHandler) + if (bulkCopyHandler != null) { // TODO: Consider improving Bulk Copy performance by avoiding boxing. result = TryProcessRow(stateObj._cleanupMetaData, bulkCopyHandler.CreateRowBuffer(), bulkCopyHandler.CreateIndexMap(), stateObj); @@ -2992,7 +2992,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle } case TdsEnums.SQLTABNAME: { - if (null != dataStream) + if (dataStream != null) { MultiPartTableName[] tableNames; result = TryProcessTableName(tokenLength, stateObj, out tableNames); @@ -3041,7 +3041,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle } stateObj._cleanupAltMetaDataSetArray.SetAltMetaData(cleanupAltMetaDataSet); - if (null != dataStream) + if (dataStream != null) { byte metadataConsumedByte; result = stateObj.TryPeekByte(out metadataConsumedByte); @@ -3123,7 +3123,7 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle if (!stateObj.HasPendingData) { - if (null != CurrentTransaction) + if (CurrentTransaction != null) { CurrentTransaction.Activate(); } @@ -3654,7 +3654,7 @@ private TdsOperationStatus TryProcessDone(SqlCommand cmd, SqlDataReader reader, stateObj.HasReceivedAttention = true; Debug.Assert(stateObj._inBytesUsed == stateObj._inBytesRead && stateObj._inBytesPacket == 0, "DONE_ATTN received with more data left on wire"); } - if ((null != cmd) && (TdsEnums.DONE_COUNT == (status & TdsEnums.DONE_COUNT))) + if (cmd != null && (TdsEnums.DONE_COUNT == (status & TdsEnums.DONE_COUNT))) { if (curCmd != TdsEnums.SELECT) { @@ -3689,7 +3689,7 @@ private TdsOperationStatus TryProcessDone(SqlCommand cmd, SqlDataReader reader, { stateObj.AddError(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, _server, SQLMessage.SevereError(), "", 0, exception: null, batchIndex: cmd?.GetCurrentBatchIndex() ?? -1)); - if (null != reader) + if (reader != null) { // SQL BU DT 269516 if (!reader.IsInitialized) { @@ -3705,7 +3705,7 @@ private TdsOperationStatus TryProcessDone(SqlCommand cmd, SqlDataReader reader, { stateObj.AddError(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.SevereError(), "", 0, exception: null, batchIndex: cmd?.GetCurrentBatchIndex() ?? -1)); - if (null != reader) + if (reader != null) { // SQL BU DT 269516 if (!reader.IsInitialized) { @@ -3747,7 +3747,7 @@ private void ProcessSqlStatistics(ushort curCmd, ushort status, int count) { // SqlStatistics bookkeeping stuff // - if (null != _statistics) + if (_statistics != null) { // any done after row(s) counts as a resultset if (_statistics.WaitForDoneAfterRow) @@ -5243,7 +5243,7 @@ internal int GetCodePage(SqlCollation collation, TdsParserStateObject stateObj) ThrowUnsupportedCollationEncountered(stateObj); } - if (null != ci) + if (ci != null) { codePage = ci.TextInfo.ANSICodePage; } @@ -5367,7 +5367,7 @@ internal void ThrowUnsupportedCollationEncountered(TdsParserStateObject stateObj { stateObj.AddError(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, _server, SQLMessage.CultureIdError(), "", 0)); - if (null != stateObj) + if (stateObj != null) { DrainData(stateObj); @@ -8540,7 +8540,7 @@ struct { private void WriteDecimal(decimal value, TdsParserStateObject stateObj) { stateObj._decimalBits = Decimal.GetBits(value); - Debug.Assert(null != stateObj._decimalBits, "decimalBits should be filled in at TdsExecuteRPC time"); + Debug.Assert(stateObj._decimalBits != null, "decimalBits should be filled in at TdsExecuteRPC time"); /* Returns a binary representation of a Decimal. The return value is an integer @@ -8575,7 +8575,7 @@ struct { private void WriteIdentifier(string s, TdsParserStateObject stateObj) { - if (null != s) + if (s != null) { stateObj.WriteByte(checked((byte)s.Length)); WriteString(s, stateObj); @@ -8588,7 +8588,7 @@ private void WriteIdentifier(string s, TdsParserStateObject stateObj) private void WriteIdentifierWithShortLength(string s, TdsParserStateObject stateObj) { - if (null != s) + if (s != null) { WriteShort(checked((short)s.Length), stateObj); WriteString(s, stateObj); @@ -9639,7 +9639,7 @@ internal byte[] GetDTCAddress(int timeout, TdsParserStateObject stateObj) { Debug.Assert(SniContext.Snix_Read == stateObj.SniContext, $"The SniContext should be Snix_Read but it actually is {stateObj.SniContext}"); - if (null != dtcReader && dtcReader.Read()) + if (dtcReader != null && dtcReader.Read()) { Debug.Assert(dtcReader.GetName(0) == "TM Address", "TdsParser: GetDTCAddress did not return 'TM Address'"); @@ -9759,7 +9759,7 @@ internal SqlDataReader TdsExecuteTransactionManagerRequest( returnReader = true; break; case TdsEnums.TransactionManagerRequestType.Propagate: - if (null != buffer) + if (buffer != null) { WriteShort(buffer.Length, stateObj); stateObj.WriteByteArray(buffer, buffer.Length, 0); @@ -9771,7 +9771,7 @@ internal SqlDataReader TdsExecuteTransactionManagerRequest( break; case TdsEnums.TransactionManagerRequestType.Begin: Debug.Assert(Is2005OrNewer, "Should not be calling TdsExecuteTransactionManagerRequest on pre-2005 clients for BeginTransaction!"); - Debug.Assert(null != transaction, "Should have specified an internalTransaction when doing a BeginTransaction request!"); + Debug.Assert(transaction != null, "Should have specified an internalTransaction when doing a BeginTransaction request!"); // Only assign the passed in transaction if it is not equal to the current transaction. // And, if it is not equal, the current actually should be null. Anything else @@ -10502,7 +10502,7 @@ internal Task TdsExecuteRPC(SqlCommand cmd, IList<_SqlRPC> rpcArray, int timeout udtVal = _connHandler.Connection.GetBytes(value, out format, out maxsize); } - Debug.Assert(null != udtVal, "GetBytes returned null instance. Make sure that it always returns non-null value"); + Debug.Assert(udtVal != null, "GetBytes returned null instance. Make sure that it always returns non-null value"); size = udtVal.Length; //it may be legitimate, but we dont support it yet @@ -11400,7 +11400,7 @@ internal void LoadColumnEncryptionKeys(_SqlMetaDataSet metadataCollection, SqlCo { for (int col = 0; col < metadataCollection.Length; col++) { - if (null != metadataCollection[col]) + if (metadataCollection[col] != null) { _SqlMetaData md = metadataCollection[col]; if (md.isEncrypted) @@ -11652,8 +11652,8 @@ internal void WriteBulkCopyMetaData(_SqlMetaDataSet metadataCollection, int coun /// internal bool ShouldEncryptValuesForBulkCopy() { - if (null != _connHandler && - null != _connHandler.ConnectionOptions && + if (_connHandler != null && + _connHandler.ConnectionOptions != null && SqlConnectionColumnEncryptionSetting.Enabled == _connHandler.ConnectionOptions.ColumnEncryptionSetting) { return true; @@ -11981,15 +11981,10 @@ private void WriteMarsHeaderData(TdsParserStateObject stateObj, SqlInternalTrans // Function to send over additional payload header data for 2005 and beyond only. Debug.Assert(_is2005, "WriteMarsHeaderData called on a non-2005 server"); - // These are not necessary - can have local started in distributed. - // Debug.Assert(!(null != sqlTransaction && null != distributedTransaction), "Error to have local (api started) and distributed transaction at the same time!"); - // Debug.Assert(!(null != _userStartedLocalTransaction && null != distributedTransaction), "Error to have local (started outside of the api) and distributed transaction at the same time!"); - // We may need to update the mars header length if mars header is changed in the future - WriteShort(TdsEnums.HEADERTYPE_MARS, stateObj); - if (null != transaction && SqlInternalTransaction.NullTransactionId != transaction.TransactionId) + if (transaction != null && SqlInternalTransaction.NullTransactionId != transaction.TransactionId) { WriteLong(transaction.TransactionId, stateObj); WriteInt(stateObj.IncrementAndObtainOpenResultCount(transaction), stateObj); @@ -12005,7 +12000,7 @@ private void WriteMarsHeaderData(TdsParserStateObject stateObj, SqlInternalTrans private int GetNotificationHeaderSize(SqlNotificationRequest notificationRequest) { - if (null != notificationRequest) + if (notificationRequest != null) { string callbackId = notificationRequest.UserData; string service = notificationRequest.Options; @@ -12061,16 +12056,16 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio // We may need to update the notification header length if the header is changed in the future - Debug.Assert(null != notificationRequest, "notificaitonRequest is null"); + Debug.Assert(notificationRequest != null, "notificaitonRequest is null"); string callbackId = notificationRequest.UserData; string service = notificationRequest.Options; int timeout = notificationRequest.Timeout; // we did verification in GetNotificationHeaderSize, so just assert here. - Debug.Assert(null != callbackId, "CallbackId is null"); + Debug.Assert(callbackId != null, "CallbackId is null"); Debug.Assert(UInt16.MaxValue >= callbackId.Length, "CallbackId length is out of range"); - Debug.Assert(null != service, "Service is null"); + Debug.Assert(service != null, "Service is null"); Debug.Assert(UInt16.MaxValue >= service.Length, "Service length is out of range"); Debug.Assert(-1 <= timeout, "Timeout"); @@ -12987,7 +12982,7 @@ private Task WriteValue(object value, MetaType type, byte scale, int actualLengt // chunk writes needed, please use WritePlpBytes/WritePlpChars private Task WriteUnterminatedValue(object value, MetaType type, byte scale, int actualLength, int encodingByteSize, int offset, TdsParserStateObject stateObj, int paramSize, bool isDataFeed) { - Debug.Assert((null != value) && (DBNull.Value != value), "unexpected missing or empty object"); + Debug.Assert(value != null && (DBNull.Value != value), "unexpected missing or empty object"); // parameters are always sent over as BIG or N types switch (type.NullableType) @@ -13258,7 +13253,7 @@ private void WriteEncryptionMetadata(SqlColumnEncryptionInputParameterInfo colum // chunk writes needed, please use WritePlpBytes/WritePlpChars private byte[] SerializeUnencryptedValue(object value, MetaType type, byte scale, int actualLength, int offset, bool isDataFeed, byte normalizationVersion, TdsParserStateObject stateObj) { - Debug.Assert((null != value) && (DBNull.Value != value), "unexpected missing or empty object"); + Debug.Assert(value != null && (DBNull.Value != value), "unexpected missing or empty object"); if (normalizationVersion != 0x01) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserHelperClasses.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserHelperClasses.cs index 8509e51f60..6a834da984 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserHelperClasses.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserHelperClasses.cs @@ -871,7 +871,7 @@ internal SqlCipherMetadata(SqlTceCipherInfoEntry sqlTceCipherInfoEntry, /// internal bool IsAlgorithmInitialized() { - return (null != _sqlClientEncryptionAlgorithm) ? true : false; + return _sqlClientEncryptionAlgorithm != null ? true : false; } } @@ -960,7 +960,7 @@ internal virtual void CopyFrom(SqlMetaDataPriv original) /// internal bool IsAlgorithmInitialized() { - if (null != cipherMD) + if (cipherMD != null) { return cipherMD.IsAlgorithmInitialized(); } @@ -976,7 +976,7 @@ internal byte NormalizationRuleVersion { get { - if (null != cipherMD) + if (cipherMD != null) { return cipherMD.NormalizationRuleVersion; } @@ -1293,7 +1293,7 @@ internal string TableName private void ParseMultipartName() { - if (null != _multipartName) + if (_multipartName != null) { string[] parts = MultipartIdentifier.ParseMultipartIdentifier(_multipartName, "[\"", "]\"", Strings.SQL_TDSParserTableName, false); _serverName = parts[0]; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.netfx.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.netfx.cs index ad8579a6c0..38b525bd80 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.netfx.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.netfx.cs @@ -67,14 +67,14 @@ private static class TdsParserStateObjectFactory internal TdsParserStateObject(TdsParser parser, SNIHandle physicalConnection, bool async) { // Construct a MARS session - Debug.Assert(null != parser, "no parser?"); + Debug.Assert(parser != null, "no parser?"); _parser = parser; _onTimeoutAsync = OnTimeoutAsync; SniContext = SniContext.Snix_GetMarsSession; - Debug.Assert(null != _parser._physicalStateObj, "no physical session?"); - Debug.Assert(null != _parser._physicalStateObj._inBuff, "no in buffer?"); - Debug.Assert(null != _parser._physicalStateObj._outBuff, "no out buffer?"); + Debug.Assert(_parser._physicalStateObj != null, "no physical session?"); + Debug.Assert(_parser._physicalStateObj._inBuff != null, "no in buffer?"); + Debug.Assert(_parser._physicalStateObj._outBuff != null, "no out buffer?"); Debug.Assert(_parser._physicalStateObj._outBuff.Length == _parser._physicalStateObj._inBuff.Length, "Unexpected unequal buffers."); @@ -329,7 +329,7 @@ internal void Dispose() DisposeCounters(); - if (null != sessionHandle || null != packetHandle) + if (sessionHandle != null || packetHandle != null) { // Comment CloseMARSSession // UNDONE - if there are pending reads or writes on logical connections, we need to block @@ -1466,7 +1466,7 @@ private void RemovePacketFromPendingList(IntPtr pointer) private void SniReadStatisticsAndTracing() { SqlStatistics statistics = Parser.Statistics; - if (null != statistics) + if (statistics != null) { if (statistics.WaitForReply) { @@ -1482,7 +1482,7 @@ private void SniReadStatisticsAndTracing() private void SniWriteStatisticsAndTracing() { SqlStatistics statistics = _parser.Statistics; - if (null != statistics) + if (statistics != null) { statistics.SafeIncrement(ref statistics._buffersSent); statistics.SafeAdd(ref statistics._bytesSent, _outBytesUsed); diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/AdapterUtil.cs index dcbb89a248..6245fd15a4 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/AdapterUtil.cs @@ -86,7 +86,7 @@ internal static InvalidUdtException CreateInvalidUdtException(Type udtType, stri static private void TraceException(string trace, Exception e) { - Debug.Assert(null != e, "TraceException: null Exception"); + Debug.Assert(e != null, "TraceException: null Exception"); if (e is not null) { SqlClientEventSource.Log.TryTraceEvent(trace, e); @@ -1227,8 +1227,8 @@ internal static ArgumentException ParameterValueOutOfRange(decimal value) internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner) { - Debug.Assert(null != value, "null value on conversion failure"); - Debug.Assert(null != inner, "null inner on conversion failure"); + Debug.Assert(value != null, "null value on conversion failure"); + Debug.Assert(inner != null, "null inner on conversion failure"); Exception e; string message = StringsHelper.GetString(Strings.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/DbConnectionOptions.Common.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/DbConnectionOptions.Common.cs index 65e425590e..f72eb5ee59 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/DbConnectionOptions.Common.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/DbConnectionOptions.Common.cs @@ -113,7 +113,7 @@ private static class SYNONYM public DbConnectionOptions(string connectionString, Dictionary synonyms) { _parsetable = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - _usersConnectionString = ((null != connectionString) ? connectionString : ""); + _usersConnectionString = connectionString != null ? connectionString : ""; // first pass on parsing, initial syntax check if (0 < _usersConnectionString.Length) @@ -248,13 +248,13 @@ private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Dict if (SqlClientEventSource.Log.IsAdvancedTraceOn()) { Debug.Assert(string.Equals(keyname, keyname?.ToLower(), StringComparison.InvariantCulture), "missing ToLower"); - string realkeyname = ((null != synonyms) ? synonyms[keyname] : keyname); + string realkeyname = synonyms != null ? synonyms[keyname] : keyname; if (!string.Equals(KEY.Password, realkeyname, StringComparison.InvariantCultureIgnoreCase) && !string.Equals(SYNONYM.Pwd, realkeyname, StringComparison.InvariantCultureIgnoreCase)) { // don't trace passwords ever! - if (null != keyvalue) + if (keyvalue != null) { SqlClientEventSource.Log.AdvancedTraceEvent(" KeyName='{0}', KeyValue='{1}'", keyname, keyvalue); } @@ -518,7 +518,7 @@ internal static int GetKeyValuePair(string connectionString, int currentPosition private static bool IsValueValidInternal(string keyvalue) { - if (null != keyvalue) + if (keyvalue != null) { #if DEBUG bool compValue = s_connectionStringValidValueRegex.IsMatch(keyvalue); @@ -531,7 +531,7 @@ private static bool IsValueValidInternal(string keyvalue) private static bool IsKeyNameValid(string keyname) { - if (null != keyname) + if (keyname != null) { #if DEBUG bool compValue = s_connectionStringValidKeyRegex.IsMatch(keyname); @@ -552,7 +552,7 @@ private static Dictionary SplitConnectionString(string connectio Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index"); Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index"); - if (null != connectionString) + if (connectionString != null) { Match match = parser.Match(connectionString); if (!match.Success || (match.Length != connectionString.Length)) @@ -588,8 +588,9 @@ private static Dictionary SplitConnectionString(string connectio } DebugTraceKeyValuePair(keyname, keyvalue, synonyms); string synonym; - string realkeyname = null != synonyms ? - (synonyms.TryGetValue(keyname, out synonym) ? synonym : null) : keyname; + string realkeyname = synonyms != null + ? (synonyms.TryGetValue(keyname, out synonym) ? synonym : null) + : keyname; if (!IsKeyNameValid(realkeyname)) { @@ -621,7 +622,7 @@ private static void ParseComparison(Dictionary parsetable, strin } catch (ArgumentException f) { - if (null != e) + if (e != null) { string msg1 = e.Message; string msg2 = f.Message; @@ -649,7 +650,7 @@ private static void ParseComparison(Dictionary parsetable, strin } e = null; } - if (null != e) + if (e != null) { Debug.Fail("ParseInternal code threw exception vs regex mismatch"); } @@ -658,7 +659,7 @@ private static void ParseComparison(Dictionary parsetable, strin private static NameValuePair ParseInternal(Dictionary parsetable, string connectionString, bool buildChain, Dictionary synonyms, bool firstKey) { - Debug.Assert(null != connectionString, "null connectionstring"); + Debug.Assert(connectionString != null, "null connectionstring"); StringBuilder buffer = new StringBuilder(); NameValuePair localKeychain = null, keychain = null; #if DEBUG @@ -697,7 +698,7 @@ private static NameValuePair ParseInternal(Dictionary parsetable parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first) } - if (null != localKeychain) + if (localKeychain != null) { localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition); } @@ -724,7 +725,7 @@ internal NameValuePair ReplacePasswordPwd(out string constr, bool fakePassword) int copyPosition = 0; NameValuePair head = null, tail = null, next = null; StringBuilder builder = new StringBuilder(_usersConnectionString.Length); - for (NameValuePair current = _keyChain; null != current; current = current.Next) + for (NameValuePair current = _keyChain; current != null; current = current.Next) { if (!string.Equals(KEY.Password, current.Name, StringComparison.InvariantCultureIgnoreCase) && !string.Equals(SYNONYM.Pwd, current.Name, StringComparison.InvariantCultureIgnoreCase)) @@ -751,7 +752,7 @@ internal NameValuePair ReplacePasswordPwd(out string constr, bool fakePassword) if (fakePassword) { - if (null != tail) + if (tail != null) { tail = tail.Next = next; } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/DbConnectionStringCommon.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/DbConnectionStringCommon.cs index 8bad83989f..f2203166a8 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/DbConnectionStringCommon.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/DbConnectionStringCommon.cs @@ -14,20 +14,28 @@ internal static class DbConnectionStringBuilderUtil { internal static bool ConvertToBoolean(object value) { - Debug.Assert(null != value, "ConvertToBoolean(null)"); + Debug.Assert(value != null, "ConvertToBoolean(null)"); if (value is string svalue) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) + { return true; + } else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no")) + { return false; + } else { string tmp = svalue.Trim(); // Remove leading & trailing white space. if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes")) + { return true; + } else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no")) + { return false; + } } return bool.Parse(svalue); } @@ -43,7 +51,7 @@ internal static bool ConvertToBoolean(object value) internal static bool ConvertToIntegratedSecurity(object value) { - Debug.Assert(null != value, "ConvertToIntegratedSecurity(null)"); + Debug.Assert(value != null, "ConvertToIntegratedSecurity(null)"); if (value is string svalue) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) @@ -98,7 +106,7 @@ internal static string ConvertToString(object value) internal static bool TryConvertToPoolBlockingPeriod(string value, out PoolBlockingPeriod result) { Debug.Assert(Enum.GetNames(typeof(PoolBlockingPeriod)).Length == 3, "PoolBlockingPeriod enum has changed, update needed"); - Debug.Assert(null != value, "TryConvertToPoolBlockingPeriod(null,...)"); + Debug.Assert(value != null, "TryConvertToPoolBlockingPeriod(null,...)"); if (StringComparer.OrdinalIgnoreCase.Equals(value, nameof(PoolBlockingPeriod.Auto))) { @@ -152,7 +160,7 @@ internal static string PoolBlockingPeriodToString(PoolBlockingPeriod value) /// PoolBlockingPeriod value in the valid range internal static PoolBlockingPeriod ConvertToPoolBlockingPeriod(string keyword, object value) { - Debug.Assert(null != value, "ConvertToPoolBlockingPeriod(null)"); + Debug.Assert(value != null, "ConvertToPoolBlockingPeriod(null)"); if (value is string sValue) { // We could use Enum.TryParse here, but it accepts value combinations like @@ -222,7 +230,7 @@ internal static PoolBlockingPeriod ConvertToPoolBlockingPeriod(string keyword, o internal static bool TryConvertToApplicationIntent(string value, out ApplicationIntent result) { Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed"); - Debug.Assert(null != value, "TryConvertToApplicationIntent(null,...)"); + Debug.Assert(value != null, "TryConvertToApplicationIntent(null,...)"); if (StringComparer.OrdinalIgnoreCase.Equals(value, nameof(ApplicationIntent.ReadOnly))) { @@ -272,7 +280,7 @@ internal static string ApplicationIntentToString(ApplicationIntent value) /// application intent value in the valid range internal static ApplicationIntent ConvertToApplicationIntent(string keyword, object value) { - Debug.Assert(null != value, "ConvertToApplicationIntent(null)"); + Debug.Assert(value != null, "ConvertToApplicationIntent(null)"); if (value is string sValue) { // We could use Enum.TryParse here, but it accepts value combinations like diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/NameValuePair.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/NameValuePair.cs index a9d1cc4e6b..e3db46466a 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/NameValuePair.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/NameValuePair.cs @@ -42,7 +42,7 @@ internal NameValuePair Next get => _next; set { - if ((null != _next) || value == null) + if (_next != null || value == null) { throw ADP.InternalError(ADP.InternalErrorCode.NameValuePairNext); } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/DataException.cs index e8a49ffa33..b509971c07 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/DataException.cs @@ -21,8 +21,8 @@ internal static class ExceptionBuilder private static void TraceException(string trace, Exception e) { - Debug.Assert(null != e, "TraceException: null Exception"); - if (null != e) + Debug.Assert(e != null, "TraceException: null Exception"); + if (e != null) { SqlClientEventSource.Log.TryAdvancedTraceEvent(trace, e.Message); try diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs index cd7b3e691d..687ee095f3 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -51,7 +51,7 @@ sealed internal class DbConnectionPoolGroup internal DbConnectionPoolGroup(DbConnectionOptions connectionOptions, DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolGroupOptions) { - Debug.Assert(null != connectionOptions, "null connection options"); + Debug.Assert(connectionOptions != null, "null connection options"); #if NETFRAMEWORK Debug.Assert(poolGroupOptions == null || ADP.s_isWindowsNT, "should not have pooling options on Win9x"); #endif @@ -81,7 +81,7 @@ internal DbConnectionPoolGroupProviderInfo ProviderInfo set { _providerInfo = value; - if (null != value) + if (value != null) { _providerInfo.PoolGroup = this; } @@ -153,7 +153,7 @@ internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactor // PoolGroupOptions will only be null when we're not supposed to pool // connections. DbConnectionPool pool = null; - if (null != _poolGroupOptions) + if (_poolGroupOptions != null) { #if NETFRAMEWORK Debug.Assert(ADP.s_isWindowsNT, "should not be pooling on Win9x"); @@ -177,7 +177,7 @@ internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactor } } - if (null != currentIdentity) + if (currentIdentity != null) { if (!_poolCollection.TryGetValue(currentIdentity, out pool)) // find the pool { diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbReferenceCollection.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbReferenceCollection.cs index 7897e4a027..3f564a71db 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbReferenceCollection.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbReferenceCollection.cs @@ -226,7 +226,7 @@ public void Notify(int message) protected void RemoveItem(object value) { - Debug.Assert(null != value, "RemoveItem with null"); + Debug.Assert(value != null, "RemoveItem with null"); bool lockObtained = false; try diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Sql/SqlNotificationRequest.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Sql/SqlNotificationRequest.cs index ccbff8fc0f..7b4a19e446 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Sql/SqlNotificationRequest.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Sql/SqlNotificationRequest.cs @@ -35,7 +35,7 @@ public string Options } set { - if ((null != value) && (ushort.MaxValue < value.Length)) + if (value != null && (ushort.MaxValue < value.Length)) { throw ADP.ArgumentOutOfRange(string.Empty, nameof(Options)); } @@ -69,7 +69,7 @@ public string UserData } set { - if ((null != value) && (ushort.MaxValue < value.Length)) + if (value != null && (ushort.MaxValue < value.Length)) { throw ADP.ArgumentOutOfRange(string.Empty, nameof(UserData)); } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationProvider.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationProvider.cs index 6162debf92..276efb441e 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationProvider.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationProvider.cs @@ -244,7 +244,7 @@ public override async Task AcquireTokenAsync(SqlAuthenti object previousPw = s_accountPwCache.Get(pwCacheKey); byte[] currPwHash = GetHash(parameters.Password); - if (null != previousPw && + if (previousPw != null && previousPw is byte[] previousPwBytes && // Only get the cached token if the current password hash matches the previously used password hash AreEqual(currPwHash, previousPwBytes)) @@ -334,7 +334,7 @@ private static async Task TryAcquireTokenSilent(IPublicCli } } - if (null != account) + if (account != null) { // If 'account' is available in 'app', we use the same to acquire token silently. // Read More on API docs: https://docs.microsoft.com/dotnet/api/microsoft.identity.client.clientapplicationbase.acquiretokensilent diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SQLFallbackDNSCache.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SQLFallbackDNSCache.cs index 8f02dc5d1b..4dd3086b45 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SQLFallbackDNSCache.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SQLFallbackDNSCache.cs @@ -26,7 +26,7 @@ private SQLFallbackDNSCache() internal bool AddDNSInfo(SQLDNSInfo item) { - if (null != item) + if (item != null) { if (DNSInfoCache.ContainsKey(item.FQDN)) { @@ -52,7 +52,7 @@ internal bool GetDNSInfo(string FQDN, out SQLDNSInfo result) internal bool IsDuplicate(SQLDNSInfo newItem) { - if (null != newItem) + if (newItem != null) { SQLDNSInfo oldItem; if (GetDNSInfo(newItem.FQDN, out oldItem)) diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/MemoryRecordBuffer.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/MemoryRecordBuffer.cs index d20a29c65e..1daf6b225c 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/MemoryRecordBuffer.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/MemoryRecordBuffer.cs @@ -15,7 +15,7 @@ internal sealed class MemoryRecordBuffer : SmiRecordBuffer internal MemoryRecordBuffer(SmiMetaData[] metaData) { - Debug.Assert(null != metaData, "invalid attempt to instantiate MemoryRecordBuffer with null SmiMetaData[]"); + Debug.Assert(metaData != null, "invalid attempt to instantiate MemoryRecordBuffer with null SmiMetaData[]"); _buffer = new SqlRecordBuffer[metaData.Length]; diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs index a0ce819222..c2451bd764 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/MetadataUtilsSmi.cs @@ -492,7 +492,7 @@ internal static SmiExtendedMetaData SqlMetaDataToSmiExtendedMetaData(SqlMetaData // Split the input name. UdtTypeName is specified as single 3 part name. // NOTE: ParseUdtTypeName throws if format is incorrect string typeName = source.ServerTypeName; - if (null != typeName) + if (typeName != null) { string[] names = SqlParameter.ParseTypeName(typeName, true /* isUdtTypeName */); @@ -572,7 +572,7 @@ internal static SmiExtendedMetaData SmiMetaDataFromDataColumn(DataColumn column, if (column.DataType == typeof(SqlDecimal)) { // Must scan all values in column to determine best-fit precision & scale - Debug.Assert(null != parent); + Debug.Assert(parent != null); scale = 0; byte nonFractionalPrecision = 0; // finds largest non-Fractional portion of precision foreach (DataRow row in parent.Rows) @@ -617,7 +617,7 @@ internal static SmiExtendedMetaData SmiMetaDataFromDataColumn(DataColumn column, else if (dbType == SqlDbType.Decimal) { // Must scan all values in column to determine best-fit precision & scale - Debug.Assert(null != parent); + Debug.Assert(parent != null); scale = 0; byte nonFractionalPrecision = 0; // finds largest non-Fractional portion of precision foreach (DataRow row in parent.Rows) @@ -658,7 +658,7 @@ internal static SmiExtendedMetaData SmiMetaDataFromDataColumn(DataColumn column, // In Net Core, since DataColumn.Locale is not accessible because it is internal and in a separate assembly, // we try to get the Locale from the parent - CultureInfo columnLocale = ((null != parent) ? parent.Locale : CultureInfo.CurrentCulture); + CultureInfo columnLocale = parent != null ? parent.Locale : CultureInfo.CurrentCulture; return new SmiExtendedMetaData( dbType, diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs index ce7c115626..0477b6aea4 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs @@ -23,14 +23,14 @@ internal bool HasMessages { #if NETFRAMEWORK SmiEventSink_Default parent = (SmiEventSink_Default)_parent; - if (null != parent) + if (parent != null) { return parent.HasMessages; } else #endif { - bool result = (null != _errors || null != _warnings); + bool result = _errors != null || _warnings != null; return result; } } @@ -48,7 +48,7 @@ bool ignoreNonFatalMessages // hooks up. #if NETFRAMEWORK SmiEventSink_Default parent = (SmiEventSink_Default)_parent; - if (null != parent) + if (parent != null) { parent.DispatchMessages(ignoreNonFatalMessages); } @@ -60,7 +60,7 @@ bool ignoreNonFatalMessages , ignoreNonFatalMessages #endif ); // ignore warnings, because there's no place to send them... - if (null != errors) + if (errors != null) { throw errors; } @@ -77,7 +77,7 @@ protected SqlException ProcessMessages(bool ignoreWarnings SqlException result = null; SqlErrorCollection temp = null; // temp variable to store that which is being thrown - so that local copies can be deleted - if (null != _errors) + if (_errors != null) { Debug.Assert(0 != _errors.Count, "empty error collection?"); // must be something in the collection #if NETFRAMEWORK @@ -99,7 +99,7 @@ protected SqlException ProcessMessages(bool ignoreWarnings else #endif { - if (null != _warnings) + if (_warnings != null) { // When we throw an exception we place all the warnings that // occurred at the end of the collection - after all the errors. @@ -127,7 +127,7 @@ protected SqlException ProcessMessages(bool ignoreWarnings _warnings = null; } - if (null != temp) + if (temp != null) { result = SqlException.CreateException(temp, ServerVersion); } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.netfx.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.netfx.cs index b87c7d8e8e..9872953b24 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.netfx.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.netfx.cs @@ -52,7 +52,7 @@ internal void ProcessMessagesAndThrow(bool ignoreNonFatalMessages) internal void CleanMessages() { SmiEventSink_Default parent = (SmiEventSink_Default)_parent; - if (null != parent) + if (parent != null) { parent.CleanMessages(); } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiGettersStream.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiGettersStream.cs index e129ed49c6..84378027e9 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiGettersStream.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiGettersStream.cs @@ -17,10 +17,10 @@ internal class SmiGettersStream : Stream internal SmiGettersStream(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, SmiMetaData metaData) { - Debug.Assert(null != sink); - Debug.Assert(null != getters); + Debug.Assert(sink != null); + Debug.Assert(getters != null); Debug.Assert(0 <= ordinal); - Debug.Assert(null != metaData); + Debug.Assert(metaData != null); _sink = sink; _getters = getters; diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiSettersStream.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiSettersStream.cs index f9476ed973..513d36f942 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiSettersStream.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiSettersStream.cs @@ -18,10 +18,10 @@ internal class SmiSettersStream : Stream internal SmiSettersStream(SmiEventSink_Default sink, ITypedSettersV3 setters, int ordinal, SmiMetaData metaData) { - Debug.Assert(null != sink); - Debug.Assert(null != setters); + Debug.Assert(sink != null); + Debug.Assert(setters != null); Debug.Assert(0 <= ordinal); - Debug.Assert(null != metaData); + Debug.Assert(metaData != null); _sink = sink; _setters = setters; diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlMetaData.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlMetaData.cs index beaecfb5d8..ab01204b13 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlMetaData.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlMetaData.cs @@ -952,7 +952,7 @@ int sortOrdinal throw SQL.InvalidSqlDbTypeForConstructor(dbType); } - if (null != database || null != owningSchema) + if (database != null || owningSchema != null) { if (objectName == null) { @@ -1060,7 +1060,7 @@ public string Adjust(string value) if (SqlDbType.Char == SqlDbType || SqlDbType.NChar == SqlDbType) { // Don't pad null values - if (null != value) + if (value != null) { // Pad if necessary if (value.Length < MaxLength) @@ -1352,7 +1352,7 @@ public SqlChars Adjust(SqlChars value) { //DBG.Assert(Max!=MaxLength, "SqlMetaData.Adjust(SqlChars): Fixed-length type with Max length!"); // Don't pad null values - if (null != value && !value.IsNull) + if (value != null && !value.IsNull) { // Pad fixed-length types long oldLength = value.Length; @@ -1410,7 +1410,7 @@ public SqlBytes Adjust(SqlBytes value) { //DBG.Assert(Max!=MaxLength, "SqlMetaData.Adjust(SqlBytes): Fixed-length type with Max length!"); // Don't pad null values - if (null != value && !value.IsNull) + if (value != null && !value.IsNull) { // Pad fixed-length types int oldLength = (int)value.Length; @@ -1943,7 +1943,7 @@ public byte[] Adjust(byte[] value) if (SqlDbType.Binary == SqlDbType || SqlDbType.Timestamp == SqlDbType) { // Don't pad null values - if (null != value) + if (value != null) { // Pad fixed-length types if (value.Length < MaxLength) @@ -2003,7 +2003,7 @@ public char[] Adjust(char[] value) if (SqlDbType.Char == SqlDbType || SqlDbType.NChar == SqlDbType) { // Don't pad null values - if (null != value) + if (value != null) { // Pad fixed-length types long oldLength = value.Length; diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlRecordBuffer.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlRecordBuffer.cs index c349d1d89f..d8e9dc94c6 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlRecordBuffer.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlRecordBuffer.cs @@ -291,7 +291,7 @@ internal string String } set { - Debug.Assert(null != value, ""); + Debug.Assert(value != null, ""); _object = value; _value._int64 = ((string)value).Length; @@ -485,7 +485,7 @@ internal int GetBytes(long fieldOffset, byte[] buffer, int bufferOffset, int len { Debug.Assert(StorageType.ByteArray == _type, "Wrong storage type: " + _type); } - Debug.Assert(null != buffer, "Null buffer"); + Debug.Assert(buffer != null, "Null buffer"); Debug.Assert(ndataIndex + length <= BytesLength, "Invalid fieldOffset or length"); Buffer.BlockCopy((byte[])_object, ndataIndex, buffer, bufferOffset, length); @@ -499,7 +499,7 @@ internal int GetChars(long fieldOffset, char[] buffer, int bufferOffset, int len Debug.Assert(!_isNull, "Null data type"); Debug.Assert(StorageType.CharArray == _type || StorageType.String == _type, "Wrong storage type: " + _type); - Debug.Assert(null != buffer, "Null buffer"); + Debug.Assert(buffer != null, "Null buffer"); Debug.Assert(ndataIndex + length <= CharsLength, "Invalid fieldOffset or length"); if (StorageType.CharArray == _type) diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/ValueUtilsSmi.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/ValueUtilsSmi.cs index 7dd4abd7c1..416424e6bc 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/ValueUtilsSmi.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/ValueUtilsSmi.cs @@ -3804,7 +3804,7 @@ ParameterPeekAheadValue peekAhead int recordNumber = 1; // used only for reporting position when there are errors. // obtain enumerator and handle any peekahead values - if (null != peekAhead && null != peekAhead.FirstRecord) + if (peekAhead != null && peekAhead.FirstRecord != null) { // hook up to enumerator enumerator = peekAhead.Enumerator; diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/ValueUtilsSmi.netfx.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/ValueUtilsSmi.netfx.cs index a8d995296c..7bed34713b 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/ValueUtilsSmi.netfx.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/ValueUtilsSmi.netfx.cs @@ -356,7 +356,7 @@ internal static void FillCompatibleITypedSettersFromRecord(SmiEventSink_Default { for (int i = 0; i < metaData.Length; ++i) { - if (null != useDefaultValues && useDefaultValues[i]) + if (useDefaultValues != null && useDefaultValues[i]) { continue; } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAeadAes256CbcHmac256Algorithm.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAeadAes256CbcHmac256Algorithm.cs index 2ff168a25b..d3a926b0da 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAeadAes256CbcHmac256Algorithm.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAeadAes256CbcHmac256Algorithm.cs @@ -103,7 +103,7 @@ internal SqlAeadAes256CbcHmac256Algorithm(SqlAeadAes256CbcHmac256EncryptionKey e _algorithmVersion = algorithmVersion; _version[0] = algorithmVersion; - Debug.Assert(null != encryptionKey, "Null encryption key detected in AeadAes256CbcHmac256 algorithm"); + Debug.Assert(encryptionKey != null, "Null encryption key detected in AeadAes256CbcHmac256 algorithm"); Debug.Assert(0x01 == algorithmVersion, "Unknown algorithm version passed to AeadAes256CbcHmac256"); // Validate encryption type for this algorithm diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlBuffer.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlBuffer.cs index f28bf6033b..6ed6b68157 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlBuffer.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlBuffer.cs @@ -989,7 +989,7 @@ internal object SqlValue { return SqlXml.Null; } - Debug.Assert(null != _object); + Debug.Assert(_object != null); return (SqlXml)_object; case StorageType.Date: @@ -1211,7 +1211,7 @@ internal static SqlBuffer[] CloneBufferArray(SqlBuffer[] values) internal static void Clear(SqlBuffer[] values) { - if (null != values) + if (values != null) { for (int i = 0; i < values.Length; ++i) { diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEncryptionAlgorithmFactoryList.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEncryptionAlgorithmFactoryList.cs index 78c3c2f698..8266b5ce15 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEncryptionAlgorithmFactoryList.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEncryptionAlgorithmFactoryList.cs @@ -74,7 +74,7 @@ internal void GetAlgorithm(SqlClientSymmetricKey key, byte type, string algorith SqlClientEncryptionAlgorithmFactoryList.GetInstance().GetRegisteredCipherAlgorithmNames()); } - Debug.Assert(null != factory, "Null Algorithm Factory class detected"); + Debug.Assert(factory != null, "Null Algorithm Factory class detected"); // If the factory exists, following method will Create an algorithm object. If this fails, // it will raise an exception. diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index c9a8d24b52..d82bd6f9c1 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -142,7 +142,7 @@ internal void Append(SqlCommand command) // deep clone the parameter value if byte[] or char[] object obj = p.Value; byte[] byteValues = (obj as byte[]); - if (null != byteValues) + if (byteValues != null) { int offset = p.Offset; int size = p.Size; @@ -159,7 +159,7 @@ internal void Append(SqlCommand command) else { char[] charValues = (obj as char[]); - if (null != charValues) + if (charValues != null) { int offset = p.Offset; int size = p.Size; @@ -176,7 +176,7 @@ internal void Append(SqlCommand command) else { ICloneable cloneable = (obj as ICloneable); - if (null != cloneable) + if (cloneable != null) { p.Value = cloneable.Clone(); } @@ -192,7 +192,7 @@ internal void Append(SqlCommand command) internal static void BuildStoredProcedureName(StringBuilder builder, string part) { - if ((null != part) && (0 < part.Length)) + if (part != null && (0 < part.Length)) { if ('[' == part[0]) { @@ -220,13 +220,13 @@ internal void Clear() { SqlClientEventSource.Log.TryTraceEvent("SqlCommandSet.Clear | API | Object Id {0}", ObjectID); DbCommand batchCommand = BatchCommand; - if (null != batchCommand) + if (batchCommand != null) { batchCommand.Parameters.Clear(); batchCommand.CommandText = null; } List commandList = _commandList; - if (null != commandList) + if (commandList != null) { commandList.Clear(); } @@ -239,7 +239,7 @@ internal void Dispose() _commandList = null; _batchCommand = null; - if (null != command) + if (command != null) { command.Dispose(); } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs index 636a1cc6ba..47de649bbd 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs @@ -125,7 +125,7 @@ internal void FailoverPermissionDemand() // Note that we only demand when there is a permission set, which only // happens once we've identified a failover situation in FailoverCheck PermissionSet failoverPermissionSet = _failoverPermissionSet; - if (null != failoverPermissionSet) + if (failoverPermissionSet != null) { // demand on pooled failover connections failoverPermissionSet.Demand(); diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionString.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionString.cs index 53b8ea4437..5518570bb2 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionString.cs @@ -425,7 +425,7 @@ internal SqlConnectionString(string connectionString) : base(connectionString, G } } - if (null != _networkLibrary) + if (_networkLibrary != null) { // MDAC 83525 string networkLibrary = _networkLibrary.Trim().ToLower(CultureInfo.InvariantCulture); Hashtable netlib = NetlibMapping(); @@ -460,7 +460,7 @@ internal SqlConnectionString(string connectionString) : base(connectionString, G ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog); ValidateValueLength(_password, TdsEnums.MAXLEN_CLIENTSECRET, KEY.Password); ValidateValueLength(_userID, TdsEnums.MAXLEN_CLIENTID, KEY.User_ID); - if (null != _workstationId) + if (_workstationId != null) { ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id); } @@ -487,7 +487,7 @@ internal SqlConnectionString(string connectionString) : base(connectionString, G #else _expandedAttachDBFilename = ExpandDataDirectory(KEY.AttachDBFilename, _attachDBFileName); #endif // NETFRAMEWORK - if (null != _expandedAttachDBFilename) + if (_expandedAttachDBFilename != null) { if (0 <= _expandedAttachDBFilename.IndexOf('|')) { @@ -782,13 +782,13 @@ internal bool EnforceLocalHost { // so tdsparser.connect can determine if SqlConnection.UserConnectionOptions // needs to enforce local host after datasource alias lookup - return (null != _expandedAttachDBFilename) && _localDBInstance == null; + return _expandedAttachDBFilename != null && _localDBInstance == null; } } protected internal override string Expand() { - if (null != _expandedAttachDBFilename) + if (_expandedAttachDBFilename != null) { #if NETFRAMEWORK return ExpandKeyword(KEY.AttachDBFilename, _expandedAttachDBFilename); diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index e4825add3b..9e13de3e69 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -166,7 +166,7 @@ protected override void ClearBatch() /// protected override int ExecuteBatch() { - Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); + Debug.Assert(_commandSet != null && (0 < _commandSet.CommandCount), "no commands"); SqlClientEventSource.Log.TryCorrelationTraceEvent("SqlDataAdapter.ExecuteBatch | Info | Correlation | Object Id {0}, Activity Id {1}, Command Count {2}", ObjectID, ActivityCorrelator.Current, _commandSet.CommandCount); return _commandSet.ExecuteNonQuery(); } @@ -205,7 +205,7 @@ protected override void InitializeBatching() } } } - if (null != command) + if (command != null) { _commandSet.Connection = command.Connection; _commandSet.Transaction = command.Transaction; @@ -216,7 +216,7 @@ protected override void InitializeBatching() /// protected override void TerminateBatching() { - if (null != _commandSet) + if (_commandSet != null) { _commandSet.Dispose(); _commandSet = null; @@ -267,10 +267,10 @@ public event SqlRowUpdatingEventHandler RowUpdating // Prevent someone from registering two different command builders on the adapter by // silently removing the old one. - if ((null != handler) && (value.Target is DbCommandBuilder)) + if (handler != null && value.Target is DbCommandBuilder) { SqlRowUpdatingEventHandler d = (SqlRowUpdatingEventHandler)ADP.FindBuilder(handler); - if (null != d) + if (d != null) { Events.RemoveHandler(s_eventRowUpdating, d); } @@ -287,7 +287,7 @@ public event SqlRowUpdatingEventHandler RowUpdating override protected void OnRowUpdated(RowUpdatedEventArgs value) { SqlRowUpdatedEventHandler handler = (SqlRowUpdatedEventHandler)Events[s_eventRowUpdated]; - if ((null != handler) && (value is SqlRowUpdatedEventArgs args)) + if (handler != null && value is SqlRowUpdatedEventArgs args) { handler(this, args); } @@ -298,7 +298,7 @@ override protected void OnRowUpdated(RowUpdatedEventArgs value) override protected void OnRowUpdating(RowUpdatingEventArgs value) { SqlRowUpdatingEventHandler handler = (SqlRowUpdatingEventHandler)Events[s_eventRowUpdating]; - if ((null != handler) && (value is SqlRowUpdatingEventArgs args)) + if (handler != null && value is SqlRowUpdatingEventArgs args) { handler(this, args); } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs index 2dbad8a514..e8d474b3da 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -79,7 +79,7 @@ public override bool Equals(object value) public override int GetHashCode() { int hashValue; - if (null != _identity) + if (_identity != null) { hashValue = _identity.GetHashCode(); } @@ -296,7 +296,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) } _timeout = timeout; - if (null != options) + if (options != null) { // Ignore null value - will force to default. _options = options; } @@ -357,7 +357,7 @@ public event OnChangeEventHandler OnChange long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { - if (null != value) + if (value != null) { SqlNotificationEventArgs sqlNotificationEvent = null; @@ -383,7 +383,7 @@ public event OnChangeEventHandler OnChange } } - if (null != sqlNotificationEvent) + if (sqlNotificationEvent != null) { // Delay firing the event until outside of lock. value(this, sqlNotificationEvent); } @@ -399,7 +399,7 @@ public event OnChangeEventHandler OnChange long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { - if (null != value) + if (value != null) { EventContextPair pair = new(value, this); lock (_eventHandlerLock) @@ -474,15 +474,15 @@ private static void ObtainProcessDispatcher() #endif // DEBUG _AppDomain masterDomain = SNINativeMethodWrapper.GetDefaultAppDomain(); - if (null != masterDomain) + if (masterDomain != null) { ObjectHandle handle = CreateProcessDispatcher(masterDomain); - if (null != handle) + if (handle != null) { SqlDependencyProcessDispatcher dependency = (SqlDependencyProcessDispatcher)handle.Unwrap(); - if (null != dependency) + if (dependency != null) { s_processDispatcher = SqlDependencyProcessDispatcher.SingletonProcessDispatcher; // Set to static instance. @@ -762,7 +762,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault lock (s_startStopLock) { - if (null != s_processDispatcher) + if (s_processDispatcher != null) { // If _processDispatcher null, no Start has been called. try { @@ -1022,7 +1022,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS resultingPair = databaseList[index]; } - if (null != resultingPair) + if (resultingPair != null) { // Exact database match. database = FixupServiceOrDatabaseName(resultingPair.Database); // Fixup in place. string quotedService = FixupServiceOrDatabaseName(resultingPair.Service); @@ -1234,7 +1234,7 @@ private void AddCommandInternal(SqlCommand cmd) }; // Add the command - A dependency should always map to a set of commands which haven't fired. - if (null != _options) + if (_options != null) { // Assign options if user provided. cmd.Notification.Options = _options; } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index 5850dd9178..d62df2b7b1 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -410,7 +410,7 @@ private void CreateQueueAndService(bool restart) try { // Since the failure will result in a rollback, rollback our object. - if (null != trans) + if (trans != null) { trans.Rollback(); trans = null; @@ -472,7 +472,7 @@ private void CreateQueueAndService(bool restart) } finally { - if (null != trans) + if (trans != null) { try { @@ -556,10 +556,10 @@ private void ProcessNotificationResults(SqlDataReader reader) if (string.Equals(msgType, "http://schemas.microsoft.com/SQL/Notifications/QueryNotification", StringComparison.OrdinalIgnoreCase)) { SqlXml payload = reader.GetSqlXml(2); - if (null != payload) + if (payload != null) { SqlNotification notification = SqlNotificationParser.ProcessMessage(payload); - if (null != notification) + if (notification != null) { string key = notification.Key; SqlClientEventSource.Log.TryNotificationTraceEvent(" Key: '{0}'", key); @@ -573,7 +573,7 @@ private void ProcessNotificationResults(SqlDataReader reader) { dispatcher = s_staticInstance._sqlDependencyPerAppDomainDispatchers[appDomainKey]; } - if (null != dispatcher) + if (dispatcher != null) { try { @@ -687,7 +687,7 @@ private void Restart(object unused) if (!_stop) { #if NETFRAMEWORK - if (null != _hashHelper.Identity) + if (_hashHelper.Identity != null) { // Only impersonate if Integrated Security. WindowsImpersonationContext context = null; RuntimeHelpers.PrepareConstrainedRegions(); // CER for context.Undo. @@ -838,7 +838,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) // Dictionary used to track how many times start has been called per app domain. // For each decrement, subtract from count, and delete if we reach 0. - if (null != appDomainKey) + if (appDomainKey != null) { // If null, then this was called from SqlDependencyProcessDispatcher, we ignore appDomainKeyHash. lock (_appDomainKeyHash) @@ -1330,12 +1330,12 @@ public override int GetHashCode() { int hashValue = 0; - if (null != _identity) + if (_identity != null) { hashValue = _identity.GetHashCode(); } - if (null != _queue) + if (_queue != null) { hashValue = unchecked(_connectionString.GetHashCode() + _queue.GetHashCode() + hashValue); } @@ -1424,7 +1424,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper( Enlist = false, ConnectRetryCount = 0 }; - if (null != queue) + if (queue != null) { // User provided! connectionStringBuilder.ApplicationName = queue; // ApplicationName will be set to queue name. } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs index b5135d25c9..66c9e8c44e 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs @@ -243,7 +243,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) { dependencyList = LookupCommandEntryWithRemove(sqlNotification.Key); - if (null != dependencyList) + if (dependencyList != null) { SqlClientEventSource.Log.TryNotificationTraceEvent(" commandHash found in hashtable."); foreach (SqlDependency dependency in dependencyList) @@ -261,7 +261,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } } - if (null != dependencyList) + if (dependencyList != null) { // After removal from hashtables, invalidate. foreach (SqlDependency dependency in dependencyList) @@ -612,7 +612,7 @@ private static void TimeoutTimerCallback(object state) { for (int i = 0; i < dependencies.Length; i++) { - if (null != dependencies[i]) + if (dependencies[i] != null) { SingletonInstance._dependencyIdToDependencyHash.Remove(dependencies[i].Id); } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlEnums.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlEnums.cs index 3fbd9b112a..86b9656684 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlEnums.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlEnums.cs @@ -603,7 +603,7 @@ private static void AssertIsUserDefinedTypeInstance(object sqlValue, string fail internal static object GetSqlValueFromComVariant(object comVal) { object sqlVal = null; - if ((null != comVal) && (DBNull.Value != comVal)) + if (comVal != null && (DBNull.Value != comVal)) { switch (comVal) { diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlException.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlException.cs index 336a788c73..19f1f5a89a 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlException.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlException.cs @@ -205,7 +205,7 @@ internal static SqlException CreateException(SqlErrorCollection errorCollection, internal static SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion, Guid conId, Exception innerException = null, SqlBatchCommand batchCommand = null) { - Debug.Assert(null != errorCollection && errorCollection.Count > 0, "no errorCollection?"); + Debug.Assert(errorCollection != null && errorCollection.Count > 0, "no errorCollection?"); StringBuilder message = new(); for (int i = 0; i < errorCollection.Count; i++) diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlInfoMessageEvent.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlInfoMessageEvent.cs index bca1f3d65f..5392419a05 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlInfoMessageEvent.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlInfoMessageEvent.cs @@ -18,7 +18,7 @@ internal SqlInfoMessageEventArgs(SqlException exception) public SqlErrorCollection Errors => _exception.Errors; // MDAC 65548 - private bool ShouldSerializeErrors() => (null != _exception) && (0 < _exception.Errors.Count); + private bool ShouldSerializeErrors() => _exception != null && (0 < _exception.Errors.Count); /// public string Message => _exception.Message; diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index afc1a8634f..e6fe8eec99 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -62,7 +62,7 @@ internal enum TransactionRequest internal SqlInternalConnection(SqlConnectionString connectionOptions) : base() { - Debug.Assert(null != connectionOptions, "null connectionOptions?"); + Debug.Assert(connectionOptions != null, "null connectionOptions?"); _connectionOptions = connectionOptions; } @@ -117,7 +117,7 @@ override internal bool IsTransactionRoot get { SqlDelegatedTransaction delegatedTransaction = DelegatedTransaction; - return ((null != delegatedTransaction) && (delegatedTransaction.IsActive)); + return delegatedTransaction != null && (delegatedTransaction.IsActive); } } @@ -127,7 +127,7 @@ internal bool HasLocalTransaction get { SqlInternalTransaction currentTransaction = CurrentTransaction; - bool result = (null != currentTransaction && currentTransaction.IsLocal); + bool result = currentTransaction != null && currentTransaction.IsLocal; return result; } } @@ -137,7 +137,7 @@ internal bool HasLocalTransactionFromAPI get { SqlInternalTransaction currentTransaction = CurrentTransaction; - bool result = (null != currentTransaction && currentTransaction.HasParentTransaction); + bool result = currentTransaction != null && currentTransaction.HasParentTransaction; return result; } } @@ -324,7 +324,7 @@ override protected void CleanupTransactionOnCompletion(Transaction transaction) // Note: unlocked, potentially multi-threaded code, so pull delegate to local to // ensure it doesn't change between test and call. SqlDelegatedTransaction delegatedTransaction = DelegatedTransaction; - if (null != delegatedTransaction) + if (delegatedTransaction != null) { delegatedTransaction.TransactionEnded(transaction); } @@ -359,7 +359,7 @@ override protected void Deactivate() bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(Connection); #endif // NETFRAMEWORK SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection; - if (null != referenceCollection) + if (referenceCollection != null) { referenceCollection.Deactivate(); } @@ -466,7 +466,7 @@ protected void Enlist(Transaction tx) private void EnlistNonNull(Transaction tx) { - Debug.Assert(null != tx, "null transaction?"); + Debug.Assert(tx != null, "null transaction?"); SqlClientEventSource.Log.TryAdvancedTraceEvent("SqlInternalConnection.EnlistNonNull | ADV | Object {0}, Transaction Id {1}, attempting to delegate.", ObjectID, tx?.TransactionInformation?.LocalIdentifier); bool hasDelegatedTransaction = false; @@ -612,7 +612,7 @@ private void EnlistNonNull(Transaction tx) // In either case, when we're working with a 2005 or newer server // we better have a current transaction by now. - Debug.Assert(null != CurrentTransaction, "delegated/enlisted transaction with null current transaction?"); + Debug.Assert(CurrentTransaction != null, "delegated/enlisted transaction with null current transaction?"); } internal void EnlistNull() @@ -663,7 +663,7 @@ override public void EnlistTransaction(Transaction transaction) throw ADP.LocalTransactionPresent(); } - if (null != transaction && transaction.Equals(EnlistedTransaction)) + if (transaction != null && transaction.Equals(EnlistedTransaction)) { // No-op if this is the current transaction return; @@ -735,7 +735,7 @@ internal SqlDataReader FindLiveReader(SqlCommand command) { SqlDataReader reader = null; SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection; - if (null != referenceCollection) + if (referenceCollection != null) { reader = referenceCollection.FindLiveReader(command); } @@ -747,7 +747,7 @@ internal SqlDataReader FindLiveReader(SqlCommand command) static private byte[] GetTransactionCookie(Transaction transaction, byte[] whereAbouts) { byte[] transactionCookie = null; - if (null != transaction) + if (transaction != null) { transactionCookie = TransactionInterop.GetExportCookie(transaction, whereAbouts); } @@ -768,7 +768,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action(outerTransaction); } @@ -475,7 +475,7 @@ internal void Zombie() SqlInternalConnection innerConnection = _innerConnection; _innerConnection = null; - if (null != innerConnection) + if (innerConnection != null) { innerConnection.DisconnectTransaction(this); } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlParameter.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlParameter.cs index 97200b4055..034a2ac306 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlParameter.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlParameter.cs @@ -116,7 +116,7 @@ private InstanceDescriptor ConvertToInstanceDescriptor(SqlParameter p) { flags |= 4; } - if (null != p.Value) + if (p.Value != null) { flags |= 8; } @@ -395,7 +395,7 @@ public SqlCompareOptions CompareInfo get { SqlCollation collation = _collation; - if (null != collation) + if (collation != null) { return collation.SqlCompareOptions; } @@ -513,7 +513,7 @@ public int LocaleId get { SqlCollation collation = _collation; - if (null != collation) + if (collation != null) { return collation.LCID; } @@ -950,7 +950,7 @@ internal MetaType InternalMetaType { get { - Debug.Assert(null != _internalMetaType, "null InternalMetaType"); + Debug.Assert(_internalMetaType != null, "null InternalMetaType"); return _internalMetaType; } set => _internalMetaType = value; @@ -1215,7 +1215,7 @@ private void GetActualFieldsAndProperties(out List fields, // set up primary key as unique key list // do this prior to general metadata loop to favor the primary key - if (null != dt.PrimaryKey && 0 < dt.PrimaryKey.Length) + if (dt.PrimaryKey != null && 0 < dt.PrimaryKey.Length) { foreach (DataColumn col in dt.PrimaryKey) { @@ -1489,7 +1489,7 @@ private void GetActualFieldsAndProperties(out List fields, // But assert no holes to be sure. foreach (SmiExtendedMetaData md in fields) { - Debug.Assert(null != md, "Shouldn't be able to have holes, since original loop algorithm prevents such."); + Debug.Assert(md != null, "Shouldn't be able to have holes, since original loop algorithm prevents such."); } #endif @@ -1892,7 +1892,7 @@ private MetaType GetMetaTypeOnly() { return _metaType; } - if (null != _value && DBNull.Value != _value) + if (_value != null && DBNull.Value != _value) { // We have a value set by the user then just use that value // char and char[] are not directly supported so we convert those values to string @@ -2220,7 +2220,7 @@ internal static object CoerceValue(object value, MetaType destinationType, out b { Debug.Assert(!(value is DataFeed), "Value provided should not already be a data feed"); Debug.Assert(!ADP.IsNull(value), "Value provided should not be null"); - Debug.Assert(null != destinationType, "null destinationType"); + Debug.Assert(destinationType != null, "null destinationType"); coercedToDataFeed = false; typeChanged = false; @@ -2422,7 +2422,7 @@ private static int BinarySize(object value, bool isSqlType) // of this and use a simple regex to do the parsing internal static string[] ParseTypeName(string typeName, bool isUdtTypeName) { - Debug.Assert(null != typeName, "null typename passed to ParseTypeName"); + Debug.Assert(typeName != null, "null typename passed to ParseTypeName"); try { diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlStatistics.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlStatistics.cs index 7a5e37198b..1ea104d065 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlStatistics.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlStatistics.cs @@ -14,7 +14,7 @@ internal sealed class SqlStatistics { internal static SqlStatistics StartTimer(SqlStatistics statistics) { - if ((null != statistics) && !statistics.RequestExecutionTimer()) + if (statistics != null && !statistics.RequestExecutionTimer()) { // we're re-entrant -- don't bother. statistics = null; @@ -24,7 +24,7 @@ internal static SqlStatistics StartTimer(SqlStatistics statistics) internal static void StopTimer(SqlStatistics statistics) { - if (null != statistics) + if (statistics != null) { statistics.ReleaseAndUpdateExecutionTimer(); } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlTransaction.Common.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlTransaction.Common.cs index 19996684b9..e96f854e50 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlTransaction.Common.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlTransaction.Common.cs @@ -87,7 +87,7 @@ internal SqlStatistics Statistics { get { - if (null != _connection) + if (_connection != null) { if (_connection.StatisticsEnabled) { @@ -110,7 +110,7 @@ internal void Zombie() // Of course, if the connection is already closed, // then we're free to zombify... SqlInternalConnection internalConnection = (_connection.InnerConnection as SqlInternalConnection); - if (null != internalConnection + if (internalConnection != null #if NETFRAMEWORK && internalConnection.Is2005OrNewer #endif diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlUtil.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlUtil.cs index 154872a8e4..8592fd7407 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlUtil.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlUtil.cs @@ -2228,7 +2228,7 @@ internal static Exception GetExceptionArray(string serverName, string errorMessa { // Create and throw an exception array SqlErrorCollection sqlErs = new SqlErrorCollection(); - Exception exceptionToInclude = (null != e.InnerException) ? e.InnerException : e; + Exception exceptionToInclude = e.InnerException != null ? e.InnerException : e; sqlErs.Add(new SqlError(infoNumber: 0, errorState: (byte)0x00, errorClass: (byte)TdsEnums.MIN_ERROR_CLASS, server: serverName, errorMessage: errorMessage, procedure: null, lineNumber: 0)); if (e is SqlException) diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSafeHandles.Windows.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSafeHandles.Windows.cs index dba1ec788c..04f1a45510 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSafeHandles.Windows.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSafeHandles.Windows.cs @@ -103,7 +103,7 @@ private static void ReadDispatcher(IntPtr key, IntPtr packet, uint error) GCHandle gcHandle = (GCHandle)key; TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target; - if (null != stateObj) + if (stateObj != null) { #if NETFRAMEWORK stateObj.ReadAsyncCallback(IntPtr.Zero, packet, error); @@ -128,7 +128,7 @@ private static void WriteDispatcher(IntPtr key, IntPtr packet, uint error) GCHandle gcHandle = (GCHandle)key; TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target; - if (null != stateObj) + if (stateObj != null) { #if NETFRAMEWORK stateObj.WriteAsyncCallback(IntPtr.Zero, packet, error); diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index cabb027e9e..444d6c79e9 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -73,7 +73,7 @@ internal void Deactivate() { TdsParserStateObject session = _cache[i]; - if (null != session) + if (session != null) { if (session.IsOrphaned) { @@ -164,8 +164,7 @@ internal TdsParserStateObject GetSession(object owner) internal void PutSession(TdsParserStateObject session) { - Debug.Assert(null != session, "null session?"); - //Debug.Assert(null != session.Owner, "session without owner?"); + Debug.Assert(session != null, "null session?"); bool okToReuse = session.Deactivate(); @@ -224,7 +223,7 @@ internal void BestEffortCleanup() for (int i = 0; i < _cache.Count; i++) { TdsParserStateObject session = _cache[i]; - if (null != session) + if (session != null) { SNIHandle sessionHandle = session.Handle; if (sessionHandle != null) diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index 7184604963..b7e830ae80 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -298,7 +298,7 @@ public TimeoutState(int value) internal TdsParserStateObject(TdsParser parser) { // Construct a physical connection - Debug.Assert(null != parser, "no parser?"); + Debug.Assert(parser != null, "no parser?"); _parser = parser; _onTimeoutAsync = OnTimeoutAsync; diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStaticMethods.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStaticMethods.cs index 6ba8be499c..3954ad6ed8 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStaticMethods.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStaticMethods.cs @@ -77,7 +77,7 @@ static internal void AliasRegistryLookup(ref string host, ref string protocol) else { protocol = (string)SqlConnectionString.NetlibMapping()[parsedProtocol]; - if (null != protocol) + if (protocol != null) { host = parsedAliasName; } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsValueSetter.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsValueSetter.cs index a1e019140c..0a5144a6b8 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsValueSetter.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsValueSetter.cs @@ -362,7 +362,7 @@ internal void SetString(string value, int offset, int length) } else if (SqlDbType.Variant == _metaData.SqlDbType) { - Debug.Assert(null != _variantType && SqlDbType.NVarChar == _variantType.SqlDbType, "Invalid variant type"); + Debug.Assert(_variantType != null && SqlDbType.NVarChar == _variantType.SqlDbType, "Invalid variant type"); SqlCollation collation = SqlCollation.FromLCIDAndSort(checked((int)_variantType.LocaleId), _variantType.CompareOptions); diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/AlwaysEncryptedTests/SqlColumnEncryptionCertificateStoreProviderShould.cs b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/AlwaysEncryptedTests/SqlColumnEncryptionCertificateStoreProviderShould.cs index 79956e78d5..b0177ac464 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/AlwaysEncryptedTests/SqlColumnEncryptionCertificateStoreProviderShould.cs +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/AlwaysEncryptedTests/SqlColumnEncryptionCertificateStoreProviderShould.cs @@ -379,7 +379,7 @@ public void TestValidCertificatePaths(string certificateStoreNameAndLocation, ob // Certificate Store Location and Name. Assert.True(certificateStoreNameAndLocation != null); - if (null != location) + if (location != null) { // Certificate Store Location. certificateStoreLocation = (StoreLocation)location; diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/AlwaysEncryptedTests/Utility.cs b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/AlwaysEncryptedTests/Utility.cs index d91a15dee8..ae7d860a42 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/AlwaysEncryptedTests/Utility.cs +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/AlwaysEncryptedTests/Utility.cs @@ -304,8 +304,8 @@ internal static void AddEncryptionKeyToCipherMD( internal static Object GetSqlCipherMetadata(ushort ordinal, byte cipherAlgorithmId, string cipherAlgorithmName, byte encryptionType, byte normalizationRuleVersion) { - Assert.True(null != SqlCipherMetadataConstructor); - Assert.True(null != SqlTceCipherInfoEntryConstructor); + Assert.True(SqlCipherMetadataConstructor != null); + Assert.True(SqlTceCipherInfoEntryConstructor != null); Object entry = SqlTceCipherInfoEntryConstructor.Invoke(new object[] { 1 });// this param is "ordinal" Object[] parameters = new Object[] { entry, ordinal, cipherAlgorithmId, cipherAlgorithmName, encryptionType, normalizationRuleVersion }; return SqlCipherMetadataConstructor.Invoke(parameters); @@ -414,7 +414,7 @@ internal static void ClearSqlConnectionGlobalProviders() { SqlConnection conn = new SqlConnection(); FieldInfo field = conn.GetType().GetField("s_globalCustomColumnEncryptionKeyStoreProviders", BindingFlags.Static | BindingFlags.NonPublic); - Assert.True(null != field); + Assert.True(field != null); field.SetValue(conn, null); } #endregion diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs index 310fae44be..0a32356fe9 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs @@ -650,7 +650,7 @@ public static string GetAccessToken() AADAccessToken = GenerateAccessToken(AADAuthorityURL, username, password); } // Creates a new Object Reference of Access Token - See GitHub Issue 438 - return (null != AADAccessToken) ? new string(AADAccessToken.ToCharArray()) : null; + return AADAccessToken != null ? new string(AADAccessToken.ToCharArray()) : null; } public static string GetSystemIdentityAccessToken() @@ -663,7 +663,7 @@ public static string GetSystemIdentityAccessToken() ManagedIdentitySupported = false; } } - return (null != AADSystemIdentityAccessToken) ? new string(AADSystemIdentityAccessToken.ToCharArray()) : null; + return AADSystemIdentityAccessToken != null ? new string(AADSystemIdentityAccessToken.ToCharArray()) : null; } public static string GetUserIdentityAccessToken() @@ -677,7 +677,7 @@ public static string GetUserIdentityAccessToken() ManagedIdentitySupported = false; } } - return (null != AADUserIdentityAccessToken) ? new string(AADUserIdentityAccessToken.ToCharArray()) : null; + return AADUserIdentityAccessToken != null ? new string(AADUserIdentityAccessToken.ToCharArray()) : null; } public static bool IsAccessTokenSetup() => !string.IsNullOrEmpty(GetAccessToken()); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/ProviderAgnostic/MultipleResultsTest/MultipleResultsTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/ProviderAgnostic/MultipleResultsTest/MultipleResultsTest.cs index ef1a48fdea..cc5d6b42c2 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/ProviderAgnostic/MultipleResultsTest/MultipleResultsTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/ProviderAgnostic/MultipleResultsTest/MultipleResultsTest.cs @@ -171,7 +171,7 @@ private void PrintException(Type expected, Exception e, params string[] values) { try { - Debug.Assert(null != e, "PrintException: null exception"); + Debug.Assert(e != null, "PrintException: null exception"); _globalBuilder.Length = 0; _globalBuilder.Append(e.GetType().Name).Append(": "); @@ -195,14 +195,14 @@ private void PrintException(Type expected, Exception e, params string[] values) { Console.WriteLine(e.StackTrace); } - if (null != values) + if (values != null) { foreach (string value in values) { Console.WriteLine(value); } } - if (null != e.InnerException) + if (e.InnerException != null) { PrintException(e.InnerException.GetType(), e.InnerException); } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs index 2240836993..8bda7696a6 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs @@ -1442,7 +1442,7 @@ public void VerifyGetCommand(string methodName, bool? useColumnsForParameterName #region Utility_Methods private void CheckParameters(SqlCommand cmd, string expectedResults) { - Debug.Assert(null != cmd, "DumpParameters: null SqlCommand"); + Debug.Assert(cmd != null, "DumpParameters: null SqlCommand"); string actualResults = ""; StringBuilder builder = new StringBuilder(); @@ -1655,7 +1655,7 @@ private void WriteObject(StringBuilder textBuilder, object value, CultureInfo cu { Type valuetype = value.GetType(); - if ((null != used) && (!valuetype.IsPrimitive)) + if (used != null && (!valuetype.IsPrimitive)) { if (used.Contains(value)) { @@ -1814,7 +1814,7 @@ private void WriteObject(StringBuilder textBuilder, object value, CultureInfo cu PropertyInfo[] properties = valuetype.GetProperties(BindingFlags.Instance | BindingFlags.Public); bool hasinfo = false; - if ((null != fields) && (0 < fields.Length)) + if (fields != null && (0 < fields.Length)) { textBuilder.Append(fullName); fullName = null; @@ -1832,9 +1832,9 @@ private void WriteObject(StringBuilder textBuilder, object value, CultureInfo cu } hasinfo = true; } - if ((null != properties) && (0 < properties.Length)) + if (properties != null && (0 < properties.Length)) { - if (null != fullName) + if (fullName != null) { textBuilder.Append(fullName); fullName = null; @@ -1879,7 +1879,7 @@ private void WriteObject(StringBuilder textBuilder, object value, CultureInfo cu textBuilder.Append(valuetype.Name); textBuilder.Append('<'); MethodInfo method = valuetype.GetMethod("ToString", new Type[] { typeof(IFormatProvider) }); - if (null != method) + if (method != null) { textBuilder.Append((string)method.Invoke(value, new object[] { cultureInfo })); } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataClassificationTest/DataClassificationTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataClassificationTest/DataClassificationTest.cs index 8119bd2586..83eecc5b23 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataClassificationTest/DataClassificationTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataClassificationTest/DataClassificationTest.cs @@ -72,7 +72,7 @@ private static void RunTestsForServer(SqlCommand sqlCommand, bool rankEnabled = private static void VerifySensitivityClassification(SqlDataReader reader, bool rankEnabled = false) { - if (null != reader.SensitivityClassification) + if (reader.SensitivityClassification != null) { for (int columnPos = 0; columnPos < reader.SensitivityClassification.ColumnSensitivities.Count; columnPos++) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteTypeBoundaries.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteTypeBoundaries.cs index b469c0795b..1bcc4ef078 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteTypeBoundaries.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SteTypeBoundaries.cs @@ -447,7 +447,7 @@ public bool UseSeparateValueList { get { - return null != _separateValueList; + return _separateValueList != null; } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/TvpTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/TvpTest.cs index 07bb0f33f5..d1fe3bf6ac 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/TvpTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/TvpTest.cs @@ -1226,7 +1226,7 @@ private bool DoesRowMatchMetadata(object[] row, DataTable table) { for (int i = 0; i < row.Length; i++) { - if (null != row[i] && DBNull.Value != row[i] && row[i].GetType() != table.Columns[i].DataType) + if (row[i] != null && DBNull.Value != row[i] && row[i].GetType() != table.Columns[i].DataType) { result = false; } @@ -1313,13 +1313,13 @@ private IList GenerateDataTables(object[][] values) if (targetTable == null) { targetTable = CreateNewTable(row, ref valueTypes); - if (null != targetTable) + if (targetTable != null) { dtList.Add(targetTable); } } - if (null != targetTable) + if (targetTable != null) { targetTable.Rows.Add(row); } @@ -1445,7 +1445,7 @@ private void VerifyColumnBoundaries(SqlDataReader rdr, IList fie { value = rdr.GetValue(columnOrd); } - if (null != values) + if (values != null) { if (CompareValue(value, values[rowOrd][columnOrd], fieldMetaData[columnOrd])) { diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/InvalidAccessFromEvent.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/InvalidAccessFromEvent.cs index 744b8ae66a..c22039c2de 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/InvalidAccessFromEvent.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/InvalidAccessFromEvent.cs @@ -134,7 +134,7 @@ internal static void InnerTest(SqlRowsCopiedEventHandler eventHandler) } catch (Exception e) { - while (null != e.InnerException) + while (e.InnerException != null) { e = e.InnerException; }