From dbd8c6543b09c9382b85dc170577b7b62dd85bd3 Mon Sep 17 00:00:00 2001 From: Davoud Eshtehari Date: Mon, 19 Aug 2024 11:46:12 -0700 Subject: [PATCH] Squashed commit of the following: commit ac1012a6b7ddaf0b14526ced7cea8c16e0791b23 Author: dauinsight <145612907+dauinsight@users.noreply.github.com> Date: Fri Aug 16 13:22:55 2024 -0700 Hotfix v3.1.6 Release notes (#2767) commit 619fa749551ed0d9e387d75cb3e6d85fe00a3df4 Author: Javad Rahnama Date: Thu Aug 15 13:48:15 2024 -0700 Fix | Fix the issue with Socke.Connect in managed SNI (#2777) commit d3658edfcda0d7eecabc09afb5459bb3f79e6290 Author: DavoudEshtehari <61173489+DavoudEshtehari@users.noreply.github.com> Date: Wed Aug 14 17:18:51 2024 -0700 Update SNI version to 6.0.0-preview1.24226.4 (#2772) commit 7216e84fb9819b56df1d51ca13969d4f89bf507a Author: Benjamin Russell Date: Fri Aug 9 12:40:30 2024 -0500 `null != x` => `x != null` (#2751) commit 6fbbb787cd7ea35c06e292bb83d01ae94900b0bf Author: Benjamin Russell Date: Sat Aug 3 11:47:53 2024 -0500 Code Cleanup | `null == x` to `x == null` (#2749) - With one approval and CI success, I think that's enough to move ahead on this one. * `null == x` to `x == null` * Update src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs Co-authored-by: David Engel --------- Co-authored-by: David Engel commit 6f177e30f2a8bbd59a7ec093ef934e29e0578004 Author: Aris Rellegue <134557572+arellegue@users.noreply.github.com> Date: Tue Jul 30 19:52:38 2024 +0000 Fix | Fixed some Azure managed identity authentication unit test failures (#2652) --- CHANGELOG.md | 12 ++ release-notes/3.1/3.1.6.md | 80 ++++++++ release-notes/3.1/3.1.md | 1 + release-notes/3.1/README.md | 1 + ...qlColumnEncryptionAzureKeyVaultProvider.cs | 2 +- .../add-ons/AzureKeyVaultProvider/Utils.cs | 7 +- .../Data/ProviderBase/DbConnectionClosed.cs | 2 +- .../Data/ProviderBase/DbConnectionFactory.cs | 50 ++--- .../Data/ProviderBase/DbConnectionInternal.cs | 12 +- .../Interop/SNINativeMethodWrapper.Windows.cs | 4 +- .../Data/Common/DbConnectionOptions.cs | 6 +- .../Data/ProviderBase/DbConnectionFactory.cs | 4 +- .../Data/ProviderBase/DbConnectionInternal.cs | 24 +-- .../Data/ProviderBase/DbConnectionPool.cs | 64 +++---- .../ProviderBase/DbConnectionPoolIdentity.cs | 2 +- .../SqlClient/AlwaysEncryptedHelperClasses.cs | 6 +- .../Microsoft/Data/SqlClient/SNI/SNICommon.cs | 18 +- .../Data/SqlClient/SNI/SNITcpHandle.cs | 31 +-- ...uthenticationProviderManager.NetCoreApp.cs | 4 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 20 +- .../SqlColumnEncryptionCngProvider.Windows.cs | 8 +- .../SqlColumnEncryptionCspProvider.Windows.cs | 8 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 131 +++++++------ .../Microsoft/Data/SqlClient/SqlConnection.cs | 46 ++--- .../Data/SqlClient/SqlConnectionFactory.cs | 25 ++- .../Data/SqlClient/SqlConnectionHelper.cs | 26 +-- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 76 ++++---- .../Data/SqlClient/SqlDelegatedTransaction.cs | 20 +- .../SqlClient/SqlInternalConnectionTds.cs | 57 +++--- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 175 +++++++++-------- .../Data/SqlClient/TdsParserHelperClasses.cs | 4 +- .../SqlClient/TdsParserStateObject.netcore.cs | 12 +- .../SqlClient/TdsParserStateObjectNative.cs | 2 +- .../Data/Common/NameValuePermission.cs | 56 +++--- .../Microsoft/Data/Common/AdapterSwitches.cs | 2 +- .../Data/Common/DBConnectionString.cs | 36 ++-- .../Data/Common/DbConnectionOptions.cs | 16 +- .../src/Microsoft/Data/Common/GreenMethods.cs | 6 +- .../Data/Interop/SNINativeMethodWrapper.cs | 8 +- .../Microsoft/Data/ProviderBase/DbBuffer.cs | 18 +- .../Data/ProviderBase/DbConnectionClosed.cs | 2 +- .../Data/ProviderBase/DbConnectionFactory.cs | 54 +++--- .../Data/ProviderBase/DbConnectionInternal.cs | 38 ++-- .../Data/ProviderBase/DbConnectionPool.cs | 64 +++---- .../ProviderBase/DbConnectionPoolCounters.cs | 14 +- .../ProviderBase/DbConnectionPoolIdentity.cs | 2 +- .../SqlClient/Server/SmiContextFactory.cs | 10 +- .../SqlAuthenticationProviderManager.cs | 4 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 23 ++- .../Data/SqlClient/SqlClientPermission.cs | 52 ++--- .../SqlClient/SqlClientWrapperSmiStream.cs | 4 +- .../SqlClientWrapperSmiStreamChars.cs | 6 +- .../SqlColumnEncryptionCngProvider.cs | 8 +- .../SqlColumnEncryptionCspProvider.cs | 8 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 164 ++++++++-------- .../Microsoft/Data/SqlClient/SqlConnection.cs | 84 +++++---- .../Data/SqlClient/SqlConnectionFactory.cs | 29 ++- .../Data/SqlClient/SqlConnectionHelper.cs | 28 +-- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 127 +++++++------ .../Data/SqlClient/SqlDataReaderSmi.cs | 2 +- .../Data/SqlClient/SqlDelegatedTransaction.cs | 20 +- .../SqlClient/SqlInternalConnectionSmi.cs | 63 ++++--- .../SqlClient/SqlInternalConnectionTds.cs | 52 ++--- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 178 +++++++++--------- .../Data/SqlClient/TdsParserHelperClasses.cs | 10 +- .../SqlClient/TdsParserStateObject.netfx.cs | 14 +- .../src/Microsoft/Data/Common/AdapterUtil.cs | 6 +- .../Data/Common/DbConnectionOptions.Common.cs | 29 +-- .../Data/Common/DbConnectionStringCommon.cs | 26 ++- .../Data/Common/MultipartIdentifier.cs | 2 +- .../Microsoft/Data/Common/NameValuePair.cs | 2 +- .../src/Microsoft/Data/DataException.cs | 4 +- .../ProviderBase/DbConnectionPoolGroup.cs | 12 +- .../Data/ProviderBase/DbMetaDataFactory.cs | 2 +- .../ProviderBase/DbReferenceCollection.cs | 2 +- .../Data/Sql/SqlNotificationRequest.cs | 4 +- .../ActiveDirectoryAuthenticationProvider.cs | 10 +- .../Data/SqlClient/ColumnEncryptionKeyInfo.cs | 12 +- .../Data/SqlClient/SQLFallbackDNSCache.cs | 4 +- .../SqlClient/Server/MemoryRecordBuffer.cs | 2 +- .../Data/SqlClient/Server/MetadataUtilsSmi.cs | 12 +- .../SqlClient/Server/SmiEventSink_Default.cs | 16 +- .../Server/SmiEventSink_Default.netfx.cs | 36 ++-- .../Data/SqlClient/Server/SmiGettersStream.cs | 6 +- .../Data/SqlClient/Server/SmiMetaData.cs | 6 +- .../Data/SqlClient/Server/SmiSettersStream.cs | 6 +- .../Data/SqlClient/Server/SqlDataRecord.cs | 2 +- .../Data/SqlClient/Server/SqlMetaData.cs | 30 +-- .../Data/SqlClient/Server/SqlRecordBuffer.cs | 6 +- .../Data/SqlClient/Server/ValueUtilsSmi.cs | 2 +- .../SqlClient/Server/ValueUtilsSmi.netfx.cs | 4 +- .../SqlClient/SignatureVerificationCache.cs | 4 +- .../SqlAeadAes256CbcHmac256Algorithm.cs | 2 +- .../src/Microsoft/Data/SqlClient/SqlBuffer.cs | 4 +- ...SqlClientEncryptionAlgorithmFactoryList.cs | 2 +- ...ryptionCertificateStoreProvider.Windows.cs | 8 +- .../Data/SqlClient/SqlCommandBuilder.cs | 2 +- .../Microsoft/Data/SqlClient/SqlCommandSet.cs | 18 +- .../SqlConnectionPoolGroupProviderInfo.cs | 6 +- .../Data/SqlClient/SqlConnectionString.cs | 16 +- .../Data/SqlClient/SqlDataAdapter.cs | 20 +- .../Microsoft/Data/SqlClient/SqlDependency.cs | 34 ++-- .../Data/SqlClient/SqlDependencyListener.cs | 26 +-- .../Data/SqlClient/SqlDependencyUtils.cs | 8 +- .../Data/SqlClient/SqlEnclaveSession.cs | 2 +- .../src/Microsoft/Data/SqlClient/SqlEnums.cs | 2 +- .../Microsoft/Data/SqlClient/SqlException.cs | 2 +- .../Data/SqlClient/SqlInfoMessageEvent.cs | 2 +- .../Data/SqlClient/SqlInternalConnection.cs | 36 ++-- .../Data/SqlClient/SqlInternalTransaction.cs | 4 +- .../Microsoft/Data/SqlClient/SqlParameter.cs | 34 ++-- .../Data/SqlClient/SqlReferenceCollection.cs | 2 +- .../Data/SqlClient/SqlSecurityUtility.cs | 8 +- .../Microsoft/Data/SqlClient/SqlStatistics.cs | 4 +- .../src/Microsoft/Data/SqlClient/SqlStream.cs | 12 +- .../Data/SqlClient/SqlTransaction.Common.cs | 4 +- .../src/Microsoft/Data/SqlClient/SqlUtil.cs | 2 +- .../SqlClient/TdsParserSafeHandles.Windows.cs | 4 +- .../Data/SqlClient/TdsParserSessionPool.cs | 11 +- .../Data/SqlClient/TdsParserStateObject.cs | 4 +- .../Data/SqlClient/TdsParserStaticMethods.cs | 4 +- .../Data/SqlClient/TdsValueSetter.cs | 8 +- ...ncryptionCertificateStoreProviderShould.cs | 2 +- .../AlwaysEncryptedTests/Utility.cs | 6 +- .../ManualTests/DataCommon/DataTestUtility.cs | 12 +- .../MultipleResultsTest.cs | 10 +- .../SQL/AdapterTest/AdapterTest.cs | 16 +- .../DataClassificationTest.cs | 2 +- .../SQL/ExceptionTest/ExceptionTest.cs | 21 ++- .../SQL/ParameterTest/SteTypeBoundaries.cs | 2 +- .../ManualTests/SQL/ParameterTest/TvpTest.cs | 23 ++- .../SQL/RetryLogic/RetryLogicTestHelper.cs | 5 +- .../SqlConnectionReliabilityTest.cs | 6 +- .../SqlBulkCopyTest/InvalidAccessFromEvent.cs | 4 +- tools/props/Versions.props | 4 +- tools/specs/Microsoft.Data.SqlClient.nuspec | 6 +- 136 files changed, 1462 insertions(+), 1337 deletions(-) create mode 100644 release-notes/3.1/3.1.6.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b8d651ebf..4778cdce02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -660,6 +660,18 @@ This update brings the below changes over the previous release: - Optimized async method allocations in .NET Framework by porting changes from .NET Core. [#1084](https://github.com/dotnet/SqlClient/pull/1084) - Various code improvements [#902](https://github.com/dotnet/SqlClient/pull/902) [#925](https://github.com/dotnet/SqlClient/pull/925) [#933](https://github.com/dotnet/SqlClient/pull/933) [#934](https://github.com/dotnet/SqlClient/pull/934) [#1024](https://github.com/dotnet/SqlClient/pull/1024) [#1057](https://github.com/dotnet/SqlClient/pull/1057) [#1122](https://github.com/dotnet/SqlClient/pull/1122) [#1133](https://github.com/dotnet/SqlClient/pull/1133) [#1134](https://github.com/dotnet/SqlClient/pull/1134) [#1141](https://github.com/dotnet/SqlClient/pull/1141) [#1187](https://github.com/dotnet/SqlClient/pull/1187) [#1188](https://github.com/dotnet/SqlClient/pull/1188) [#1223](https://github.com/dotnet/SqlClient/pull/1223) [#1225](https://github.com/dotnet/SqlClient/pull/1225) [#1226](https://github.com/dotnet/SqlClient/pull/1226) +## [Stable release 3.1.6] - 2024-08-15 + +### Fixed + +- Fixed connection to unsubscribe from transaction completion events before returning it to the connection pool. [#2301](https://github.com/dotnet/SqlClient/pull/2301) [#2434](https://github.com/dotnet/SqlClient/pull/2434) +- Fixed `AcquireTokenAsync` timeout handling for edge cases in `ActiveDirectoryAuthenticationProvider`. [#2709](https://github.com/dotnet/SqlClient/pull/2709) + +### Changed + +- Updated Microsoft.Data.SqlClient.SNI version 3.0.1 to 3.0.2 [#2676](https://github.com/dotnet/SqlClient/pull/2676) which includes the fix for AppDomain crashing in issue [#1418](https://github.com/dotnet/SqlClient/issues/1418) and various code refactors. +- Code health improvements: [#2147](https://github.com/dotnet/SqlClient/pull/2147), [#2515](https://github.com/dotnet/SqlClient/pull/2515), [#2517](https://github.com/dotnet/SqlClient/pull/2517) addresses [CVE-2019-0545](https://github.com/advisories/GHSA-2xjx-v99w-gqf3), [#2539](https://github.com/dotnet/SqlClient/pull/2539) + ## [Stable release 3.1.5] - 2024-01-09 ### Fixed diff --git a/release-notes/3.1/3.1.6.md b/release-notes/3.1/3.1.6.md new file mode 100644 index 0000000000..b9095c1b37 --- /dev/null +++ b/release-notes/3.1/3.1.6.md @@ -0,0 +1,80 @@ +# Release Notes + +## Microsoft.Data.SqlClient 3.1.6 released 15 August 2024 + +This update brings the below changes over the previous release: + +### Fixed + +- Fixed connection to unsubscribe from transaction completion events before returning it to the connection pool. [#2301](https://github.com/dotnet/SqlClient/pull/2301) [#2434](https://github.com/dotnet/SqlClient/pull/2434) +- Fixed `AcquireTokenAsync` timeout handling for edge cases in `ActiveDirectoryAuthenticationProvider`. [#2709](https://github.com/dotnet/SqlClient/pull/2709) + +### Changed + +- Updated Microsoft.Data.SqlClient.SNI version 3.0.1 to 3.0.2 [#2676](https://github.com/dotnet/SqlClient/pull/2676) which includes the fix for AppDomain crashing in issue [#1418](https://github.com/dotnet/SqlClient/issues/1418) and various code refactors. +- Code health improvements: [#2147](https://github.com/dotnet/SqlClient/pull/2147), [#2515](https://github.com/dotnet/SqlClient/pull/2515), [#2517](https://github.com/dotnet/SqlClient/pull/2517) addresses [CVE-2019-0545](https://github.com/advisories/GHSA-2xjx-v99w-gqf3), [#2539](https://github.com/dotnet/SqlClient/pull/2539) + +## Target Platform Support + +- .NET Framework 4.6.1+ (Windows x86, Windows x64) +- .NET Core 2.1+ (Windows x86, Windows x64, Windows ARM64, Windows ARM, Linux, macOS) +- .NET Standard 2.0+ (Windows x86, Windows x64, Windows ARM64, Windows ARM, Linux, macOS) + +### Dependencies + +#### .NET Framework 4.6.1 + +- Microsoft.Data.SqlClient.SNI 3.0.2 +- Azure.Identity 1.3.0 +- Microsoft.Identity.Client 4.22.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 6.8.0 +- Microsoft.IdentityModel.JsonWebTokens 6.8.0 +- System.Configuration.ConfigurationManager 4.7.0 +- System.Text.Encodings.Web 4.7.2 + +#### .NET Core 2.1 + +- Microsoft.Data.SqlClient.SNI.runtime 3.0.2 +- Microsoft.Win32.Registry 4.7.0 +- System.Security.Principal.Windows 4.7.0 +- System.Text.Encoding.CodePages 4.7.0 +- System.Text.Encodings.Web 4.7.2 +- System.Diagnostics.DiagnosticSource 4.7.0 +- System.Configuration.ConfigurationManager 4.7.0 +- System.Runtime.Caching 4.7.0 +- Azure.Identity 1.3.0 +- Microsoft.Identity.Client 4.22.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 6.8.0 +- Microsoft.IdentityModel.JsonWebTokens 6.8.0 + +#### .NET Core 3.1 + +- Microsoft.Data.SqlClient.SNI.runtime 3.0.2 +- Microsoft.Win32.Registry 4.7.0 +- System.Security.Principal.Windows 4.7.0 +- System.Text.Encoding.CodePages 4.7.0 +- System.Text.Encodings.Web 4.7.2 +- System.Diagnostics.DiagnosticSource 4.7.0 +- System.Configuration.ConfigurationManager 4.7.0 +- System.Runtime.Caching 4.7.0 +- Azure.Identity 1.3.0 +- Microsoft.Identity.Client 4.22.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 6.8.0 +- Microsoft.IdentityModel.JsonWebTokens 6.8.0 + +#### .NET Standard + +- Microsoft.Data.SqlClient.SNI.runtime 3.0.2 +- Microsoft.Win32.Registry 4.7.0 +- System.Buffers 4.5.1 +- System.Memory 4.5.4 +- System.Security.Principal.Windows 4.7.0 +- System.Text.Encoding.CodePages 4.7.0 +- System.Text.Encodings.Web 4.7.2 +- System.Runtime.Caching 4.7.0 +- Azure.Identity 1.3.0 +- Microsoft.Identity.Client 4.22.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 6.8.0 +- Microsoft.IdentityModel.JsonWebTokens 6.8.0 +- System.Configuration.ConfigurationManager 4.7.0 +- System.Runtime.Loader 4.3.0 diff --git a/release-notes/3.1/3.1.md b/release-notes/3.1/3.1.md index b3a5e2eb2c..e1f5caf9ce 100644 --- a/release-notes/3.1/3.1.md +++ b/release-notes/3.1/3.1.md @@ -4,6 +4,7 @@ The following Microsoft.Data.SqlClient 3.1 stable releases have been shipped: | Release Date | Version | Notes | | :-- | :-- | :--: | +| 2024/08/15 | 3.1.6 | [release notes](3.1.6.md) | | 2024/01/09 | 3.1.5 | [release notes](3.1.5.md) | | 2023/10/31 | 3.1.4 | [release notes](3.1.4.md) | | 2023/03/10 | 3.1.3 | [release notes](3.1.3.md) | diff --git a/release-notes/3.1/README.md b/release-notes/3.1/README.md index b3a5e2eb2c..e1f5caf9ce 100644 --- a/release-notes/3.1/README.md +++ b/release-notes/3.1/README.md @@ -4,6 +4,7 @@ The following Microsoft.Data.SqlClient 3.1 stable releases have been shipped: | Release Date | Version | Notes | | :-- | :-- | :--: | +| 2024/08/15 | 3.1.6 | [release notes](3.1.6.md) | | 2024/01/09 | 3.1.5 | [release notes](3.1.5.md) | | 2023/10/31 | 3.1.4 | [release notes](3.1.4.md) | | 2023/03/10 | 3.1.3 | [release notes](3.1.3.md) | diff --git a/src/Microsoft.Data.SqlClient/add-ons/AzureKeyVaultProvider/SqlColumnEncryptionAzureKeyVaultProvider.cs b/src/Microsoft.Data.SqlClient/add-ons/AzureKeyVaultProvider/SqlColumnEncryptionAzureKeyVaultProvider.cs index d06063f8c0..eb8c8d77c4 100644 --- a/src/Microsoft.Data.SqlClient/add-ons/AzureKeyVaultProvider/SqlColumnEncryptionAzureKeyVaultProvider.cs +++ b/src/Microsoft.Data.SqlClient/add-ons/AzureKeyVaultProvider/SqlColumnEncryptionAzureKeyVaultProvider.cs @@ -241,7 +241,7 @@ byte[] DecryptEncryptionKey() byte[] message = new byte[encryptedColumnEncryptionKey.Length - signatureLength]; Buffer.BlockCopy(encryptedColumnEncryptionKey, 0, message, 0, encryptedColumnEncryptionKey.Length - signatureLength); - if (null == message) + if (message == null) { throw ADP.NullHashFound(); } diff --git a/src/Microsoft.Data.SqlClient/add-ons/AzureKeyVaultProvider/Utils.cs b/src/Microsoft.Data.SqlClient/add-ons/AzureKeyVaultProvider/Utils.cs index 2909422c1a..f71080ffab 100644 --- a/src/Microsoft.Data.SqlClient/add-ons/AzureKeyVaultProvider/Utils.cs +++ b/src/Microsoft.Data.SqlClient/add-ons/AzureKeyVaultProvider/Utils.cs @@ -45,7 +45,7 @@ internal static void ValidateNotNullOrWhitespaceForEach(string[] parameters, str internal static void ValidateEncryptionAlgorithm(string encryptionAlgorithm, bool isSystemOp) { // This validates that the encryption algorithm is RSA_OAEP - if (null == encryptionAlgorithm) + if (encryptionAlgorithm == null) { throw ADP.NullAlgorithm(isSystemOp); } @@ -124,8 +124,9 @@ internal static ArgumentException InvalidSignatureTemplate(string masterKeyPath) internal static ArgumentException InvalidAKVPath(string masterKeyPath, bool isSystemOp) { - string errorMessage = null == masterKeyPath ? Strings.NullAkvPath - : string.Format(CultureInfo.InvariantCulture, Strings.InvalidAkvPathTemplate, masterKeyPath); + string errorMessage = masterKeyPath == null + ? Strings.NullAkvPath + : string.Format(CultureInfo.InvariantCulture, Strings.InvalidAkvPathTemplate, masterKeyPath); if (isSystemOp) { return new ArgumentNullException(Constants.AeParamMasterKeyPath, errorMessage); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs index a7c98207c7..a8d9dcc13f 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs @@ -102,7 +102,7 @@ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnect // we are completing an asynchronous open Debug.Assert(retry.Task.Status == TaskStatus.RanToCompletion, "retry task must be completed successfully"); DbConnectionInternal openConnection = retry.Task.Result; - if (null == openConnection) + if (openConnection == null) { connectionFactory.SetInnerConnectionTo(outerConnection, this); throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull); 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 e5c76701e4..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,19 +207,19 @@ 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 // new pool entry and add it to our collection. DbConnectionOptions connectionOptions = CreateConnectionOptions(key.ConnectionString, userConnectionOptions); - if (null == connectionOptions) + if (connectionOptions == null) { throw ADP.InternalConnectionError(ADP.ConnectionError.ConnectionOptionsMissing); } - if (null == userConnectionOptions) + if (userConnectionOptions == null) { // we only allow one expansion on the connection string userConnectionOptions = connectionOptions; @@ -236,9 +236,9 @@ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, D } // We don't support connection pooling on Win9x - if (null == poolOptions) + if (poolOptions == null) { - if (null != connectionPoolGroup) + if (connectionPoolGroup != null) { // reusing existing pool option in case user originally used SetConnectionPoolOptions poolOptions = connectionPoolGroup.PoolGroupOptions; @@ -276,10 +276,10 @@ 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 (null == userConnectionOptions) + else if (userConnectionOptions == null) { userConnectionOptions = connectionPoolGroup.ConnectionOptions; } @@ -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 bc77341b30..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 @@ -178,10 +178,10 @@ public ConnectionState State internal void AddWeakReference(object value, int tag) { - if (null == _referenceCollection) + if (_referenceCollection == null) { _referenceCollection = CreateReferenceCollection(); - if (null == _referenceCollection) + if (_referenceCollection == null) { throw ADP.InternalError(ADP.InternalErrorCode.CreateReferenceCollectionReturnedNull); } @@ -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); } @@ -349,7 +349,7 @@ protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnect connectionFactory.SetInnerConnectionTo(outerConnection, this); throw; } - if (null == openConnection) + if (openConnection == null) { connectionFactory.SetInnerConnectionTo(outerConnection, this); throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull); @@ -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 35440e9e11..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) && (null == rootFolderPath)) + 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 1a2e809147..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; @@ -43,7 +43,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour poolGroup = GetConnectionPoolGroup(owningConnection); // Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread. connectionPool = GetConnectionPool(owningConnection, poolGroup); - if (null == connectionPool) + if (connectionPool == null) { // If GetConnectionPool returns null, we can be certain that // this connection should not be pooled via DbConnectionPool 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 a3624ccdce..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 (((null == currentEnlistedTransaction) && (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 @@ -354,7 +354,7 @@ virtual internal void DelegatedTransactionEnded() DbConnectionPool pool = Pool; - if (null == pool) + if (pool == null) { throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool); // pooled connection does not have a pool } @@ -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 3bf8a9d561..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(); } @@ -729,7 +729,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio try { newObj = _connectionFactory.CreatePooledConnection(this, owningObject, _connectionPoolGroup.ConnectionOptions, _connectionPoolGroup.PoolKey, userOptions); - if (null == newObj) + if (newObj == null) { throw ADP.InternalError(ADP.InternalErrorCode.CreateObjectReturnedNull); // CreateObject succeeded, but null object } @@ -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. @@ -1172,7 +1172,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj obj = GetFromTransactedPool(out transaction); } - if (null == obj) + if (obj == null) { Interlocked.Increment(ref _waitCount); @@ -1217,7 +1217,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj } catch { - if (null == obj) + if (obj == null) { Interlocked.Decrement(ref _waitCount); } @@ -1227,13 +1227,13 @@ 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); } } - if (null == obj) + if (obj == null) { // If we were not able to create an object, check to see if // we reached MaxPoolSize. If so, we will no longer wait on @@ -1304,15 +1304,15 @@ 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; } - } while (null == obj); + } 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/SNI/SNICommon.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs index c9515d971f..b3d47cb28c 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs @@ -292,20 +292,14 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ internal static IPAddress[] GetDnsIpAddresses(string serverName, TimeoutTimer timeout) { - using (TrySNIEventScope.Create(nameof(SNICommon))) + IPAddress[] ipAddresses = GetDnsIpAddresses(serverName); + + // We cannot timeout accurately in sync code above, so throw TimeoutException if we've now exceeded the timeout. + if (timeout.IsExpired) { - int remainingTimeout = timeout.MillisecondsRemainingInt; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.INFO, - "Getting DNS host entries for serverName {0} within {1} milliseconds.", - args0: serverName, - args1: remainingTimeout); - using CancellationTokenSource cts = new CancellationTokenSource(remainingTimeout); - // using this overload to support netstandard - Task task = Dns.GetHostAddressesAsync(serverName); - task.ConfigureAwait(false); - task.Wait(cts.Token); - return task.Result; + throw new TimeoutException(); } + return ipAddresses; } internal static IPAddress[] GetDnsIpAddresses(string serverName) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNITcpHandle.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNITcpHandle.cs index 2791de17a4..666c38fa75 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNITcpHandle.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNITcpHandle.cs @@ -426,33 +426,16 @@ private static Socket Connect(string serverName, int port, TimeoutTimer timeout, bool isConnected; try // catching SocketException with SocketErrorCode == WouldBlock to run Socket.Select { - if (isInfiniteTimeout) + socket.Connect(ipAddress, port); + if (!isInfiniteTimeout) { - socket.Connect(ipAddress, port); - } - else - { - if (timeout.IsExpired) - { - return null; - } - // Socket.Connect does not support infinite timeouts, so we use Task to simulate it - Task socketConnectTask = new Task(() => socket.Connect(ipAddress, port)); - socketConnectTask.ConfigureAwait(false); - socketConnectTask.Start(); - int remainingTimeout = timeout.MillisecondsRemainingInt; - if (!socketConnectTask.Wait(remainingTimeout)) - { - throw ADP.TimeoutException($"The socket couldn't connect during the expected {remainingTimeout} remaining time."); - } throw SQL.SocketDidNotThrow(); } isConnected = true; } - catch (AggregateException aggregateException) when (!isInfiniteTimeout - && aggregateException.InnerException is SocketException socketException - && socketException.SocketErrorCode == SocketError.WouldBlock) + catch (SocketException socketException) when (!isInfiniteTimeout && + socketException.SocketErrorCode == SocketError.WouldBlock) { // https://github.com/dotnet/SqlClient/issues/826#issuecomment-736224118 // Socket.Select is used because it supports timeouts, while Socket.Connect does not @@ -509,11 +492,11 @@ private static Socket Connect(string serverName, int port, TimeoutTimer timeout, return socket; } } - catch (AggregateException aggregateException) when (aggregateException.InnerException is SocketException socketException) + catch (SocketException e) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "THIS EXCEPTION IS BEING SWALLOWED: {0}", args0: socketException?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "THIS EXCEPTION IS BEING SWALLOWED: {0}", args0: e?.Message); SqlClientEventSource.Log.TryAdvancedTraceEvent( - $"{nameof(SNITCPHandle)}.{nameof(Connect)}{EventType.ERR}THIS EXCEPTION IS BEING SWALLOWED: {socketException}"); + $"{nameof(SNITCPHandle)}.{nameof(Connect)}{EventType.ERR}THIS EXCEPTION IS BEING SWALLOWED: {e}"); } finally { 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 dd57c60da8..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 @@ -21,7 +21,7 @@ static SqlAuthenticationProviderManager() { // New configuration section "SqlClientAuthenticationProviders" for Microsoft.Data.SqlClient accepted to avoid conflicts with older one. configurationSection = FetchConfigurationSection(SqlClientAuthenticationProviderConfigurationSection.Name); - if (null == configurationSection) + if (configurationSection == null) { // If configuration section is not yet found, try with old Configuration Section name for backwards compatibility configurationSection = FetchConfigurationSection(SqlAuthenticationProviderConfigurationSection.Name); @@ -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 92c6d0075c..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) { @@ -540,7 +540,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i isInTransaction = _connection.HasLocalTransaction; // Throw if there is a transaction but no flag is set - if (isInTransaction && null == _externalTransaction && null == _internalTransaction && (_connection.Parser != null && _connection.Parser.CurrentTransaction != null && _connection.Parser.CurrentTransaction.IsLocal)) + if (isInTransaction && _externalTransaction == null && _internalTransaction == null && (_connection.Parser != null && _connection.Parser.CurrentTransaction != null && _connection.Parser.CurrentTransaction.IsLocal)) { throw SQL.BulkLoadExistingTransaction(); } @@ -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) { @@ -1281,7 +1281,7 @@ private SourceColumnMetadata GetColumnMetadata(int ordinal) private void CreateOrValidateConnection(string method) { - if (null == _connection) + if (_connection == null) { throw ADP.ConnectionRequired(method); } @@ -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/SqlColumnEncryptionCngProvider.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCngProvider.Windows.cs index a3c92002d1..cb09f49d91 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCngProvider.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCngProvider.Windows.cs @@ -32,7 +32,7 @@ public override byte[] DecryptColumnEncryptionKey(string masterKeyPath, string e // Validate the input parameters ValidateNonEmptyKeyPath(masterKeyPath, isSystemOp: true); - if (null == encryptedColumnEncryptionKey) + if (encryptedColumnEncryptionKey == null) { throw SQL.NullEncryptedColumnEncryptionKey(); } @@ -126,7 +126,7 @@ public override byte[] EncryptColumnEncryptionKey(string masterKeyPath, string e // Validate the input parameters ValidateNonEmptyKeyPath(masterKeyPath, isSystemOp: false); - if (null == columnEncryptionKey) + if (columnEncryptionKey == null) { throw SQL.NullColumnEncryptionKey(); } @@ -231,7 +231,7 @@ public override bool VerifyColumnMasterKeyMetadata(string masterKeyPath, bool al private void ValidateEncryptionAlgorithm(string encryptionAlgorithm, bool isSystemOp) { // This validates that the encryption algorithm is RSA_OAEP - if (null == encryptionAlgorithm) + if (encryptionAlgorithm == null) { throw SQL.NullKeyEncryptionAlgorithm(isSystemOp); } @@ -251,7 +251,7 @@ private void ValidateNonEmptyKeyPath(string masterKeyPath, bool isSystemOp) { if (string.IsNullOrWhiteSpace(masterKeyPath)) { - if (null == masterKeyPath) + if (masterKeyPath == null) { throw SQL.NullCngKeyPath(isSystemOp); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCspProvider.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCspProvider.Windows.cs index 891c0e1c61..c356e73527 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCspProvider.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCspProvider.Windows.cs @@ -40,7 +40,7 @@ public override byte[] DecryptColumnEncryptionKey(string masterKeyPath, string e // Validate the input parameters ValidateNonEmptyCSPKeyPath(masterKeyPath, isSystemOp: true); - if (null == encryptedColumnEncryptionKey) + if (encryptedColumnEncryptionKey == null) { throw SQL.NullEncryptedColumnEncryptionKey(); } @@ -134,7 +134,7 @@ public override byte[] EncryptColumnEncryptionKey(string masterKeyPath, string e // Validate the input parameters ValidateNonEmptyCSPKeyPath(masterKeyPath, isSystemOp: false); - if (null == columnEncryptionKey) + if (columnEncryptionKey == null) { throw SQL.NullColumnEncryptionKey(); } @@ -239,7 +239,7 @@ public override bool VerifyColumnMasterKeyMetadata(string masterKeyPath, bool al private void ValidateEncryptionAlgorithm(string encryptionAlgorithm, bool isSystemOp) { // This validates that the encryption algorithm is RSA_OAEP - if (null == encryptionAlgorithm) + if (encryptionAlgorithm == null) { throw SQL.NullKeyEncryptionAlgorithm(isSystemOp); } @@ -260,7 +260,7 @@ private void ValidateNonEmptyCSPKeyPath(string masterKeyPath, bool isSystemOp) { if (string.IsNullOrWhiteSpace(masterKeyPath)) { - if (null == masterKeyPath) + if (masterKeyPath == null) { throw SQL.NullCspKeyPath(isSystemOp); } 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 dd052bb346..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) && (null == _transaction.Connection)) + if (_transaction != null && _transaction.Connection == null) { _transaction = null; } @@ -783,7 +783,7 @@ public override bool DesignTimeVisible { get { - if (null == _parameters) + if (_parameters == null) { // delay the creation of the SqlParameterCollection // until user actually uses the Parameters property @@ -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); } @@ -1028,12 +1028,12 @@ public override void Cancel() // if we have pending data, but it is not a result of this command, then we don't cancel either. Note that // this model is implementable because we only allow one active command at any one time. This code // will have to change we allow multiple outstanding batches - if (null == _activeConnection) + if (_activeConnection == null) { return; } SqlInternalConnectionTds connection = (_activeConnection.InnerConnection as SqlInternalConnectionTds); - if (null == connection) + if (connection == null) { // Fail with out locking return; } @@ -1050,12 +1050,11 @@ public override void Cancel() } TdsParser parser = connection.Parser; - if (null == parser) + if (parser == null) { return; } - if (!_pendingCancel) { // Do nothing if already pending. // Before attempting actual cancel, set the _pendingCancel flag to false. @@ -1066,7 +1065,7 @@ public override void Cancel() _pendingCancel = true; TdsParserStateObject stateObj = _stateObj; - if (null != stateObj) + if (stateObj != null) { stateObj.Cancel(this); } @@ -1625,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(); } @@ -1644,7 +1643,7 @@ private object InternalEndExecuteNonQuery(IAsyncResult asyncResult, bool isInter } } - Debug.Assert(null == _stateObj, "non-null state object in EndExecuteNonQuery"); + Debug.Assert(_stateObj == null, "non-null state object in EndExecuteNonQuery"); return _rowsAffected; } @@ -1652,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; @@ -1675,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) { @@ -1700,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) { @@ -1716,7 +1715,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, bo } } - Debug.Assert(isAsync || null == _stateObj, "non-null state object in InternalExecuteNonQuery"); + Debug.Assert(isAsync || _stateObj == null, "non-null state object in InternalExecuteNonQuery"); return task; } @@ -2001,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) { @@ -2441,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(); } @@ -2564,7 +2563,7 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, bool is CheckThrowSNIException(); SqlDataReader reader = CompleteAsyncExecuteReader(isInternal); - Debug.Assert(null == _stateObj, "non-null state object in InternalEndExecuteReader"); + Debug.Assert(_stateObj == null, "non-null state object in InternalEndExecuteReader"); return reader; } @@ -3178,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]) { @@ -3198,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. @@ -3297,7 +3296,7 @@ internal void DeriveParameters() // Use common parser for SqlClient and OleDb - parse into 4 parts - Server, Catalog, Schema, ProcedureName string[] parsedSProc = MultipartIdentifier.ParseMultipartIdentifier(CommandText, "[\"", "]\"", Strings.SQL_SqlCommandCommandText, false); - if (null == parsedSProc[3] || string.IsNullOrEmpty(parsedSProc[3])) + if (string.IsNullOrEmpty(parsedSProc[3])) { throw ADP.NoStoredProcedureExists(CommandText); } @@ -3362,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; @@ -3586,11 +3585,11 @@ 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) { - if (null == _sqlDep.Options) + if (_sqlDep.Options == null) { // If null, SqlDependency was not created with options, so we need to obtain default options now. // GetDefaultOptions can and will throw under certain conditions. @@ -3800,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(); } @@ -3885,10 +3884,10 @@ private void PrepareForTransparentEncryption(CommandBehavior cmdBehavior, bool r // If we didn't have parameters, we can fall back to regular code path, by simply returning. if (!describeParameterEncryptionNeeded) { - Debug.Assert(null == fetchInputParameterEncryptionInfoTask, + Debug.Assert(fetchInputParameterEncryptionInfoTask == null, "fetchInputParameterEncryptionInfoTask should not be set if describe parameter encryption is not needed."); - Debug.Assert(null == describeParameterEncryptionDataReader, + Debug.Assert(describeParameterEncryptionDataReader == null, "SqlDataReader created for describe parameter encryption params when it is not needed."); return; @@ -4013,7 +4012,7 @@ private SqlDataReader GetParameterEncryptionDataReader(out Task returnTask, Task // Complete executereader. describeParameterEncryptionDataReader = command.CompleteAsyncExecuteReader(forDescribeParameterEncryption: true); - Debug.Assert(null == command._stateObj, "non-null state object in PrepareForTransparentEncryption."); + Debug.Assert(command._stateObj == null, "non-null state object in PrepareForTransparentEncryption."); // Read the results of describe parameter encryption. command.ReadDescribeEncryptionParameterResults(describeParameterEncryptionDataReader, describeParameterEncryptionRpcOriginalRpcMap, inRetry); @@ -4087,7 +4086,7 @@ private SqlDataReader GetParameterEncryptionDataReaderAsync(out Task returnTask, // Complete executereader. describeParameterEncryptionDataReader = CompleteAsyncExecuteReader(forDescribeParameterEncryption: true); - Debug.Assert(null == _stateObj, "non-null state object in PrepareForTransparentEncryption."); + Debug.Assert(_stateObj == null, "non-null state object in PrepareForTransparentEncryption."); // Read the results of describe parameter encryption. ReadDescribeEncryptionParameterResults(describeParameterEncryptionDataReader, @@ -4732,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; @@ -4756,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)) @@ -4990,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)); @@ -5130,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"); @@ -5175,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(); } @@ -5191,7 +5190,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi } } - Debug.Assert(isAsync || null == _stateObj, "non-null state object in RunExecuteReader"); + Debug.Assert(isAsync || _stateObj == null, "non-null state object in RunExecuteReader"); return ds; } @@ -5316,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 { @@ -5409,7 +5408,7 @@ private Task RegisterForConnectionCloseNotification(Task outerTask) // throws exception for error case, returns false if the commandText is empty private void ValidateCommand(bool isAsync, [CallerMemberName] string method = "") { - if (null == _activeConnection) + if (_activeConnection == null) { throw ADP.ConnectionRequired(method); } @@ -5420,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(); @@ -5455,14 +5454,14 @@ 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; } // throw if the connection is in a transaction but there is no // locally assigned transaction object - if (_activeConnection.HasLocalTransactionFromAPI && (null == _transaction)) + if (_activeConnection.HasLocalTransactionFromAPI && _transaction == null) { throw ADP.TransactionRequired(method); } @@ -5470,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,8 +5498,8 @@ private void ValidateAsyncCommand() private void GetStateObject(TdsParser parser = null) { - Debug.Assert(null == _stateObj, "StateObject not null on GetStateObject"); - Debug.Assert(null != _activeConnection, "no active connection?"); + Debug.Assert(_stateObj == null, "StateObject not null on GetStateObject"); + Debug.Assert(_activeConnection != null, "no active connection?"); if (_pendingCancel) { @@ -5551,7 +5550,7 @@ private void PutStateObject() TdsParserStateObject stateObj = _stateObj; _stateObj = null; - if (null != stateObj) + if (stateObj != null) { stateObj.CloseSession(); } @@ -5641,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 } @@ -5687,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. @@ -5807,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(); } @@ -5850,7 +5849,7 @@ private SqlParameter GetParameterForOutputValueExtraction(SqlParameterCollection SqlParameter thisParam = null; bool foundParam = false; - if (null == paramName) + if (paramName == null) { // rec.parameter should only be null for a return value from a function for (int i = 0; i < paramCount; i++) @@ -5979,12 +5978,12 @@ private void SetUpRPCParameters(_SqlRPC rpc, bool inSchema, SqlParameterCollecti // set default value bit if (parameter.Direction != ParameterDirection.Output) { - // remember that null == Convert.IsEmpty, DBNull.Value is a database null! + // remember that Convert.IsEmpty is null, DBNull.Value is a database null! // Don't assume a default value exists for parameters in the case when // the user is simply requesting schema. // TVPs use DEFAULT and do not allow NULL, even for schema only. - if (null == parameter.Value && (!inSchema || SqlDbType.Structured == parameter.SqlDbType)) + if (parameter.Value == null && (!inSchema || SqlDbType.Structured == parameter.SqlDbType)) { options |= TdsEnums.RPC_PARAM_DEFAULT; } @@ -6102,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; } // @@ -6437,10 +6436,10 @@ 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 (null == s) + if (s == null) { SqlString sval = val is SqlString ? (SqlString)val : SqlString.Null; if (!sval.IsNull) @@ -6450,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 @@ -6502,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]); } @@ -6621,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 fd4ed4d0de..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 @@ -468,7 +468,7 @@ public bool StatisticsEnabled // start if (ConnectionState.Open == State) { - if (null == _statistics) + if (_statistics == null) { _statistics = new SqlStatistics(); _statistics._openTimestamp = ADP.TimerCurrent(); @@ -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(); } @@ -1883,7 +1883,7 @@ private void PrepareStatisticsForNewConnection() s_diagnosticListener.IsEnabled(SqlClientCommandAfter.Name) || s_diagnosticListener.IsEnabled(SqlClientConnectionOpenAfter.Name)) { - if (null == _statistics) + if (_statistics == null) { _statistics = new SqlStatistics(); } @@ -2146,7 +2146,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action 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 7526f38623..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,8 +85,7 @@ override protected DbConnectionInternal CreateConnection(DbConnectionOptions opt redirectedUserInstance = true; string instanceName; - if ((null == pool) || - (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 @@ -105,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 @@ -114,7 +113,7 @@ override protected DbConnectionInternal CreateConnection(DbConnectionOptions opt } finally { - if (null != sseConnection) + if (sseConnection != null) { sseConnection.Dispose(); } @@ -208,7 +207,7 @@ override internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupPro internal static SqlConnectionString FindSqlConnectionOptions(SqlConnectionPoolKey key) { SqlConnectionString connectionOptions = (SqlConnectionString)SingletonInstance.FindConnectionOptions(key); - if (null == connectionOptions) + if (connectionOptions == null) { connectionOptions = new SqlConnectionString(key.ConnectionString); } @@ -223,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; } @@ -233,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; } @@ -243,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; } @@ -253,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(); } @@ -262,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; } @@ -271,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); } @@ -280,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); } @@ -290,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 a34be614cd..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); - if ((null == connectionOptions) || connectionOptions.IsEmpty) + 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 de86ff932e..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,9 +431,9 @@ 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(null == _snapshot, "Should not change during execution of asynchronous command"); + Debug.Assert(_snapshot == null, "Should not change during execution of asynchronous command"); stateObj.Owner = this; _stateObj = stateObj; @@ -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; @@ -1446,7 +1448,7 @@ override public int GetOrdinal(string name) try { statistics = SqlStatistics.StartTimer(Statistics); - if (null == _fieldNameLookup) + if (_fieldNameLookup == null) { CheckMetaDataIsReady(); _fieldNameLookup = new FieldNameLookup(this, _defaultLCID); @@ -1480,12 +1482,12 @@ public override DataTable GetSchemaTable() try { statistics = SqlStatistics.StartTimer(Statistics); - if (null == _metaData || null == _metaData.schemaTable) + 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; @@ -1696,7 +1698,7 @@ private TdsOperationStatus TryGetBytesInternal(int i, long dataIndex, byte[] buf } // if no buffer is passed in, return the number total of bytes, or -1 - if (null == buffer) + if (buffer == null) { if (_metaData[i].metaType.IsPlp) { @@ -1807,7 +1809,7 @@ private TdsOperationStatus TryGetBytesInternal(int i, long dataIndex, byte[] buf cbytes = data.Length; // if no buffer is passed in, return the number of characters we have - if (null == buffer) + if (buffer == null) { remaining = cbytes; return TdsOperationStatus.Done; @@ -2147,8 +2149,10 @@ override public long GetChars(int i, long dataIndex, char[] buffer, int bufferIn int ndataIndex = (int)dataIndex; // if no buffer is passed in, return the number of characters we have - if (null == buffer) + if (buffer == null) + { return cchars; + } // if dataIndex outside of data range, return 0 if (ndataIndex < 0 || ndataIndex >= cchars) @@ -2252,7 +2256,7 @@ private long GetCharsFromPlpData(int i, long dataIndex, char[] buffer, int buffe } // if no buffer is passed in, return the total number of characters or -1 - if (null == buffer) + if (buffer == null) { cch = (long)_parser.PlpBytesTotalLength(_stateObj); return (isUnicode && (cch > 0)) ? cch >> 1 : cch; @@ -2631,7 +2635,7 @@ virtual public int GetSqlValues(object[] values) { statistics = SqlStatistics.StartTimer(Statistics); CheckDataIsReady(); - if (null == values) + if (values == null) { throw ADP.ArgumentNull(nameof(values)); } @@ -3045,7 +3049,7 @@ override public int GetValues(object[] values) { statistics = SqlStatistics.StartTimer(Statistics); - if (null == values) + if (values == null) { throw ADP.ArgumentNull(nameof(values)); } @@ -3136,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); @@ -3152,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) { @@ -3221,7 +3225,7 @@ private TdsOperationStatus TryHasMoreResults(out bool moreResults) private TdsOperationStatus TryHasMoreRows(out bool moreRows) { - if (null != _parser) + if (_parser != null) { if (_sharedState._dataReady) { @@ -3394,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; @@ -3411,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); @@ -3539,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) { @@ -3766,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; } @@ -4102,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; @@ -4169,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. @@ -4198,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); @@ -4281,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 @@ -4362,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); } @@ -5826,17 +5830,17 @@ public ReadOnlyCollection GetColumnSchema() try { statistics = SqlStatistics.StartTimer(Statistics); - if (null == _metaData || null == _metaData.dbColumnSchema) + 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 2f9e1e8e06..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; @@ -99,7 +99,7 @@ public void Initialize() connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Begin, null, _isolationLevel, _internalTransaction, true); // Handle case where ExecuteTran didn't produce a new transaction, but also didn't throw. - if (null == connection.CurrentTransaction) + if (connection.CurrentTransaction == null) { connection.DoomThisConnection(); throw ADP.InternalError(ADP.InternalErrorCode.UnknownTransactionFailure); @@ -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); @@ -485,7 +485,7 @@ internal void TransactionEnded(Transaction transaction) private SqlInternalConnection GetValidConnection() { SqlInternalConnection connection = _connection; - if (null == connection && Transaction.TransactionInformation.Status != TransactionStatus.Aborted) + if (connection == null && Transaction.TransactionInformation.Status != TransactionStatus.Aborted) { throw ADP.ObjectDisposed(this); } @@ -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 5d6a1d30e0..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 @@ -641,7 +641,7 @@ internal protected override bool IsNonPoolableTransactionRoot { get { - return IsTransactionRoot && (!Is2008OrNewer || null == Pool); + return IsTransactionRoot && (!Is2008OrNewer || Pool == null); } } @@ -689,7 +689,7 @@ protected override bool ReadyToPrepareTransaction { get { - bool result = (null == FindLiveReader(null)); // can't prepare with a live data reader... + bool result = FindLiveReader(null) == null; // can't prepare with a live data reader... return result; } } @@ -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); } @@ -1004,7 +1004,7 @@ internal override void ExecuteTransaction(TransactionRequest transactionRequest, } } - string transactionName = (null == name) ? string.Empty : name; + string transactionName = name == null ? string.Empty : name; ExecuteTransaction2005(transactionRequest, transactionName, iso, internalTransaction, isDelegateControlRequest); } @@ -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); @@ -1591,12 +1591,13 @@ private void LoginNoFailover(ServerInfo serverInfo, continue; } - if (null == _parser - || TdsParserState.Closed != _parser.State - || IsDoNotRetryConnectError(sqlex) - || timeout.IsExpired) - { // no more time to try again - throw; // Caller will call LoginFailure() + if (_parser == null + || TdsParserState.Closed != _parser.State + || IsDoNotRetryConnectError(sqlex) + || timeout.IsExpired) + { + // no more time to try again + throw; // Caller will call LoginFailure() } // Check sleep interval to make sure we won't exceed the timeout @@ -1610,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) { @@ -1644,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 @@ -1710,7 +1711,7 @@ TimeoutTimer timeout ServerInfo failoverServerInfo = new ServerInfo(connectionOptions, failoverHost, connectionOptions.FailoverPartnerSPN); ResolveExtendedServerName(primaryServerInfo, !redirectedUserInstance, connectionOptions); - if (null == ServerProvidedFailOverPartner) + if (ServerProvidedFailOverPartner == null) { ResolveExtendedServerName(failoverServerInfo, !redirectedUserInstance && failoverHost != primaryServerInfo.UserServerName, connectionOptions); } @@ -1759,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); @@ -1844,12 +1845,12 @@ TimeoutTimer timeout _activeDirectoryAuthTimeoutRetryHelper.State = ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn; // if connected to failover host, but said host doesn't have DbMirroring set up, throw an error - if (useFailoverHost && null == ServerProvidedFailOverPartner) + if (useFailoverHost && ServerProvidedFailOverPartner == null) { 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 @@ -2010,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(); } @@ -2894,7 +2895,7 @@ private ServerInfo(SqlConnectionString userOptions, string serverName) { //----------------- // Preconditions - Debug.Assert(null != userOptions); + Debug.Assert(userOptions != null); //----------------- //Method body @@ -2913,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 da0d437927..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 @@ -231,16 +231,16 @@ internal SqlInternalTransaction CurrentTransaction set { Debug.Assert(value == _currentTransaction - || null == _currentTransaction - || null == value - || (null != _currentTransaction && !_currentTransaction.IsLocal), "attempting to change current transaction?"); + || _currentTransaction == null + || value == null + || (_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 ((null == _currentTransaction && null != value) - || (null != _currentTransaction && null == value)) + 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 @@ -508,7 +508,7 @@ internal void Connect( uint result = _physicalStateObj.SniGetConnectionId(ref _connHandler._clientConnectionId); Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); - if (null == _connHandler.pendingSQLDNSObject) + if (_connHandler.pendingSQLDNSObject == null) { // for DNS Caching phase 1 _physicalStateObj.AssignPendingDNSInfo(serverInfo.UserProtocol, FQDNforDNSCache, ref _connHandler.pendingSQLDNSObject); @@ -581,7 +581,7 @@ internal void Connect( Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); SqlClientEventSource.Log.TryTraceEvent(" Sending prelogin handshake"); - if (null == _connHandler.pendingSQLDNSObject) + if (_connHandler.pendingSQLDNSObject == null) { // for DNS Caching phase 1 _physicalStateObj.AssignPendingDNSInfo(serverInfo.UserProtocol, FQDNforDNSCache, ref _connHandler.pendingSQLDNSObject); @@ -1183,9 +1183,9 @@ internal void Deactivate(bool connectionIsDoomed) _sessionPool.Deactivate(); } - Debug.Assert(connectionIsDoomed || null == _pendingTransaction, "pending transaction at disconnect?"); + Debug.Assert(connectionIsDoomed || _pendingTransaction == null, "pending transaction at disconnect?"); - if (!connectionIsDoomed && null != _physicalStateObj) + if (!connectionIsDoomed && _physicalStateObj != null) { if (_physicalStateObj.HasPendingData) { @@ -1208,10 +1208,10 @@ 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(null == CurrentTransaction, "rollback didn't clear current transaction?"); + Debug.Assert(CurrentTransaction == null, "rollback didn't clear current transaction?"); } Statistics = null; // must come after CleanWire or we won't count the stuff that happens there... @@ -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,10 +1313,10 @@ 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(null == CurrentTransaction, "rollback didn't clear current transaction?"); + Debug.Assert(CurrentTransaction == null, "rollback didn't clear current transaction?"); } } @@ -1680,7 +1680,7 @@ internal void CheckResetConnection(TdsParserStateObject stateObj) // internal byte[] SerializeShort(int v, TdsParserStateObject stateObj) { - if (null == stateObj._bShortBytes) + if (stateObj._bShortBytes == null) { stateObj._bShortBytes = new byte[2]; } @@ -1739,7 +1739,7 @@ internal void WriteUnsignedInt(uint i, TdsParserStateObject stateObj) // internal byte[] SerializeInt(int v, TdsParserStateObject stateObj) { - if (null == stateObj._bIntBytes) + if (stateObj._bIntBytes == null) { stateObj._bIntBytes = new byte[sizeof(int)]; } @@ -1812,7 +1812,7 @@ internal void WriteFloat(float v, TdsParserStateObject stateObj) internal byte[] SerializeLong(long v, TdsParserStateObject stateObj) { int current = 0; - if (null == stateObj._bLongBytes) + if (stateObj._bLongBytes == null) { stateObj._bLongBytes = new byte[8]; } @@ -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); @@ -2256,11 +2256,11 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle // the current transaction, then we store the token in it. // if there isn't a pending transaction, then it's either // a TSQL transaction or a distributed transaction. - Debug.Assert(null == _currentTransaction, "non-null current transaction with an ENV Change"); + Debug.Assert(_currentTransaction == null, "non-null current transaction with an ENV Change"); _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); @@ -6235,12 +6235,12 @@ internal bool DeserializeUnencryptedValue(SqlBuffer value, byte[] unencryptedByt { System.Text.Encoding encoding = md.baseTI.encoding; - if (null == encoding) + if (encoding == null) { encoding = _defaultEncoding; } - if (null == encoding) + if (encoding == null) { ThrowUnsupportedCollationEncountered(stateObj); } @@ -7134,7 +7134,7 @@ internal Task WriteSqlVariantValue(object value, int length, int offset, TdsPars internal Task WriteSqlVariantDataRowValue(object value, TdsParserStateObject stateObj, bool canAccumulate = true) { // handle null values - if ((null == value) || (DBNull.Value == value)) + if (value == null || (DBNull.Value == value)) { WriteInt(TdsEnums.FIXEDNULL, stateObj); return null; @@ -7369,7 +7369,7 @@ private byte[] SerializeCurrency(Decimal value, int length, TdsParserStateObject } Debug.Assert(8 == length, "invalid length in SerializeCurrency"); - if (null == stateObj._bLongBytes) + if (stateObj._bLongBytes == null) { stateObj._bLongBytes = new byte[8]; } @@ -7543,7 +7543,7 @@ private TdsOperationStatus TryReadDecimalBits(int length, TdsParserStateObject s bits = stateObj._decimalBits; // used alloc'd array if we have one already int i; - if (null == bits) + if (bits == null) { bits = new int[4]; stateObj._decimalBits = bits; @@ -7601,7 +7601,7 @@ internal static decimal AdjustDecimalScale(decimal value, int newScale) internal byte[] SerializeSqlDecimal(SqlDecimal d, TdsParserStateObject stateObj) { - if (null == stateObj._bDecimalBytes) + if (stateObj._bDecimalBytes == null) { stateObj._bDecimalBytes = new byte[17]; } @@ -7660,7 +7660,7 @@ internal void WriteSqlDecimal(SqlDecimal d, TdsParserStateObject stateObj) private byte[] SerializeDecimal(decimal value, TdsParserStateObject stateObj) { int[] decimalBits = Decimal.GetBits(value); - if (null == stateObj._bDecimalBytes) + if (stateObj._bDecimalBytes == null) { stateObj._bDecimalBytes = new byte[17]; } @@ -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); @@ -7931,7 +7931,7 @@ internal int GetEncodingCharLength(string value, int numChars, int charOffset, E // 7.0 has no support for multiple code pages in data - single code page support only if (encoding == null) { - if (null == _defaultEncoding) + if (_defaultEncoding == null) { ThrowUnsupportedCollationEncountered(null); } @@ -8586,8 +8586,10 @@ private void WriteLoginData(SqlLogin rec, WriteShort(rec.database.Length, _physicalStateObj); offset += rec.database.Length * 2; - if (null == s_nicAddress) + if (s_nicAddress == null) + { s_nicAddress = TdsParserStaticMethods.GetNetworkPhysicalAddressForTdsLoginOnly(); + } _physicalStateObj.WriteByteArray(s_nicAddress, s_nicAddress.Length, 0); @@ -8777,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'"); @@ -8893,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); @@ -8904,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 @@ -9747,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) @@ -10478,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) @@ -10718,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; @@ -10772,7 +10774,7 @@ internal object EncryptColumnValue(object value, SqlMetaDataPriv metadata, strin case TdsEnums.SQLBIGCHAR: case TdsEnums.SQLBIGVARCHAR: case TdsEnums.SQLTEXT: - if (null == _defaultEncoding) + if (_defaultEncoding == null) { ThrowUnsupportedCollationEncountered(null); // stateObject only when reading } @@ -10910,7 +10912,7 @@ internal Task WriteBulkCopyValue(object value, SqlMetaDataPriv metadata, TdsPars case TdsEnums.SQLBIGCHAR: case TdsEnums.SQLBIGVARCHAR: case TdsEnums.SQLTEXT: - if (null == _defaultEncoding) + if (_defaultEncoding == null) { ThrowUnsupportedCollationEncountered(null); // stateObject only when reading } @@ -11046,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); @@ -11070,13 +11067,13 @@ 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; int timeout = notificationRequest.Timeout; - if (null == callbackId) + if (callbackId == null) { throw ADP.ArgumentNull(nameof(callbackId)); } @@ -11085,7 +11082,7 @@ private int GetNotificationHeaderSize(SqlNotificationRequest notificationRequest throw ADP.ArgumentOutOfRange(nameof(callbackId)); } - if (null == service) + if (service == null) { throw ADP.ArgumentNull(nameof(service)); } @@ -11126,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"); @@ -11993,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) @@ -12262,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) { @@ -12376,7 +12373,7 @@ private byte[] SerializeUnencryptedValue(object value, MetaType type, byte scale if (0 > dt.days || dt.days > UInt16.MaxValue) throw SQL.SmallDateTimeOverflow(MetaType.ToDateTime(dt.days, dt.time, 4).ToString(CultureInfo.InvariantCulture)); - if (null == stateObj._bIntBytes) + if (stateObj._bIntBytes == null) { stateObj._bIntBytes = new byte[4]; } @@ -12395,7 +12392,7 @@ private byte[] SerializeUnencryptedValue(object value, MetaType type, byte scale } else { - if (null == stateObj._bLongBytes) + if (stateObj._bLongBytes == null) { stateObj._bLongBytes = new byte[8]; } @@ -12569,7 +12566,7 @@ private byte[] SerializeUnencryptedSqlValue(object value, MetaType type, int act if (0 > dt.DayTicks || dt.DayTicks > UInt16.MaxValue) throw SQL.SmallDateTimeOverflow(dt.ToString()); - if (null == stateObj._bIntBytes) + if (stateObj._bIntBytes == null) { stateObj._bIntBytes = new byte[4]; } @@ -12588,7 +12585,7 @@ private byte[] SerializeUnencryptedSqlValue(object value, MetaType type, int act } else { - if (null == stateObj._bLongBytes) + if (stateObj._bLongBytes == null) { stateObj._bLongBytes = new byte[8]; } @@ -12909,7 +12906,7 @@ internal int ReadPlpAnsiChars(ref char[] buff, int offst, int len, SqlMetaDataPr if (enc == null) { - if (null == _defaultEncoding) + if (_defaultEncoding == null) { ThrowUnsupportedCollationEncountered(stateObj); } @@ -13153,38 +13150,38 @@ internal string TraceString() { return string.Format(/*IFormatProvider*/ null, StateTraceFormatString, - null == _physicalStateObj ? "(null)" : _physicalStateObj.ObjectID.ToString((IFormatProvider)null), - null == _pMarsPhysicalConObj ? "(null)" : _pMarsPhysicalConObj.ObjectID.ToString((IFormatProvider)null), + _physicalStateObj == null ? "(null)" : _physicalStateObj.ObjectID.ToString((IFormatProvider)null), + _pMarsPhysicalConObj == null ? "(null)" : _pMarsPhysicalConObj.ObjectID.ToString((IFormatProvider)null), _state, _server, _fResetConnection ? bool.TrueString : bool.FalseString, - null == _defaultCollation ? "(null)" : _defaultCollation.TraceString(), + _defaultCollation == null ? "(null)" : _defaultCollation.TraceString(), _defaultCodePage, _defaultLCID, TraceObjectClass(_defaultEncoding), _encryptionOption, - null == _currentTransaction ? "(null)" : _currentTransaction.TraceString(), - null == _pendingTransaction ? "(null)" : _pendingTransaction.TraceString(), + _currentTransaction == null ? "(null)" : _currentTransaction.TraceString(), + _pendingTransaction == null ? "(null)" : _pendingTransaction.TraceString(), _retainedTransactionId, _nonTransactedOpenResultCount, - null == _connHandler ? "(null)" : _connHandler.ObjectID.ToString((IFormatProvider)null), + _connHandler == null ? "(null)" : _connHandler.ObjectID.ToString((IFormatProvider)null), _fMARS ? bool.TrueString : bool.FalseString, - null == _sessionPool ? "(null)" : _sessionPool.TraceString(), + _sessionPool == null ? "(null)" : _sessionPool.TraceString(), _is2005 ? bool.TrueString : bool.FalseString, - null == _sniSpnBuffer ? "(null)" : _sniSpnBuffer.Length.ToString((IFormatProvider)null), + _sniSpnBuffer == null ? "(null)" : _sniSpnBuffer.Length.ToString((IFormatProvider)null), _physicalStateObj != null ? "(null)" : _physicalStateObj.ErrorCount.ToString((IFormatProvider)null), _physicalStateObj != null ? "(null)" : _physicalStateObj.WarningCount.ToString((IFormatProvider)null), _physicalStateObj != null ? "(null)" : _physicalStateObj.PreAttentionErrorCount.ToString((IFormatProvider)null), _physicalStateObj != null ? "(null)" : _physicalStateObj.PreAttentionWarningCount.ToString((IFormatProvider)null), - null == _statistics ? bool.TrueString : bool.FalseString, + _statistics == null ? bool.TrueString : bool.FalseString, _statisticsIsInTransaction ? bool.TrueString : bool.FalseString, _fPreserveTransaction ? bool.TrueString : bool.FalseString, - null == _connHandler ? "(null)" : _connHandler.ConnectionOptions.MultiSubnetFailover.ToString((IFormatProvider)null)); + _connHandler == null ? "(null)" : _connHandler.ConnectionOptions.MultiSubnetFailover.ToString((IFormatProvider)null)); } private string TraceObjectClass(object instance) { - if (null == instance) + if (instance == null) { return "(null)"; } 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 d0431e1901..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 @@ -361,7 +361,7 @@ internal _SqlMetaData this[int index] } set { - Debug.Assert(null == value, "used only by SqlBulkCopy"); + Debug.Assert(value == null, "used only by SqlBulkCopy"); _metaDataArray[index] = value; } } @@ -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 e47c3ab456..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,16 +65,16 @@ 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; kv = kvtree.CheckKeyForValue(keychain.Name); - if (null == kv) + if (kv == null) { kv = new NameValuePermission(keychain.Name); kvtree.Add(kv); // add directly into live tree @@ -82,19 +82,19 @@ static internal void AddEntry(NameValuePermission kvtree, ArrayList entries, DBC kvtree = kv; kv = kvtree.CheckKeyForValue(keychain.Value); - if (null == kv) + 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 (null == keychain.Next) + 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); @@ -128,32 +128,32 @@ static internal void AddEntry(NameValuePermission kvtree, ArrayList entries, DBC internal void Intersect(ArrayList entries, NameValuePermission target) { - if (null == target) + if (target == null) { _tree = null; _entry = null; } 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) { @@ -199,13 +199,13 @@ private void Add(NameValuePermission permit) internal bool CheckValueForKeyPermit(DBConnectionString parsetable) { - if (null == parsetable) + if (parsetable == null) { return false; } 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,11 +215,11 @@ 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 - Debug.Assert(null == permitKey._entry, "key member has no restrictions"); + Debug.Assert(permitKey._entry == null, "key member has no restrictions"); #endif if (parsetable.ContainsKey(keyword)) { @@ -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)) @@ -252,11 +252,11 @@ internal bool CheckValueForKeyPermit(DBConnectionString parsetable) // else try next keyword } } - // partial chain match, either leaf-node by shorter chain or fail mid-chain if (null == _restrictions) + // partial chain match, either leaf-node by shorter chain or fail mid-chain if ( _restrictions == null) } 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/AdapterSwitches.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterSwitches.cs index 0563e8a1ef..fdbdf4f270 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterSwitches.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterSwitches.cs @@ -15,7 +15,7 @@ internal static class AdapterSwitches { static internal TraceSwitch DataSchema { get { TraceSwitch dataSchema = _dataSchema; - if (null == dataSchema) { + if (dataSchema == null) { _dataSchema = dataSchema = new TraceSwitch("Data.Schema", "Enable tracing for schema actions."); } return dataSchema; 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 4a2ea20c4d..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: @@ -147,7 +147,7 @@ internal string ConnectionString internal bool IsEmpty { - get { return (null == _keychain); } + get { return _keychain == null; } } internal NameValuePair KeyChain @@ -160,10 +160,10 @@ internal string Restrictions get { string restrictions = _restrictions; - if (null == 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 : ""); } } @@ -202,7 +202,7 @@ internal DBConnectionString Intersect(DBConnectionString entry) KeyRestrictionBehavior behavior = _behavior; string[] restrictionValues = null; - if (null == entry) + if (entry == null) { //Debug.WriteLine("0 entry AllowNothing"); behavior = KeyRestrictionBehavior.AllowOnly; @@ -287,7 +287,7 @@ internal DBConnectionString Intersect(DBConnectionString entry) // verify _hasPassword & _parsetable are in sync between Everett/Whidbey Debug.Assert(!_hasPassword || ContainsKey(KEY.Password) || ContainsKey(KEY.Pwd), "OnDeserialized password mismatch this"); - Debug.Assert(null == entry || !entry._hasPassword || entry.ContainsKey(KEY.Password) || entry.ContainsKey(KEY.Pwd), "OnDeserialized password mismatch entry"); + Debug.Assert(entry == null || !entry._hasPassword || entry.ContainsKey(KEY.Password) || entry.ContainsKey(KEY.Pwd), "OnDeserialized password mismatch entry"); DBConnectionString value = new DBConnectionString(this, restrictionValues, behavior); ValidateCombinedSet(this, value); @@ -367,7 +367,7 @@ private void ValidateCombinedSet(DBConnectionString componentSet, DBConnectionSt private bool IsRestrictedKeyword(string key) { // restricted if not found - return ((null == _restrictionValues) || (0 > Array.BinarySearch(_restrictionValues, key, StringComparer.Ordinal))); + return (_restrictionValues == null || (0 > Array.BinarySearch(_restrictionValues, key, StringComparer.Ordinal))); } internal bool IsSupersetOf(DBConnectionString entry) @@ -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) { @@ -415,7 +415,7 @@ static private string[] NewRestrictionAllowOnly(string[] allowonly, string[] pre { if (0 > Array.BinarySearch(preventusage, allowonly[i], StringComparer.Ordinal)) { - if (null == newlist) + if (newlist == null) { newlist = new List(); } @@ -423,7 +423,7 @@ static private string[] NewRestrictionAllowOnly(string[] allowonly, string[] pre } } string[] restrictionValues = null; - if (null != newlist) + if (newlist != null) { restrictionValues = newlist.ToArray(); } @@ -438,7 +438,7 @@ static private string[] NewRestrictionIntersect(string[] a, string[] b) { if (0 <= Array.BinarySearch(b, a[i], StringComparer.Ordinal)) { - if (null == newlist) + if (newlist == null) { newlist = new List(); } @@ -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 364f256fdc..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])) { @@ -88,11 +88,11 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key ADP.CheckArgumentNull(builder, nameof(builder)); ADP.CheckArgumentLength(keyName, nameof(keyName)); - if ((null == keyName) || !s_connectionStringValidKeyRegex.IsMatch(keyName)) + if (keyName == null || !s_connectionStringValidKeyRegex.IsMatch(keyName)) { 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,16 +165,16 @@ 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; - if (null == rootFolderPath) + if (rootFolderPath == null) { // find the replacement path object rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory"); rootFolderPath = (rootFolderObject as string); - if ((null != rootFolderObject) && (null == rootFolderPath)) + if (rootFolderObject != null && rootFolderPath == null) { throw ADP.InvalidDataDirectory(); } @@ -182,7 +182,7 @@ internal static string ExpandDataDirectory(string keyword, string value, ref str { rootFolderPath = AppDomain.CurrentDomain.BaseDirectory; } - if (null == rootFolderPath) + if (rootFolderPath == null) { rootFolderPath = ""; } 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 8cbf6e0543..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 @@ -29,11 +29,11 @@ internal static class GreenMethods internal static object MicrosoftDataSqlClientSqlProviderServices_Instance() { - if (null == MicrosoftDataSqlClientSqlProviderServices_Instance_FieldInfo) + if (MicrosoftDataSqlClientSqlProviderServices_Instance_FieldInfo == null) { 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 f6dcccacd3..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 @@ -126,11 +126,11 @@ internal static bool NativeSetData(void* passedData, int passedSize) } Trace.Assert(1 == thelock); // Now that we have the lock, lock should be equal to 1. - if (null == data) + if (data == null) { 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/DbConnectionClosed.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs index 99ad6029de..3ec932cdc0 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionClosed.cs @@ -141,7 +141,7 @@ internal override bool TryOpenConnection(DbConnection outerConnection, DbConnect // we are completing an asynchronous open Debug.Assert(retry.Task.Status == TaskStatus.RanToCompletion, "retry task must be completed successfully"); DbConnectionInternal openConnection = retry.Task.Result; - if (null == openConnection) + if (openConnection == null) { connectionFactory.SetInnerConnectionTo(outerConnection, this); throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull); 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 b857323bb1..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; @@ -220,7 +220,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour poolGroup = GetConnectionPoolGroup(owningConnection); // Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread. connectionPool = GetConnectionPool(owningConnection, poolGroup); - if (null == connectionPool) + if (connectionPool == null) { // If GetConnectionPool returns null, we can be certain that // this connection should not be pooled via DbConnectionPool @@ -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,20 +419,20 @@ 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 // new pool entry and add it to our collection. DbConnectionOptions connectionOptions = CreateConnectionOptions(key.ConnectionString, userConnectionOptions); - if (null == connectionOptions) + if (connectionOptions == null) { throw ADP.InternalConnectionError(ADP.ConnectionError.ConnectionOptionsMissing); } string expandedConnectionString = key.ConnectionString; - if (null == userConnectionOptions) + if (userConnectionOptions == null) { // we only allow one expansion on the connection string userConnectionOptions = connectionOptions; @@ -449,9 +449,9 @@ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, D } // We don't support connection pooling on Win9x; it lacks too many of the APIs we require. - if ((null == poolOptions) && ADP.s_isWindowsNT) + 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,10 +489,10 @@ 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 (null == userConnectionOptions) + else if (userConnectionOptions == null) { userConnectionOptions = connectionPoolGroup.ConnectionOptions; } @@ -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 ad218453b4..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 (((null == currentEnlistedTransaction) && (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); @@ -404,10 +404,10 @@ internal void ActivateConnection(Transaction transaction) internal void AddWeakReference(object value, int tag) { - if (null == _referenceCollection) + if (_referenceCollection == null) { _referenceCollection = CreateReferenceCollection(); - if (null == _referenceCollection) + if (_referenceCollection == null) { throw ADP.InternalError(ADP.InternalErrorCode.CreateReferenceCollectionReturnedNull); } @@ -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 @@ -615,7 +615,7 @@ virtual internal void DelegatedTransactionEnded() DbConnectionPool pool = Pool; - if (null == pool) + if (pool == null) { throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool); // pooled connection does not have a pool } @@ -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); } @@ -768,7 +768,7 @@ protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnect connectionFactory.SetInnerConnectionTo(outerConnection, this); throw; } - if (null == openConnection) + if (openConnection == null) { connectionFactory.SetInnerConnectionTo(outerConnection, this); throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull); @@ -790,7 +790,7 @@ internal void PrePush(object expectedOwner) //3 // The following tests are retail assertions of things we can't allow to happen. bool isAlive = _owningObject.TryGetTarget(out DbConnection connection); - if (null == expectedOwner) + if (expectedOwner == null) { if (isAlive) { @@ -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 62fb98df2a..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(); } @@ -850,7 +850,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio try { newObj = _connectionFactory.CreatePooledConnection(this, owningObject, _connectionPoolGroup.ConnectionOptions, _connectionPoolGroup.PoolKey, userOptions); - if (null == newObj) + if (newObj == null) { throw ADP.InternalError(ADP.InternalErrorCode.CreateObjectReturnedNull); // CreateObject succeeded, but null object } @@ -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. @@ -1347,7 +1347,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj obj = GetFromTransactedPool(out transaction); } - if (null == obj) + if (obj == null) { Interlocked.Increment(ref _waitCount); uint waitHandleCount = allowCreate ? 3u : 2u; @@ -1411,7 +1411,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj } catch { - if (null == obj) + if (obj == null) { Interlocked.Decrement(ref _waitCount); } @@ -1421,13 +1421,13 @@ 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); } } - if (null == obj) + if (obj == null) { // If we were not able to create an object, check to see if // we reached MaxPoolSize. If so, we will no longer wait on @@ -1536,15 +1536,15 @@ 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; } - } while (null == obj); + } 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/Server/SmiContextFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContextFactory.cs index d231fe861a..820c9c1bd2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContextFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiContextFactory.cs @@ -40,7 +40,7 @@ private SmiContextFactory() { Type smiLinkType = Type.GetType("Microsoft.SqlServer.Server.InProcLink, SqlAccess, PublicKeyToken=89845dcd8080cc91"); - if (null == smiLinkType) + if (smiLinkType == null) { Debug.Assert(false, "could not get InProcLink type"); throw SQL.ContextUnavailableOutOfProc(); // Must not be a valid version of Sql Server. @@ -95,7 +95,7 @@ internal ulong NegotiatedSmiVersion { get { - if (null == _smiLink) + if (_smiLink == null) { throw SQL.ContextUnavailableOutOfProc(); // Must not be a valid version of Sql Server, or not be SqlCLR } @@ -108,7 +108,7 @@ internal string ServerVersion { get { - if (null == _smiLink) + if (_smiLink == null) { throw SQL.ContextUnavailableOutOfProc(); // Must not be a valid version of Sql Server, or not be SqlCLR } @@ -119,7 +119,7 @@ internal string ServerVersion internal SmiContext GetCurrentContext() { - if (null == _smiLink) + if (_smiLink == null) { throw SQL.ContextUnavailableOutOfProc(); // Must not be a valid version of Sql Server, or not be SqlCLR } @@ -127,7 +127,7 @@ internal SmiContext GetCurrentContext() object result = _smiLink.GetCurrentContext(_eventSinkForGetCurrentContext); _eventSinkForGetCurrentContext.ProcessMessagesAndThrow(); - if (null == result) + if (result == null) { throw SQL.ContextUnavailableWhileInProc(); } 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 bc654f39f7..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 @@ -31,7 +31,7 @@ static SqlAuthenticationProviderManager() { // New configuration section "SqlClientAuthenticationProviders" for Microsoft.Data.SqlClient accepted to avoid conflicts with older one. configurationSection = FetchConfigurationSection(SqlClientAuthenticationProviderConfigurationSection.Name); - if (null == configurationSection) + if (configurationSection == null) { // If configuration section is not yet found, try with old Configuration Section name for backwards compatibility configurationSection = FetchConfigurationSection(SqlAuthenticationProviderConfigurationSection.Name); @@ -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 54b03683b7..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) { @@ -572,7 +572,10 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i } // Throw if there is a transaction but no flag is set - if (isInTransaction && null == _externalTransaction && null == _internalTransaction && (_connection.Parser != null && _connection.Parser.CurrentTransaction != null && _connection.Parser.CurrentTransaction.IsLocal)) + if (isInTransaction && + _externalTransaction == null && + _internalTransaction == null && + (_connection.Parser != null && _connection.Parser.CurrentTransaction != null && _connection.Parser.CurrentTransaction.IsLocal)) { throw SQL.BulkLoadExistingTransaction(); } @@ -720,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; @@ -885,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(); @@ -961,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) { @@ -1319,7 +1322,7 @@ private SourceColumnMetadata GetColumnMetadata(int ordinal) private void CreateOrValidateConnection(string method) { - if (null == _connection) + if (_connection == null) { throw ADP.ConnectionRequired(method); } @@ -1340,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(); } @@ -1383,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 @@ -1808,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; @@ -1863,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 8c497f90d2..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,12 +50,12 @@ 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)); } - if ((null == constr) || constr.IsEmpty) + if (constr == null || constr.IsEmpty) { base.Add("", "", KeyRestrictionBehavior.AllowOnly); } @@ -81,11 +81,11 @@ override public IPermission Copy() internal void AddPermissionEntry(DBConnectionString entry) { - if (null == _keyvaluetree) + if (_keyvaluetree == null) { _keyvaluetree = new NameValuePermission(); } - if (null == _keyvalues) + if (_keyvalues == null) { _keyvalues = new ArrayList(); } @@ -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(); } @@ -129,7 +129,7 @@ private void CopyFrom(SqlClientPermission permission) /// override public IPermission Intersect(IPermission target) { // used during Deny actions - if (null == target) + if (target == null) { return null; } @@ -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(); @@ -175,7 +175,7 @@ override public IPermission Intersect(IPermission target) private bool IsEmpty() { // MDAC 84804 ArrayList keyvalues = _keyvalues; - bool flag = (!IsUnrestricted() && !AllowBlankPassword && ((null == keyvalues) || (0 == keyvalues.Count))); + bool flag = !IsUnrestricted() && !AllowBlankPassword && (keyvalues == null || (0 == keyvalues.Count)); return flag; } @@ -198,11 +198,11 @@ override public bool IsSubsetOf(IPermission target) { if (!IsUnrestricted() && (!AllowBlankPassword || superset.AllowBlankPassword) && - ((null == _keyvalues) || (null != superset._keyvaluetree))) + (_keyvalues == null || superset._keyvaluetree != null)) { subset = true; - if (null != _keyvalues) + if (_keyvalues != null) { foreach (DBConnectionString kventry in _keyvalues) { @@ -221,7 +221,7 @@ override public bool IsSubsetOf(IPermission target) /// override public IPermission Union(IPermission target) { - if (null == target) + if (target == null) { return this.Copy(); } @@ -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(); @@ -285,7 +285,7 @@ private string EncodeXmlValue(string value) override public void FromXml(SecurityElement securityElement) { // code derived from CodeAccessPermission.ValidateElement - if (null == securityElement) + if (securityElement == null) { throw ADP.ArgumentNull("securityElement"); } @@ -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) { @@ -375,8 +375,10 @@ override public SecurityElement ToXml() } tmp = value.Restrictions; tmp = EncodeXmlValue(tmp); - if (null == tmp) - { tmp = ""; } + if (tmp == null) + { + tmp = ""; + } valueElement.AddAttribute(XmlStr._KeyRestrictions, tmp); tmp = value.Behavior.ToString(); 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 d8fdcd1337..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; } @@ -29,7 +29,7 @@ public override bool IsNull { get { - return null == _stream; + return _stream == null; } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCngProvider.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCngProvider.cs index ad84233197..9ea5374c9f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCngProvider.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCngProvider.cs @@ -32,7 +32,7 @@ public override byte[] DecryptColumnEncryptionKey(string masterKeyPath, string e // Validate the input parameters ValidateNonEmptyKeyPath(masterKeyPath, isSystemOp: true); - if (null == encryptedColumnEncryptionKey) + if (encryptedColumnEncryptionKey == null) { throw SQL.NullEncryptedColumnEncryptionKey(); } @@ -126,7 +126,7 @@ public override byte[] EncryptColumnEncryptionKey(string masterKeyPath, string e // Validate the input parameters ValidateNonEmptyKeyPath(masterKeyPath, isSystemOp: false); - if (null == columnEncryptionKey) + if (columnEncryptionKey == null) { throw SQL.NullColumnEncryptionKey(); } @@ -231,7 +231,7 @@ public override bool VerifyColumnMasterKeyMetadata(string masterKeyPath, bool al private void ValidateEncryptionAlgorithm(string encryptionAlgorithm, bool isSystemOp) { // This validates that the encryption algorithm is RSA_OAEP - if (null == encryptionAlgorithm) + if (encryptionAlgorithm == null) { throw SQL.NullKeyEncryptionAlgorithm(isSystemOp); } @@ -251,7 +251,7 @@ private void ValidateNonEmptyKeyPath(string masterKeyPath, bool isSystemOp) { if (string.IsNullOrWhiteSpace(masterKeyPath)) { - if (null == masterKeyPath) + if (masterKeyPath == null) { throw SQL.NullCngKeyPath(isSystemOp); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCspProvider.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCspProvider.cs index 6296d4005d..9489f1b5f4 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCspProvider.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCspProvider.cs @@ -36,7 +36,7 @@ public override byte[] DecryptColumnEncryptionKey(string masterKeyPath, string e // Validate the input parameters ValidateNonEmptyCSPKeyPath(masterKeyPath, isSystemOp: true); - if (null == encryptedColumnEncryptionKey) + if (encryptedColumnEncryptionKey == null) { throw SQL.NullEncryptedColumnEncryptionKey(); } @@ -130,7 +130,7 @@ public override byte[] EncryptColumnEncryptionKey(string masterKeyPath, string e // Validate the input parameters ValidateNonEmptyCSPKeyPath(masterKeyPath, isSystemOp: false); - if (null == columnEncryptionKey) + if (columnEncryptionKey == null) { throw SQL.NullColumnEncryptionKey(); } @@ -235,7 +235,7 @@ public override bool VerifyColumnMasterKeyMetadata(string masterKeyPath, bool al private void ValidateEncryptionAlgorithm(string encryptionAlgorithm, bool isSystemOp) { // This validates that the encryption algorithm is RSA_OAEP - if (null == encryptionAlgorithm) + if (encryptionAlgorithm == null) { throw SQL.NullKeyEncryptionAlgorithm(isSystemOp); } @@ -256,7 +256,7 @@ private void ValidateNonEmptyCSPKeyPath(string masterKeyPath, bool isSystemOp) { if (string.IsNullOrWhiteSpace(masterKeyPath)) { - if (null == masterKeyPath) + if (masterKeyPath == null) { throw SQL.NullCspKeyPath(isSystemOp); } 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 fb1b563e67..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++) { @@ -411,7 +411,7 @@ private CommandEventSink EventSink { get { - if (null == _smiEventSink) + if (_smiEventSink == null) { _smiEventSink = new CommandEventSink(this); } @@ -425,7 +425,7 @@ private SmiEventSink_DeferedProcessing OutParamEventSink { get { - if (null == _outParamEventSink) + if (_outParamEventSink == null) { _outParamEventSink = new SmiEventSink_DeferedProcessing(EventSink); } @@ -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) && (null == _transaction.Connection)) + if (_transaction != null && _transaction.Connection == null) { _transaction = null; } @@ -895,7 +895,7 @@ public override bool DesignTimeVisible { get { - if (null == _parameters) + if (_parameters == null) { // delay the creation of the SqlParameterCollection // until user actually uses the Parameters property @@ -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); } @@ -1230,12 +1230,12 @@ public override void Cancel() // if we have pending data, but it is not a result of this command, then we don't cancel either. Note that // this model is implementable because we only allow one active command at any one time. This code // will have to change we allow multiple outstanding batches - if (null == _activeConnection) + if (_activeConnection == null) { return; } SqlInternalConnectionTds connection = (_activeConnection.InnerConnection as SqlInternalConnectionTds); - if (null == connection) + if (connection == null) { // Fail with out locking return; } @@ -1252,7 +1252,7 @@ public override void Cancel() } TdsParser parser = connection.Parser; - if (null == parser) + if (parser == null) { return; } @@ -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(); } @@ -2004,7 +2004,7 @@ private object InternalEndExecuteNonQuery(IAsyncResult asyncResult, string endMe } } - Debug.Assert(null == _stateObj, "non-null state object in EndExecuteNonQuery"); + Debug.Assert(_stateObj == null, "non-null state object in EndExecuteNonQuery"); return _rowsAffected; } #if DEBUG @@ -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) { @@ -2119,7 +2119,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st } } } - Debug.Assert(async || null == _stateObj, "non-null state object in InternalExecuteNonQuery"); + Debug.Assert(async || _stateObj == null, "non-null state object in InternalExecuteNonQuery"); return task; } #if DEBUG @@ -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(); } @@ -3016,7 +3016,7 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string #endif //DEBUG bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(_activeConnection); SqlDataReader reader = CompleteAsyncExecuteReader(isInternal); - Debug.Assert(null == _stateObj, "non-null state object in InternalEndExecuteReader"); + Debug.Assert(_stateObj == null, "non-null state object in InternalEndExecuteReader"); return reader; } #if DEBUG @@ -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. @@ -3553,7 +3553,7 @@ internal void DeriveParameters() // Use common parser for SqlClient and OleDb - parse into 4 parts - Server, Catalog, Schema, ProcedureName string[] parsedSProc = MultipartIdentifier.ParseMultipartIdentifier(CommandText, "[\"", "]\"", Strings.SQL_SqlCommandCommandText, false); - if (null == parsedSProc[3] || ADP.IsEmpty(parsedSProc[3])) + if (parsedSProc[3] == null || ADP.IsEmpty(parsedSProc[3])) { throw ADP.NoStoredProcedureExists(CommandText); } @@ -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,11 +3873,11 @@ 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) { - if (null == _sqlDep.Options) + if (_sqlDep.Options == null) { // If null, SqlDependency was not created with options, so we need to obtain default options now. // GetDefaultOptions can and will throw under certain conditions. @@ -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(); } @@ -4265,10 +4265,10 @@ private void PrepareForTransparentEncryption(CommandBehavior cmdBehavior, bool r // If we didn't have parameters, we can fall back to regular code path, by simply returning. if (!describeParameterEncryptionNeeded) { - Debug.Assert(null == fetchInputParameterEncryptionInfoTask, + Debug.Assert(fetchInputParameterEncryptionInfoTask == null, "fetchInputParameterEncryptionInfoTask should not be set if describe parameter encryption is not needed."); - Debug.Assert(null == describeParameterEncryptionDataReader, + Debug.Assert(describeParameterEncryptionDataReader == null, "SqlDataReader created for describe parameter encryption params when it is not needed."); return; @@ -4315,7 +4315,7 @@ private void PrepareForTransparentEncryption(CommandBehavior cmdBehavior, bool r // Complete executereader. describeParameterEncryptionDataReader = CompleteAsyncExecuteReader(forDescribeParameterEncryption: true); - Debug.Assert(null == _stateObj, "non-null state object in PrepareForTransparentEncryption."); + Debug.Assert(_stateObj == null, "non-null state object in PrepareForTransparentEncryption."); // Read the results of describe parameter encryption. ReadDescribeEncryptionParameterResults( @@ -4403,7 +4403,7 @@ private void PrepareForTransparentEncryption(CommandBehavior cmdBehavior, bool r // Complete executereader. describeParameterEncryptionDataReader = CompleteAsyncExecuteReader(forDescribeParameterEncryption: true); - Debug.Assert(null == _stateObj, "non-null state object in PrepareForTransparentEncryption."); + Debug.Assert(_stateObj == null, "non-null state object in PrepareForTransparentEncryption."); // Read the results of describe parameter encryption. ReadDescribeEncryptionParameterResults(describeParameterEncryptionDataReader, describeParameterEncryptionRpcOriginalRpcMap, inRetry); @@ -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(); } @@ -5679,7 +5679,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi } } - Debug.Assert(async || null == _stateObj, "non-null state object in RunExecuteReader"); + Debug.Assert(async || _stateObj == null, "non-null state object in RunExecuteReader"); return ds; } @@ -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(); } @@ -5942,7 +5942,7 @@ private Task RegisterForConnectionCloseNotification(Task outterTask) // throws exception for error case, returns false if the commandText is empty private void ValidateCommand(string method, bool async) { - if (null == _activeConnection) + if (_activeConnection == null) { throw ADP.ConnectionRequired(method); } @@ -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,14 +6028,14 @@ 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; } // throw if the connection is in a transaction but there is no // locally assigned transaction object - if (_activeConnection.HasLocalTransactionFromAPI && (null == _transaction)) + if (_activeConnection.HasLocalTransactionFromAPI && _transaction == null) { throw ADP.TransactionRequired(method); } @@ -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(); } @@ -6085,8 +6085,8 @@ private void ValidateAsyncCommand() private void GetStateObject(TdsParser parser = null) { - Debug.Assert(null == _stateObj, "StateObject not null on GetStateObject"); - Debug.Assert(null != _activeConnection, "no active connection?"); + Debug.Assert(_stateObj == null, "StateObject not null on GetStateObject"); + 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; } @@ -6533,7 +6533,7 @@ private SqlParameter GetParameterForOutputValueExtraction(SqlParameterCollection SqlParameter thisParam = null; bool foundParam = false; - if (null == paramName) + if (paramName == null) { // rec.parameter should only be null for a return value from a function for (int i = 0; i < paramCount; i++) @@ -6679,7 +6679,7 @@ private void SetUpRPCParameters(_SqlRPC rpc, bool inSchema, SqlParameterCollecti // MDAC 62117, don't assume a default value exists for parameters in the case when // the user is simply requesting schema // SQLBUVSTS 179488 TVPs use DEFAULT and do not allow NULL, even for schema only. - if (null == parameter.Value && (!inSchema || SqlDbType.Structured == parameter.SqlDbType)) + if (parameter.Value == null && (!inSchema || SqlDbType.Structured == parameter.SqlDbType)) { options |= TdsEnums.RPC_PARAM_DEFAULT; } @@ -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,10 +7143,10 @@ 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 (null == s) + if (s == null) { SqlString sval = val is SqlString ? (SqlString)val : SqlString.Null; if (!sval.IsNull) @@ -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 7492f76dea..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 @@ -499,7 +499,7 @@ public bool StatisticsEnabled // start if (ConnectionState.Open == State) { - if (null == _statistics) + if (_statistics == null) { _statistics = new SqlStatistics(); _statistics._openTimestamp = ADP.TimerCurrent(); @@ -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,8 +1123,8 @@ 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); - if (null == result) + string result = constr != null ? constr.WorkstationId : null; + if (result == null) { // getting machine name requires Environment.Permission // user must have that permission in order to retrieve this @@ -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(); } @@ -1719,7 +1719,7 @@ public void Open(SqlConnectionOverrides overrides) if (StatisticsEnabled) { - if (null == _statistics) + if (_statistics == null) { _statistics = new SqlStatistics(); } @@ -1988,7 +1988,7 @@ private Task InternalOpenAsync(CancellationToken cancellationToken) { if (StatisticsEnabled) { - if (null == _statistics) + if (_statistics == null) { _statistics = new SqlStatistics(); } @@ -2351,7 +2351,7 @@ internal TdsParser Parser get { SqlInternalConnectionTds tdsConnection = (GetOpenConnection() as SqlInternalConnectionTds); - if (null == tdsConnection) + if (tdsConnection == null) { throw SQL.NotAvailableOnContextConnection(); } @@ -2496,7 +2496,7 @@ private void CompleteOpen() internal SqlInternalConnection GetOpenConnection() { SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); - if (null == innerConnection) + if (innerConnection == null) { throw ADP.ClosedConnectionError(); } @@ -2507,7 +2507,7 @@ internal SqlInternalConnection GetOpenConnection(string method) { DbConnectionInternal innerConnection = InnerConnection; SqlInternalConnection innerSqlConnection = (innerConnection as SqlInternalConnection); - if (null == innerSqlConnection) + if (innerSqlConnection == null) { throw ADP.OpenConnectionRequired(method, innerConnection.State); } @@ -2517,7 +2517,7 @@ internal SqlInternalConnection GetOpenConnection(string method) internal SqlInternalConnectionTds GetOpenTdsConnection() { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); - if (null == innerConnection) + if (innerConnection == null) { throw ADP.ClosedConnectionError(); } @@ -2527,7 +2527,7 @@ internal SqlInternalConnectionTds GetOpenTdsConnection() internal SqlInternalConnectionTds GetOpenTdsConnection(string method) { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); - if (null == innerConnection) + if (innerConnection == null) { throw ADP.OpenConnectionRequired(method, InnerConnection.State); } @@ -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(); @@ -3278,20 +3280,26 @@ bool ISQLDebug.SQLDebug(int dwpidDebugger, int dwpidDebuggee, [MarshalAs(Unmanag IntPtr pDacl = IntPtr.Zero; // validate the structure - if (null == pszMachineName || null == pszSDIDLLName) + if (pszMachineName == null || pszSDIDLLName == null) + { return false; + } if (pszMachineName.Length > TdsEnums.SDCI_MAX_MACHINENAME || - pszSDIDLLName.Length > TdsEnums.SDCI_MAX_DLLNAME) + pszSDIDLLName.Length > TdsEnums.SDCI_MAX_DLLNAME) + { return false; + } // note that these are ansi strings Encoding cp = System.Text.Encoding.GetEncoding(TdsEnums.DEFAULT_ENGLISH_CODE_PAGE_VALUE); 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; @@ -3356,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 aca7bfc151..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,8 +92,7 @@ override protected DbConnectionInternal CreateConnection(DbConnectionOptions opt redirectedUserInstance = true; string instanceName; - if ((null == pool) || - (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; @@ -114,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 @@ -123,7 +122,7 @@ override protected DbConnectionInternal CreateConnection(DbConnectionOptions opt } finally { - if (null != sseConnection) + if (sseConnection != null) { sseConnection.Dispose(); } @@ -229,7 +228,7 @@ override internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupPro internal static SqlConnectionString FindSqlConnectionOptions(SqlConnectionPoolKey key) { SqlConnectionString connectionOptions = (SqlConnectionString)SingletonInstance.FindConnectionOptions(key); - if (null == connectionOptions) + if (connectionOptions == null) { connectionOptions = new SqlConnectionString(key.ConnectionString); } @@ -247,9 +246,9 @@ private SqlInternalConnectionSmi GetContextConnection(SqlConnectionString option SqlInternalConnectionSmi result = (SqlInternalConnectionSmi)smiContext.GetContextValue((int)SmiContextFactory.ContextKey.Connection); // context connections are automatically re-useable if they exist unless they've been doomed. - if (null == result || result.IsConnectionDoomed) + 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. } @@ -266,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; } @@ -276,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; } @@ -286,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; } @@ -296,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(); } @@ -305,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; } @@ -314,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); } @@ -323,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); } @@ -333,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 dcbd0738cb..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); - if ((null == connectionOptions) || connectionOptions.IsEmpty) + 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 18eb99bd04..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,9 +486,8 @@ override public object this[string name] internal void Bind(TdsParserStateObject stateObj) { - Debug.Assert(null != stateObj, "null stateobject"); - - Debug.Assert(null == _snapshot, "Should not change during execution of asynchronous command"); + Debug.Assert(stateObj != null, "null stateobject"); + Debug.Assert(_snapshot == null, "Should not change during execution of asynchronous command"); stateObj.Owner = this; _stateObj = stateObj; @@ -500,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; @@ -800,7 +801,7 @@ internal DataTable BuildSchemaTable() internal void Cancel(int objectID) { TdsParserStateObject stateObj = _stateObj; - if (null != stateObj) + if (stateObj != null) { stateObj.Cancel(objectID); } @@ -1140,7 +1141,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) { _isClosed = true; aborting = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -1150,7 +1151,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) { _isClosed = true; aborting = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -1160,7 +1161,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) { _isClosed = true; aborting = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -1219,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) { @@ -1247,7 +1248,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) } catch (System.OutOfMemoryException e) { - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -1255,7 +1256,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) } catch (System.StackOverflowException e) { - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -1263,7 +1264,7 @@ private TdsOperationStatus TryCloseInternal(bool closeReader) } catch (System.Threading.ThreadAbortException e) { - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -1437,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; @@ -1557,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; } @@ -1641,7 +1642,7 @@ override public int GetOrdinal(string name) try { statistics = SqlStatistics.StartTimer(Statistics); - if (null == _fieldNameLookup) + if (_fieldNameLookup == null) { CheckMetaDataIsReady(); _fieldNameLookup = new FieldNameLookup(this, _defaultLCID); @@ -1675,12 +1676,12 @@ override public DataTable GetSchemaTable() try { statistics = SqlStatistics.StartTimer(Statistics); - if (null == _metaData || null == _metaData._schemaTable) + 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; @@ -1904,7 +1905,7 @@ private TdsOperationStatus TryGetBytesInternal(int i, long dataIndex, byte[] buf } // if no buffer is passed in, return the number total of bytes, or -1 - if (null == buffer) + if (buffer == null) { if (_metaData[i].metaType.IsPlp) { @@ -2015,7 +2016,7 @@ private TdsOperationStatus TryGetBytesInternal(int i, long dataIndex, byte[] buf cbytes = data.Length; // if no buffer is passed in, return the number of characters we have - if (null == buffer) + if (buffer == null) { remaining = cbytes; return TdsOperationStatus.Done; @@ -2075,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); } @@ -2084,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); } @@ -2093,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); } @@ -2212,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); } @@ -2221,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); } @@ -2230,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); } @@ -2438,12 +2439,16 @@ override public long GetChars(int i, long dataIndex, char[] buffer, int bufferIn int ndataIndex = (int)dataIndex; // if no buffer is passed in, return the number of characters we have - if (null == buffer) + if (buffer == null) + { return cchars; + } // if dataIndex outside of data range, return 0 if (ndataIndex < 0 || ndataIndex >= cchars) + { return 0; + } try { @@ -2558,7 +2563,7 @@ private long GetCharsFromPlpData(int i, long dataIndex, char[] buffer, int buffe // if no buffer is passed in, return the total number of characters or -1 // TODO: for DBCS encoding it returns number of bytes, not number of chars - if (null == buffer) + if (buffer == null) { cch = (long)_parser.PlpBytesTotalLength(_stateObj); return (isUnicode && (cch > 0)) ? cch >> 1 : cch; @@ -2605,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); } @@ -2614,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); } @@ -2623,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); } @@ -2985,7 +2990,7 @@ virtual public int GetSqlValues(object[] values) { statistics = SqlStatistics.StartTimer(Statistics); CheckDataIsReady(); - if (null == values) + if (values == null) { throw ADP.ArgumentNull("values"); } @@ -3391,7 +3396,7 @@ override public int GetValues(object[] values) { statistics = SqlStatistics.StartTimer(Statistics); - if (null == values) + if (values == null) { throw ADP.ArgumentNull("values"); } @@ -3482,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); @@ -3498,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) { @@ -3573,7 +3578,7 @@ private TdsOperationStatus TryHasMoreResults(out bool moreResults) private TdsOperationStatus TryHasMoreRows(out bool moreRows) { - if (null != _parser) + if (_parser != null) { if (_sharedState._dataReady) { @@ -3786,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; @@ -3803,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); @@ -3899,7 +3904,7 @@ private TdsOperationStatus TryNextResult(out bool more) catch (System.OutOfMemoryException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -3908,7 +3913,7 @@ private TdsOperationStatus TryNextResult(out bool more) catch (System.StackOverflowException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -3917,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); } @@ -3974,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) { @@ -4218,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 @@ -4230,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); } @@ -4239,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); } @@ -4248,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); } @@ -4319,7 +4324,7 @@ private TdsOperationStatus TryReadColumnHeader(int i) catch (System.OutOfMemoryException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -4328,7 +4333,7 @@ private TdsOperationStatus TryReadColumnHeader(int i) catch (System.StackOverflowException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -4337,7 +4342,7 @@ private TdsOperationStatus TryReadColumnHeader(int i) catch (System.Threading.ThreadAbortException e) { _isClosed = true; - if (null != _connection) + if (_connection != null) { _connection.Abort(e); } @@ -4645,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; @@ -4712,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. @@ -4741,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); @@ -4824,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) @@ -4909,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 ffe44e328c..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; @@ -115,7 +115,7 @@ public void Initialize() connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Begin, null, _isolationLevel, _internalTransaction, true); // Handle case where ExecuteTran didn't produce a new transaction, but also didn't throw. - if (null == connection.CurrentTransaction) + if (connection.CurrentTransaction == null) { connection.DoomThisConnection(); throw ADP.InternalError(ADP.InternalErrorCode.UnknownTransactionFailure); @@ -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); @@ -546,7 +546,7 @@ internal void TransactionEnded(Transaction transaction) private SqlInternalConnection GetValidConnection() { SqlInternalConnection connection = _connection; - if (null == connection && _atomicTransaction.TransactionInformation.Status != TransactionStatus.Aborted) + if (connection == null && _atomicTransaction.TransactionInformation.Status != TransactionStatus.Aborted) { throw ADP.ObjectDisposed(this); } @@ -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 88b9aa2430..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); @@ -237,7 +237,7 @@ private Transaction InternalEnlistedTransaction // This works for now only because we can't unenlist from the context transaction Transaction tx = EnlistedTransaction; - if (null == tx) + if (tx == null) { tx = ContextTransaction; } @@ -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. } @@ -282,7 +286,7 @@ internal void AutomaticEnlistment() _currentTransaction = new SqlInternalTransaction(this, TransactionType.Context, null, contextTransactionId); ContextTransaction = contextTransaction; } - else if (null == currentSystemTransaction) + else if (currentSystemTransaction == null) { _currentTransaction = null; // there really isn't a transaction. SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, no transaction.", ObjectID); @@ -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. @@ -535,11 +546,11 @@ private void TransactionStarted(long transactionId, bool isDistributed) // the current transaction, then we store the token in it. // if there isn't a pending transaction, then it's either // a TSQL transaction or a distributed transaction. - Debug.Assert(null == _currentTransaction, "non-null current transaction with an env change"); + Debug.Assert(_currentTransaction == null, "non-null current transaction with an env change"); _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 cc80af6767..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 @@ -738,7 +738,7 @@ override protected internal bool IsNonPoolableTransactionRoot { get { - return IsTransactionRoot && (!Is2008OrNewer || null == Pool); + return IsTransactionRoot && (!Is2008OrNewer || Pool == null); } } @@ -803,7 +803,7 @@ override protected bool ReadyToPrepareTransaction get { // TODO: probably need to use a different method, but that's a different bug - bool result = (null == FindLiveReader(null)); // can't prepare with a live data reader... + bool result = FindLiveReader(null) == null; // can't prepare with a live data reader... return result; } } @@ -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); } @@ -1173,7 +1173,7 @@ override internal void ExecuteTransaction(TransactionRequest transactionRequest, } } - string transactionName = (null == name) ? String.Empty : name; + string transactionName = name == null ? String.Empty : name; if (!_parser.Is2005OrNewer) { @@ -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); @@ -1914,7 +1914,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt continue; } - if (null == _parser + if (_parser == null || TdsParserState.Closed != _parser.State || IsDoNotRetryConnectError(sqlex) || timeout.IsExpired) @@ -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 @@ -2060,7 +2060,7 @@ TimeoutTimer timeout ServerInfo failoverServerInfo = new ServerInfo(connectionOptions, failoverHost, connectionOptions.FailoverPartnerSPN); ResolveExtendedServerName(primaryServerInfo, !redirectedUserInstance, connectionOptions); - if (null == ServerProvidedFailOverPartner) + if (ServerProvidedFailOverPartner == null) {// No point in resolving the failover partner when we're going to override it below // Don't resolve aliases if failover == primary // UNDONE: WHY? Previous code in TdsParser.Connect did this, but the reason is not clear ResolveExtendedServerName(failoverServerInfo, !redirectedUserInstance && failoverHost != primaryServerInfo.UserServerName, connectionOptions); @@ -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); @@ -2233,12 +2233,12 @@ TimeoutTimer timeout _activeDirectoryAuthTimeoutRetryHelper.State = ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn; // if connected to failover host, but said host doesn't have DbMirroring set up, throw an error - if (useFailoverHost && null == ServerProvidedFailOverPartner) + if (useFailoverHost && ServerProvidedFailOverPartner == null) { 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 c6b338d2a0..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 @@ -347,16 +347,16 @@ internal SqlInternalTransaction CurrentTransaction set { Debug.Assert(value == _currentTransaction - || null == _currentTransaction - || null == value - || (null != _currentTransaction && !_currentTransaction.IsLocal), "attempting to change current transaction?"); + || _currentTransaction == null + || value == null + || (_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 ((null == _currentTransaction && null != value) - || (null != _currentTransaction && null == value)) + 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 @@ -1621,9 +1621,9 @@ internal void Deactivate(bool connectionIsDoomed) _sessionPool.Deactivate(); } - Debug.Assert(connectionIsDoomed || null == _pendingTransaction, "pending transaction at disconnect?"); + Debug.Assert(connectionIsDoomed || _pendingTransaction == null, "pending transaction at disconnect?"); - if (!connectionIsDoomed && null != _physicalStateObj) + if (!connectionIsDoomed && _physicalStateObj != null) { if (_physicalStateObj.HasPendingData) { @@ -1646,10 +1646,10 @@ 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(null == CurrentTransaction, "rollback didn't clear current transaction?"); + Debug.Assert(CurrentTransaction == null, "rollback didn't clear current transaction?"); } Statistics = null; // must come after CleanWire or we won't count the stuff that happens there... @@ -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,10 +1746,10 @@ 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(null == CurrentTransaction, "rollback didn't clear current transaction?"); + Debug.Assert(CurrentTransaction == null, "rollback didn't clear current transaction?"); } } @@ -2087,7 +2087,7 @@ internal void CheckResetConnection(TdsParserStateObject stateObj) // internal byte[] SerializeShort(int v, TdsParserStateObject stateObj) { - if (null == stateObj._bShortBytes) + if (stateObj._bShortBytes == null) { stateObj._bShortBytes = new byte[2]; } @@ -2145,7 +2145,7 @@ internal void WriteUnsignedInt(uint i, TdsParserStateObject stateObj) // internal byte[] SerializeInt(int v, TdsParserStateObject stateObj) { - if (null == stateObj._bIntBytes) + if (stateObj._bIntBytes == null) { stateObj._bIntBytes = new byte[4]; } @@ -2213,7 +2213,7 @@ internal void WriteFloat(float v, TdsParserStateObject stateObj) internal byte[] SerializeLong(long v, TdsParserStateObject stateObj) { int current = 0; - if (null == stateObj._bLongBytes) + if (stateObj._bLongBytes == null) { stateObj._bLongBytes = new byte[8]; } @@ -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); @@ -2702,11 +2702,11 @@ internal TdsOperationStatus TryRun(RunBehavior runBehavior, SqlCommand cmdHandle // the current transaction, then we store the token in it. // if there isn't a pending transaction, then it's either // a TSQL transaction or a distributed transaction. - Debug.Assert(null == _currentTransaction, "non-null current transaction with an ENV Change"); + Debug.Assert(_currentTransaction == null, "non-null current transaction with an ENV Change"); _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); @@ -7065,12 +7065,12 @@ internal bool DeserializeUnencryptedValue(SqlBuffer value, byte[] unencryptedByt { System.Text.Encoding encoding = md.baseTI.encoding; - if (null == encoding) + if (encoding == null) { encoding = _defaultEncoding; } - if (null == encoding) + if (encoding == null) { ThrowUnsupportedCollationEncountered(stateObj); } @@ -7971,7 +7971,7 @@ internal Task WriteSqlVariantDataRowValue(object value, TdsParserStateObject sta Debug.Assert(_is2000 == true, "Shouldn't be dealing with sql_variant in pre-SQL2000 server!"); // handle null values - if ((null == value) || (DBNull.Value == value)) + if (value == null || (DBNull.Value == value)) { WriteInt(TdsEnums.FIXEDNULL, stateObj); return null; @@ -8206,7 +8206,7 @@ private byte[] SerializeCurrency(Decimal value, int length, TdsParserStateObject } Debug.Assert(8 == length, "invalid length in SerializeCurrency"); - if (null == stateObj._bLongBytes) + if (stateObj._bLongBytes == null) { stateObj._bLongBytes = new byte[8]; } @@ -8381,8 +8381,10 @@ private TdsOperationStatus TryReadDecimalBits(int length, TdsParserStateObject s bits = stateObj._decimalBits; // used alloc'd array if we have one already int i; - if (null == bits) + if (bits == null) + { bits = new int[4]; + } else { for (i = 0; i < bits.Length; i++) @@ -8437,7 +8439,7 @@ static internal decimal AdjustDecimalScale(decimal value, int newScale) internal byte[] SerializeSqlDecimal(SqlDecimal d, TdsParserStateObject stateObj) { - if (null == stateObj._bDecimalBytes) + if (stateObj._bDecimalBytes == null) { stateObj._bDecimalBytes = new byte[17]; } @@ -8487,7 +8489,7 @@ internal void WriteSqlDecimal(SqlDecimal d, TdsParserStateObject stateObj) private byte[] SerializeDecimal(decimal value, TdsParserStateObject stateObj) { int[] decimalBits = Decimal.GetBits(value); - if (null == stateObj._bDecimalBytes) + if (stateObj._bDecimalBytes == null) { stateObj._bDecimalBytes = new byte[17]; } @@ -8538,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 @@ -8573,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); @@ -8586,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); @@ -8747,7 +8749,7 @@ internal int GetEncodingCharLength(string value, int numChars, int charOffset, E // 7.0 has no support for multiple code pages in data - single code page support only if (encoding == null) { - if (null == _defaultEncoding) + if (_defaultEncoding == null) { ThrowUnsupportedCollationEncountered(null); } @@ -9428,8 +9430,10 @@ private void WriteLoginData(SqlLogin rec, // UNDONE: NIC address // previously we declared the array and simply sent it over - byte[] of 0's - if (null == s_nicAddress) + if (s_nicAddress == null) + { s_nicAddress = TdsParserStaticMethods.GetNetworkPhysicalAddressForTdsLoginOnly(); + } _physicalStateObj.WriteByteArray(s_nicAddress, s_nicAddress.Length, 0); @@ -9635,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'"); @@ -9755,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); @@ -9767,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 @@ -10498,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 @@ -11396,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) @@ -11648,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; @@ -11701,7 +11705,7 @@ internal object EncryptColumnValue(object value, SqlMetaDataPriv metadata, strin case TdsEnums.SQLBIGCHAR: case TdsEnums.SQLBIGVARCHAR: case TdsEnums.SQLTEXT: - if (null == _defaultEncoding) + if (_defaultEncoding == null) { ThrowUnsupportedCollationEncountered(null); // stateObject only when reading } @@ -11839,7 +11843,7 @@ internal Task WriteBulkCopyValue(object value, SqlMetaDataPriv metadata, TdsPars case TdsEnums.SQLBIGCHAR: case TdsEnums.SQLBIGVARCHAR: case TdsEnums.SQLTEXT: - if (null == _defaultEncoding) + if (_defaultEncoding == null) { ThrowUnsupportedCollationEncountered(null); // stateObject only when reading } @@ -11977,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); @@ -12001,13 +12000,13 @@ 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; int timeout = notificationRequest.Timeout; - if (null == callbackId) + if (callbackId == null) { throw ADP.ArgumentNull("CallbackId"); } @@ -12016,7 +12015,7 @@ private int GetNotificationHeaderSize(SqlNotificationRequest notificationRequest throw ADP.ArgumentOutOfRange("CallbackId"); } - if (null == service) + if (service == null) { throw ADP.ArgumentNull("Service"); } @@ -12057,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"); @@ -12983,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) @@ -13254,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) { @@ -13366,9 +13365,11 @@ private byte[] SerializeUnencryptedValue(object value, MetaType type, byte scale if (type.FixedLength == 4) { if (0 > dt.days || dt.days > UInt16.MaxValue) + { throw SQL.SmallDateTimeOverflow(MetaType.ToDateTime(dt.days, dt.time, 4).ToString(CultureInfo.InvariantCulture)); + } - if (null == stateObj._bIntBytes) + if (stateObj._bIntBytes == null) { stateObj._bIntBytes = new byte[4]; } @@ -13387,7 +13388,7 @@ private byte[] SerializeUnencryptedValue(object value, MetaType type, byte scale } else { - if (null == stateObj._bLongBytes) + if (stateObj._bLongBytes == null) { stateObj._bLongBytes = new byte[8]; } @@ -13562,7 +13563,7 @@ private byte[] SerializeUnencryptedSqlValue(object value, MetaType type, int act if (0 > dt.DayTicks || dt.DayTicks > UInt16.MaxValue) throw SQL.SmallDateTimeOverflow(dt.ToString()); - if (null == stateObj._bIntBytes) + if (stateObj._bIntBytes == null) { stateObj._bIntBytes = new byte[4]; } @@ -13581,7 +13582,7 @@ private byte[] SerializeUnencryptedSqlValue(object value, MetaType type, int act } else { - if (null == stateObj._bLongBytes) + if (stateObj._bLongBytes == null) { stateObj._bLongBytes = new byte[8]; } @@ -13876,10 +13877,9 @@ internal int ReadPlpAnsiChars(ref char[] buff, int offst, int len, SqlMetaDataPr if (enc == null) { - if (null == _defaultEncoding) + if (_defaultEncoding == null) { ThrowUnsupportedCollationEncountered(stateObj); - } enc = _defaultEncoding; @@ -14043,36 +14043,36 @@ internal string TraceString() { return string.Format(/*IFormatProvider*/ null, StateTraceFormatString, - null == _physicalStateObj ? "(null)" : _physicalStateObj.ObjectID.ToString((IFormatProvider)null), - null == _pMarsPhysicalConObj ? "(null)" : _pMarsPhysicalConObj.ObjectID.ToString((IFormatProvider)null), + _physicalStateObj == null ? "(null)" : _physicalStateObj.ObjectID.ToString((IFormatProvider)null), + _pMarsPhysicalConObj == null ? "(null)" : _pMarsPhysicalConObj.ObjectID.ToString((IFormatProvider)null), _state, _server, _fResetConnection ? bool.TrueString : bool.FalseString, - null == _defaultCollation ? "(null)" : _defaultCollation.TraceString(), + _defaultCollation == null ? "(null)" : _defaultCollation.TraceString(), _defaultCodePage, _defaultLCID, TraceObjectClass(_defaultEncoding), _encryptionOption, - null == _currentTransaction ? "(null)" : _currentTransaction.TraceString(), - null == _pendingTransaction ? "(null)" : _pendingTransaction.TraceString(), + _currentTransaction == null ? "(null)" : _currentTransaction.TraceString(), + _pendingTransaction == null ? "(null)" : _pendingTransaction.TraceString(), _retainedTransactionId, _nonTransactedOpenResultCount, - null == _connHandler ? "(null)" : _connHandler.ObjectID.ToString((IFormatProvider)null), + _connHandler == null ? "(null)" : _connHandler.ObjectID.ToString((IFormatProvider)null), _fMARS ? bool.TrueString : bool.FalseString, - null == _sessionPool ? "(null)" : _sessionPool.TraceString(), + _sessionPool == null ? "(null)" : _sessionPool.TraceString(), _is2000 ? bool.TrueString : bool.FalseString, _is2000SP1 ? bool.TrueString : bool.FalseString, _is2005 ? bool.TrueString : bool.FalseString, - null == _sniSpnBuffer ? "(null)" : _sniSpnBuffer.Length.ToString((IFormatProvider)null), + _sniSpnBuffer == null ? "(null)" : _sniSpnBuffer.Length.ToString((IFormatProvider)null), _physicalStateObj != null ? "(null)" : _physicalStateObj.ErrorCount.ToString((IFormatProvider)null), _physicalStateObj != null ? "(null)" : _physicalStateObj.WarningCount.ToString((IFormatProvider)null), _physicalStateObj != null ? "(null)" : _physicalStateObj.PreAttentionErrorCount.ToString((IFormatProvider)null), _physicalStateObj != null ? "(null)" : _physicalStateObj.PreAttentionWarningCount.ToString((IFormatProvider)null), - null == _statistics ? bool.TrueString : bool.FalseString, + _statistics == null ? bool.TrueString : bool.FalseString, _statisticsIsInTransaction ? bool.TrueString : bool.FalseString, _fPreserveTransaction ? bool.TrueString : bool.FalseString, - null == _connHandler ? "(null)" : _connHandler.ConnectionOptions.MultiSubnetFailover.ToString((IFormatProvider)null), - null == _connHandler ? "(null)" : _connHandler.ConnectionOptions.TransparentNetworkIPResolution.ToString((IFormatProvider)null)); + _connHandler == null ? "(null)" : _connHandler.ConnectionOptions.MultiSubnetFailover.ToString((IFormatProvider)null), + _connHandler == null ? "(null)" : _connHandler.ConnectionOptions.TransparentNetworkIPResolution.ToString((IFormatProvider)null)); } private string TraceObjectClass(object instance) 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 079787506a..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 @@ -579,7 +579,7 @@ internal _SqlMetaData this[int index] } set { - Debug.Assert(null == value, "used only by SqlBulkCopy"); + Debug.Assert(value == null, "used only by SqlBulkCopy"); _metaDataArray[index] = value; } } @@ -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 95a54538f9..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 @@ -570,7 +578,7 @@ internal static string AuthenticationTypeToString(SqlAuthenticationMethod value) internal static SqlAuthenticationMethod ConvertToAuthenticationType(string keyword, object value) { - if (null == value) + if (value == null) { return DbConnectionStringDefaults.Authentication; } @@ -644,7 +652,7 @@ internal static SqlAuthenticationMethod ConvertToAuthenticationType(string keywo /// internal static SqlConnectionColumnEncryptionSetting ConvertToColumnEncryptionSetting(string keyword, object value) { - if (null == value) + if (value == null) { return DbConnectionStringDefaults.ColumnEncryptionSetting; } @@ -765,7 +773,7 @@ internal static string AttestationProtocolToString(SqlConnectionAttestationProto internal static SqlConnectionAttestationProtocol ConvertToAttestationProtocol(string keyword, object value) { - if (null == value) + if (value == null) { return DbConnectionStringDefaults.AttestationProtocol; } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/MultipartIdentifier.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/MultipartIdentifier.cs index a30b462092..b89a080e99 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/MultipartIdentifier.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Common/MultipartIdentifier.cs @@ -145,7 +145,7 @@ internal static string[] ParseMultipartIdentifier(string name, string leftQuote, if (IsWhitespace(testchar)) { // If it is Whitespace parsedNames[stringCount] = sb.ToString(); // Set the currently parsed string - if (null == whitespaceSB) + if (whitespaceSB == null) { whitespaceSB = new StringBuilder(); } 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 f0cfc71d53..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) || (null == value)) + 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 7568340594..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,9 +51,9 @@ 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(null == poolGroupOptions || ADP.s_isWindowsNT, "should not have pooling options on Win9x"); + Debug.Assert(poolGroupOptions == null || ADP.s_isWindowsNT, "should not have pooling options on Win9x"); #endif _connectionOptions = connectionOptions; @@ -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 { @@ -224,7 +224,7 @@ internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactor } } - if (null == pool) + if (pool == null) { lock (this) { diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs index c3c34c702b..12b572bb47 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs @@ -237,7 +237,7 @@ internal DataRow FindMetaDataCollectionRow(string collectionName) DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]; - if ((null == collectionNameColumn) || (typeof(string) != collectionNameColumn.DataType)) + if (collectionNameColumn == null || (typeof(string) != collectionNameColumn.DataType)) { throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName); } 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 726410f741..276efb441e 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationProvider.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationProvider.cs @@ -218,7 +218,7 @@ public override async Task AcquireTokenAsync(SqlAuthenti { result = await TryAcquireTokenSilent(app, parameters, scopes, cts).ConfigureAwait(false); - if (null == result) + if (result == null) { if (!string.IsNullOrEmpty(parameters.UserId)) { @@ -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)) @@ -252,7 +252,7 @@ previousPw is byte[] previousPwBytes && result = await TryAcquireTokenSilent(app, parameters, scopes, cts).ConfigureAwait(false); } - if (null == result) + if (result == null) { result = await app.AcquireTokenByUsernamePassword(scopes, parameters.UserId, parameters.Password) .WithCorrelationId(parameters.ConnectionId) @@ -288,7 +288,7 @@ previousPw is byte[] previousPwBytes && SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (interactive) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result?.ExpiresOn); } - if (null == result) + if (result == null) { // If no existing 'account' is found, we request user to sign in interactively. result = await AcquireTokenInteractiveDeviceFlowAsync(app, scopes, parameters.ConnectionId, parameters.UserId, parameters.AuthenticationMethod, cts, _customWebUI, _deviceCodeFlowCallback).ConfigureAwait(false); @@ -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/ColumnEncryptionKeyInfo.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ColumnEncryptionKeyInfo.cs index 1b1dbceba0..a56dc2ac47 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ColumnEncryptionKeyInfo.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ColumnEncryptionKeyInfo.cs @@ -35,14 +35,22 @@ internal class ColumnEncryptionKeyInfo internal ColumnEncryptionKeyInfo(byte[] decryptedKey, int databaseId, byte[] keyMetadataVersion, int keyid) { - if (null == decryptedKey) + if (decryptedKey == null) + { throw SQL.NullArgumentInConstructorInternal(_decryptedKeyName, _className); + } if (0 == decryptedKey.Length) + { throw SQL.EmptyArgumentInConstructorInternal(_decryptedKeyName, _className); - if (null == keyMetadataVersion) + } + if (keyMetadataVersion == null) + { throw SQL.NullArgumentInConstructorInternal(_keyMetadataVersionName, _className); + } if (0 == keyMetadataVersion.Length) + { throw SQL.EmptyArgumentInConstructorInternal(_keyMetadataVersionName, _className); + } KeyId = keyid; DatabaseId = databaseId; 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 d3c01546ce..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 @@ -199,7 +199,7 @@ Type udtType ExtendedClrTypeCode extendedCode = ExtendedClrTypeCode.Invalid; // fast-track null, which is valid for all types - if (null == value) + if (value == null) { extendedCode = ExtendedClrTypeCode.Empty; } @@ -343,7 +343,7 @@ Type udtType break; case SqlDbType.Udt: // Validate UDT type if caller gave us a type to validate against - if (null == udtType || value.GetType() == udtType) + if (udtType == null || value.GetType() == udtType) { extendedCode = ExtendedClrTypeCode.Object; } @@ -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 39f87beaae..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. @@ -118,7 +118,7 @@ protected SqlException ProcessMessages(bool ignoreWarnings } else { - Debug.Assert(null == _warnings || 0 != _warnings.Count, "empty warning collection?");// must be something in the collection + Debug.Assert(_warnings == null || 0 != _warnings.Count, "empty warning collection?");// must be something in the collection if (!ignoreWarnings) { @@ -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 75d61f09ff..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 @@ -13,7 +13,7 @@ private SqlErrorCollection Errors { get { - if (null == _errors) + if (_errors == null) { _errors = new SqlErrorCollection(); } @@ -32,7 +32,7 @@ private SqlErrorCollection Warnings { get { - if (null == _warnings) + if (_warnings == null) { _warnings = new SqlErrorCollection(); } @@ -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(); } @@ -98,7 +98,7 @@ internal SmiEventSink_Default(SmiEventSink parent) // internal override void BatchCompleted() { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.BatchCompleted); } @@ -107,7 +107,7 @@ internal override void BatchCompleted() internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 paramValues) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.ParametersAvailable); } @@ -116,7 +116,7 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter paramValue, int ordinal) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.ParameterAvailable); } @@ -126,7 +126,7 @@ internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiType // Called when the server database context changes (ENVCHANGE token) internal override void DefaultDatabaseChanged(string databaseName) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.DefaultDatabaseChanged); } @@ -136,7 +136,7 @@ internal override void DefaultDatabaseChanged(string databaseName) // Called for messages and errors (ERROR and INFO tokens) internal override void MessagePosted(int number, byte state, byte errorClass, string server, string message, string procedure, int lineNumber) { - if (null == _parent) + if (_parent == null) { SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, number={1} state={2} errorClass={3} server='{4}' message='{5}' procedure='{6}' linenumber={7}.", 0, number, state, errorClass, server, message, procedure, lineNumber); SqlError error = new SqlError(number, state, errorClass, server, message, procedure, lineNumber); @@ -159,7 +159,7 @@ internal override void MessagePosted(int number, byte state, byte errorClass, st // Called for new resultset starting (COLMETADATA token) internal override void MetaDataAvailable(SmiQueryMetaData[] metaData, bool nextEventIsRow) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.MetaDataAvailable); } @@ -169,7 +169,7 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] metaData, bool nextE // Called when a new row arrives (ROW token) internal override void RowAvailable(ITypedGetters rowData) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.RowAvailable); } @@ -179,7 +179,7 @@ internal override void RowAvailable(ITypedGetters rowData) // Called when a new row arrives (ROW token) internal override void RowAvailable(ITypedGettersV3 rowData) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.RowAvailable); } @@ -189,7 +189,7 @@ internal override void RowAvailable(ITypedGettersV3 rowData) // Called when any statement completes on server (DONE token) internal override void StatementCompleted(int rowsAffected) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.StatementCompleted); } @@ -199,7 +199,7 @@ internal override void StatementCompleted(int rowsAffected) // Called when a transaction is committed (ENVCHANGE token) internal override void TransactionCommitted(long transactionId) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.TransactionCommitted); } @@ -209,7 +209,7 @@ internal override void TransactionCommitted(long transactionId) // Called when a transaction is committed (ENVCHANGE token) internal override void TransactionDefected(long transactionId) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.TransactionDefected); } @@ -219,7 +219,7 @@ internal override void TransactionDefected(long transactionId) // Called when a transaction is committed (ENVCHANGE token) internal override void TransactionEnlisted(long transactionId) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.TransactionEnlisted); } @@ -230,7 +230,7 @@ internal override void TransactionEnlisted(long transactionId) // by the provider's batch (ENVCHANGE token) internal override void TransactionEnded(long transactionId) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.TransactionEnded); } @@ -240,7 +240,7 @@ internal override void TransactionEnded(long transactionId) // Called when a transaction is rolled back (ENVCHANGE token) internal override void TransactionRolledBack(long transactionId) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.TransactionRolledBack); } @@ -250,7 +250,7 @@ internal override void TransactionRolledBack(long transactionId) // Called when a transaction is started (ENVCHANGE token) internal override void TransactionStarted(long transactionId) { - if (null == _parent) + if (_parent == null) { throw SQL.UnexpectedSmiEvent(UnexpectedEventType.TransactionStarted); } 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/SmiMetaData.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiMetaData.cs index d69ab6448c..a3945a42e8 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiMetaData.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SmiMetaData.cs @@ -493,7 +493,7 @@ internal Type Type get { // Fault-in UDT clr types on access if have assembly-qualified name - if (null == _clrType && SqlDbType.Udt == _databaseType && _udtAssemblyQualifiedName != null) + if (_clrType == null && SqlDbType.Udt == _databaseType && _udtAssemblyQualifiedName != null) { _clrType = Type.GetType(_udtAssemblyQualifiedName, true); } @@ -507,7 +507,7 @@ internal Type TypeWithoutThrowing get { // Fault-in UDT clr types on access if have assembly-qualified name - if (null == _clrType && SqlDbType.Udt == _databaseType && _udtAssemblyQualifiedName != null) + if (_clrType == null && SqlDbType.Udt == _databaseType && _udtAssemblyQualifiedName != null) { _clrType = Type.GetType(_udtAssemblyQualifiedName, false); } @@ -872,7 +872,7 @@ string typeSpecificNamePart3 extendedProperties ) { - Debug.Assert(null == name || MaxNameLength >= name.Length, "Name is too long"); + Debug.Assert(name == null || MaxNameLength >= name.Length, "Name is too long"); _name = name; _typeSpecificNamePart1 = typeSpecificNamePart1; 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/SqlDataRecord.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlDataRecord.cs index 0afb0f7b7a..5e150a9ea4 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlDataRecord.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Server/SqlDataRecord.cs @@ -183,7 +183,7 @@ public virtual SqlMetaData GetSqlMetaData(int ordinal) /// public virtual int GetSqlValues(object[] values) { - if (null == values) + if (values == null) { throw ADP.ArgumentNull(nameof(values)); } 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 9cc490f0ce..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 @@ -913,7 +913,7 @@ int sortOrdinal throw SQL.InvalidSqlDbTypeForConstructor(dbType); } - if (null == userDefinedType) + if (userDefinedType == null) { throw ADP.ArgumentNull(nameof(userDefinedType)); } @@ -952,9 +952,9 @@ int sortOrdinal throw SQL.InvalidSqlDbTypeForConstructor(dbType); } - if (null != database || null != owningSchema) + if (database != null || owningSchema != null) { - if (null == objectName) + if (objectName == null) { throw ADP.ArgumentNull(nameof(objectName)); } @@ -974,7 +974,7 @@ int sortOrdinal private void AssertNameIsValid(string name) { - if (null == name) + if (name == null) { throw ADP.ArgumentNull(nameof(name)); } @@ -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) @@ -1078,7 +1078,7 @@ public string Adjust(string value) } // Handle null values after type check - if (null == value) + if (value == null) { return null; } @@ -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; @@ -1389,7 +1389,7 @@ public SqlChars Adjust(SqlChars value) } // Handle null values after type check. - if (null == value || value.IsNull) + if (value == null || value.IsNull) { return value; } @@ -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; @@ -1438,7 +1438,7 @@ public SqlBytes Adjust(SqlBytes value) } // Handle null values after type check. - if (null == value || value.IsNull) + if (value == null || value.IsNull) { return value; } @@ -1487,7 +1487,7 @@ public DateTimeOffset Adjust(DateTimeOffset value) public object Adjust(object value) { // Pass null references through - if (null == value) + if (value == null) { return null; } @@ -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) @@ -1961,7 +1961,7 @@ public byte[] Adjust(byte[] value) } // Handle null values after type check - if (null == value) + if (value == null) { return null; } @@ -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; @@ -2032,7 +2032,7 @@ public char[] Adjust(char[] value) } // Handle null values after type check - if (null == value) + if (value == null) { return null; } 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 53bcedf146..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 @@ -120,7 +120,7 @@ internal static TimeSpan GetTimeSpan(SmiEventSink_Default sink, ITypedGettersV3 } ThrowIfITypedGettersIsNull(sink, getters, ordinal); object obj = GetValue(sink, getters, ordinal, metaData); - if (null == obj) + if (obj == null) { throw ADP.InvalidCast(); } @@ -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/SignatureVerificationCache.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SignatureVerificationCache.cs index e54e88f23e..40d4ed9b79 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SignatureVerificationCache.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SignatureVerificationCache.cs @@ -87,7 +87,7 @@ private void ValidateSignatureNotNullOrEmpty(byte[] signature, string methodName { if (signature == null || signature.Length == 0) { - if (null == signature) + if (signature == null) { throw SQL.NullArgumentInternal(_signatureName, _className, methodName); } @@ -102,7 +102,7 @@ private void ValidateStringArgumentNotNullOrEmpty(string stringArgValue, string { if (string.IsNullOrWhiteSpace(stringArgValue)) { - if (null == stringArgValue) + if (stringArgValue == null) { throw SQL.NullArgumentInternal(stringArgName, _className, methodName); } 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/SqlColumnEncryptionCertificateStoreProvider.Windows.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCertificateStoreProvider.Windows.cs index f850259311..b2dad9ed0f 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCertificateStoreProvider.Windows.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCertificateStoreProvider.Windows.cs @@ -57,7 +57,7 @@ public override byte[] DecryptColumnEncryptionKey(string masterKeyPath, string e // Validate the input parameters ValidateNonEmptyCertificatePath(masterKeyPath, isSystemOp: true); - if (null == encryptedColumnEncryptionKey) + if (encryptedColumnEncryptionKey == null) { throw SQL.NullEncryptedColumnEncryptionKey(); } @@ -152,7 +152,7 @@ public override byte[] EncryptColumnEncryptionKey(string masterKeyPath, string e { // Validate the input parameters ValidateNonEmptyCertificatePath(masterKeyPath, isSystemOp: false); - if (null == columnEncryptionKey) + if (columnEncryptionKey == null) { throw SQL.NullColumnEncryptionKey(); } @@ -295,7 +295,7 @@ private byte[] ComputeMasterKeyMetadataHash(string masterKeyPath, bool allowEncl private void ValidateEncryptionAlgorithm(string encryptionAlgorithm, bool isSystemOp) { // This validates that the encryption algorithm is RSA_OAEP - if (null == encryptionAlgorithm) + if (encryptionAlgorithm == null) { throw SQL.NullKeyEncryptionAlgorithm(isSystemOp); } @@ -334,7 +334,7 @@ private void ValidateNonEmptyCertificatePath(string masterKeyPath, bool isSystem { if (string.IsNullOrWhiteSpace(masterKeyPath)) { - if (null == masterKeyPath) + if (masterKeyPath == null) { throw SQL.NullCertificatePath(GetValidCertificateLocations(), isSystemOp); } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandBuilder.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandBuilder.cs index e256dde95c..0f57a0e74f 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandBuilder.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandBuilder.cs @@ -250,7 +250,7 @@ public static void DeriveParameters(SqlCommand command) #if NETFRAMEWORK SqlConnection.ExecutePermission.Demand(); #endif - if (null == command) + if (command == null) { throw ADP.ArgumentNull(nameof(command)); } 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 fd7dd61e59..d82bd6f9c1 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -35,7 +35,7 @@ private SqlCommand BatchCommand get { SqlCommand command = _batchCommand; - if (null == command) + if (command == null) { throw ADP.ObjectDisposed(this); } @@ -50,7 +50,7 @@ private List CommandList get { List commandList = _commandList; - if (null == commandList) + if (commandList == null) { throw ADP.ObjectDisposed(this); } @@ -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 238885b368..47de649bbd 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs @@ -39,7 +39,7 @@ internal void AliasCheck(string server) { lock (this) { - if (null == _alias) + if (_alias == null) { _alias = server; } @@ -105,7 +105,7 @@ private PermissionSet CreateFailoverPermission(SqlConnectionString userConnectio // in the original connection string. if (userConnectionOptions.ContainsKey(SqlConnectionString.KEY.FailoverPartner) && - null == userConnectionOptions[SqlConnectionString.KEY.FailoverPartner]) + userConnectionOptions[SqlConnectionString.KEY.FailoverPartner] == null) { keywordToReplace = SqlConnectionString.KEY.Data_Source; } @@ -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 243efb3db1..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) && (null == _localDBInstance); + return _expandedAttachDBFilename != null && _localDBInstance == null; } } protected internal override string Expand() { - if (null != _expandedAttachDBFilename) + if (_expandedAttachDBFilename != null) { #if NETFRAMEWORK return ExpandKeyword(KEY.AttachDBFilename, _expandedAttachDBFilename); @@ -831,7 +831,7 @@ private static bool CompareHostName(ref string host, string name, bool fixup) internal static Dictionary GetParseSynonyms() { Dictionary synonyms = s_sqlClientSynonyms; - if (null == synonyms) + if (synonyms == null) { int count = SqlConnectionStringBuilder.KeywordsCount + SynonymCount; @@ -936,7 +936,7 @@ internal string ObtainWorkstationId() // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. string result = WorkstationId; - if (null == result) + if (result == null) { // permission to obtain Environment.MachineName is Asserted // since permission to open the connection has been granted @@ -1172,7 +1172,7 @@ static internal Hashtable NetlibMapping() const int NetLibCount = 8; Hashtable hash = s_netlibMapping; - if (null == hash) + if (hash == null) { hash = new Hashtable(NetLibCount) { 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 bf1b67093a..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(); } @@ -193,19 +193,19 @@ protected override void InitializeBatching() SqlClientEventSource.Log.TryTraceEvent("SqlDataAdapter.InitializeBatching | API | Object Id {0}", ObjectID); _commandSet = new SqlCommandSet(); SqlCommand command = SelectCommand; - if (null == command) + if (command == null) { command = InsertCommand; - if (null == command) + if (command == null) { command = UpdateCommand; - if (null == command) + if (command == null) { command = DeleteCommand; } } } - 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 0b882bc02c..e8d474b3da 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -50,7 +50,7 @@ public override bool Equals(object value) bool result = false; - if (null == temp) + if (temp == null) { // If passed value null - false. result = false; } @@ -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(); } @@ -115,7 +115,7 @@ public override bool Equals(object value) bool result = false; - if (null == temp) + if (temp == null) { // If passed value null - false. result = false; } @@ -158,7 +158,7 @@ public override bool Equals(object value) bool result = false; - if (null == temp) + if (temp == null) { // If passed value null - false. result = false; } @@ -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. @@ -577,7 +577,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul #endif if (string.IsNullOrEmpty(connectionString)) { - if (null == connectionString) + if (connectionString == null) { throw ADP.ArgumentNull(nameof(connectionString)); } @@ -612,7 +612,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul { try { - if (null == s_processDispatcher) + if (s_processDispatcher == null) { // Ensure _processDispatcher reference is present - inside lock. #if NETFRAMEWORK ObtainProcessDispatcher(); @@ -730,7 +730,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault #endif if (string.IsNullOrEmpty(connectionString)) { - if (null == connectionString) + if (connectionString == null) { throw ADP.ArgumentNull(nameof(connectionString)); } @@ -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 0dbdb28c42..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; @@ -426,7 +426,7 @@ private void CreateQueueAndService(bool restart) } } - if (null == trans) + if (trans == null) { // Create a new transaction for next operations. trans = _con.BeginTransaction(); com.Transaction = trans; @@ -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) @@ -1281,7 +1281,7 @@ public override bool Equals(object value) // Ignore SqlConnectionStringBuilder, since it is present largely for debug purposes. - if (null == temp) + if (temp == null) { // If passed value null - false. result = false; } @@ -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); } @@ -1363,7 +1363,7 @@ public override int GetHashCode() // Private constructor - only called by public constructor for static initialization. private SqlDependencyProcessDispatcher(object dummyVariable) { - Debug.Assert(null == s_staticInstance, "Real constructor called with static instance already created!"); + Debug.Assert(s_staticInstance == null, "Real constructor called with static instance already created!"); long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { @@ -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 c3a0bb1492..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) @@ -351,7 +351,7 @@ internal SqlDependency LookupDependencyEntry(string id) long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, Key: '{1}'", ObjectID, id); try { - if (null == id) + if (id == null) { throw ADP.ArgumentNull(nameof(id)); } @@ -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/SqlEnclaveSession.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlEnclaveSession.cs index b7b87112af..a4c30621d3 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlEnclaveSession.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlEnclaveSession.cs @@ -43,7 +43,7 @@ private byte[] Clone(byte[] arrayToClone) /// internal SqlEnclaveSession(byte[] sessionKey, long sessionId) { - if (null == sessionKey) + if (sessionKey == null) { throw SQL.NullArgumentInConstructorInternal(_sessionKeyName, _className); } 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 401815cf94..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(); } @@ -430,7 +430,7 @@ protected void Enlist(Transaction tx) // Sys.Tx keeps the connection alive until the transaction is completed. Debug.Assert(!IsNonPoolableTransactionRoot, "cannot defect an active delegated transaction!"); // potential race condition, but it's an assert - if (null == tx) + if (tx == null) { if (IsEnlistedInTransaction) { @@ -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; @@ -581,7 +581,7 @@ private void EnlistNonNull(Transaction tx) } else { - if (null == _whereAbouts) + if (_whereAbouts == null) { byte[] dtcAddress = GetDTCAddress(); _whereAbouts = dtcAddress ?? throw SQL.CannotGetDTCAddress(); @@ -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() @@ -644,7 +644,7 @@ internal void EnlistNull() // In either case, when we're working with a 2005 or newer server // we better not have a current transaction at this point. - Debug.Assert(null == CurrentTransaction, "unenlisted transaction with non-null current transaction?"); // verify it! + Debug.Assert(CurrentTransaction == null, "unenlisted transaction with non-null current transaction?"); // verify it! } override public void EnlistTransaction(Transaction transaction) @@ -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 a7c7fa58e1..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; } @@ -465,7 +465,7 @@ public override DbType DbType set { MetaType metatype = _metaType; - if ((null == metatype) || (metatype.DbType != value)) + if (metatype == null || (metatype.DbType != value)) { PropertyTypeChanging(); _metaType = MetaType.GetMetaTypeFromDbType(value); @@ -513,7 +513,7 @@ public int LocaleId get { SqlCollation collation = _collation; - if (null != collation) + if (collation != null) { return collation.LCID; } @@ -608,7 +608,7 @@ public SqlDbType SqlDbType { throw SQL.InvalidSqlDbType(value); } - if ((null == metatype) || (metatype.SqlDbType != value)) + if (metatype == null || (metatype.SqlDbType != value)) { PropertyTypeChanging(); _metaType = MetaType.GetMetaTypeFromSqlDbType(value, value == SqlDbType.Structured); @@ -741,7 +741,7 @@ public override object Value _coercedValue = null; _valueAsINullable = _value as INullable; SetFlag(SqlParameterFlags.IsSqlParameterSqlType, _valueAsINullable != null); - SetFlag(SqlParameterFlags.IsNull, (null == _value) || (_value == DBNull.Value) || (HasFlag(SqlParameterFlags.IsSqlParameterSqlType) && _valueAsINullable.IsNull)); + SetFlag(SqlParameterFlags.IsNull, _value == null || (_value == DBNull.Value) || (HasFlag(SqlParameterFlags.IsSqlParameterSqlType) && _valueAsINullable.IsNull)); _udtLoadError = null; _actualSize = -1; } @@ -897,7 +897,7 @@ internal bool CoercedValueIsDataFeed { get { - if (null == _coercedValue) + if (_coercedValue == null) { GetCoercedValue(); } @@ -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) { @@ -1346,7 +1346,7 @@ private void GetActualFieldsAndProperties(out List fields, if (hasDefault) { // May have already created props list in unique key handling - if (null == props) + if (props == null) { props = new SmiMetaDataPropertyCollection(); } @@ -1375,7 +1375,7 @@ private void GetActualFieldsAndProperties(out List fields, } // May have already created props list - if (null == props) + if (props == null) { props = new SmiMetaDataPropertyCollection(); } @@ -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 @@ -1877,7 +1877,7 @@ internal void AssertPropertiesAreValid(object value, bool? isSqlType = null, boo private SqlDbType GetMetaSqlDbTypeOnly() { MetaType metaType = _metaType; - if (null == metaType) + if (metaType == null) { // infer the type from the value metaType = MetaType.GetDefaultMetaType(); } @@ -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 @@ -1977,7 +1977,7 @@ internal void Validate(int index, bool isCommandProc) !ADP.IsDirection(this, ParameterDirection.ReturnValue) && (!metaType.IsFixed) && !ShouldSerializeSize() && - ((null == _value) || Convert.IsDBNull(_value)) && + (_value == null || Convert.IsDBNull(_value)) && (SqlDbType != SqlDbType.Timestamp) && (SqlDbType != SqlDbType.Udt) && // BUG: (VSTFDevDiv - 479609): Output parameter with size 0 throws for XML, TEXT, NTEXT, IMAGE. @@ -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/SqlReferenceCollection.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlReferenceCollection.cs index f6780b1bf4..4ee4d625f3 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlReferenceCollection.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlReferenceCollection.cs @@ -52,7 +52,7 @@ internal SqlDataReader FindLiveReader(SqlCommand command) { if (command is null) { - // if null == command, will find first live datareader + // if command is null, will find first live datareader return FindItem(DataReaderTag, s_hasOpenReaderFunc); } else diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs index 01d2d1bc61..90fb9a5d32 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs @@ -80,7 +80,7 @@ internal static void GenerateRandomBytes(byte[] randomBytes) /// returns true if both the arrays have the same byte values else returns false internal static bool CompareBytes(byte[] buffer1, byte[] buffer2, int buffer2Index, int lengthToCompare) { - if (null == buffer1 || null == buffer2) + if (buffer1 == null || buffer2 == null) { return false; } @@ -140,7 +140,7 @@ private static string ValidateAndGetEncryptionAlgorithmName(byte cipherAlgorithm { if (TdsEnums.CustomCipherAlgorithmId == cipherAlgorithmId) { - if (null == cipherAlgorithmName) + if (cipherAlgorithmName == null) { throw SQL.NullColumnEncryptionAlgorithm(SqlClientEncryptionAlgorithmFactoryList.GetInstance().GetRegisteredCipherAlgorithmNames()); } @@ -178,7 +178,7 @@ internal static byte[] EncryptWithKey(byte[] plainText, SqlCipherMetadata md, Sq Debug.Assert(md.IsAlgorithmInitialized(), "Encryption Algorithm is not initialized"); byte[] cipherText = md.CipherAlgorithm.EncryptData(plainText); // this call succeeds or throws. - if (null == cipherText || 0 == cipherText.Length) + if (cipherText == null || 0 == cipherText.Length) { throw SQL.NullCipherText(); } @@ -217,7 +217,7 @@ internal static byte[] DecryptWithKey(byte[] cipherText, SqlCipherMetadata md, S try { byte[] plainText = md.CipherAlgorithm.DecryptData(cipherText); // this call succeeds or throws. - if (null == plainText) + if (plainText == null) { throw SQL.NullPlainText(); } 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/SqlStream.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlStream.cs index 4c78cc4c85..62401a49de 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlStream.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlStream.cs @@ -76,11 +76,11 @@ public override int Read(byte[] buffer, int offset, int count) int intCount = 0; int cBufferedData = 0; - if (null == _reader) + if (_reader == null) { throw ADP.StreamClosed(); } - if (null == buffer) + if (buffer == null) { throw ADP.ArgumentNull(nameof(buffer)); } @@ -305,7 +305,7 @@ public override long Position } set { - if (null == _cachedBytes) + if (_cachedBytes == null) { throw ADP.StreamClosed(ADP.ParameterSetPosition); } @@ -337,12 +337,12 @@ public override int Read(byte[] buffer, int offset, int count) int cb; int intCount = 0; - if (null == _cachedBytes) + if (_cachedBytes == null) { throw ADP.StreamClosed(); } - if (null == buffer) + if (buffer == null) { throw ADP.ArgumentNull(nameof(buffer)); } @@ -394,7 +394,7 @@ public override long Seek(long offset, SeekOrigin origin) { long pos = 0; - if (null == _cachedBytes) + if (_cachedBytes == null) { throw ADP.StreamClosed(); } 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 269b69ca3e..444d6c79e9 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -43,7 +43,7 @@ private bool IsDisposed { get { - return (null == _freeStateObjects); + return _freeStateObjects == null; } } @@ -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(); @@ -212,7 +211,7 @@ internal string TraceString() return string.Format(/*IFormatProvider*/ null, "(ObjID={0}, free={1}, cached={2}, total={3})", _objectID, - null == _freeStateObjects ? "(null)" : _freeStateObjectCount.ToString((IFormatProvider)null), + _freeStateObjects == null ? "(null)" : _freeStateObjectCount.ToString((IFormatProvider)null), _cachedCount, _cache.Count); } @@ -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 c1dc058ff2..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; @@ -1654,7 +1654,7 @@ internal TdsOperationStatus TryReadStringWithEncoding(int length, System.Text.En TdsParser.ReliabilitySection.Assert("unreliable call to ReadStringWithEncoding"); // you need to setup for a thread abort somewhere before you call this method Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async"); - if (null == encoding) + if (encoding == null) { // Need to skip the current column before throwing the error - this ensures that the state shared between this and the data reader is consistent when calling DrainData if (isPlp) 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 93aac3fdea..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; } @@ -199,7 +199,7 @@ static internal byte[] GetNetworkPhysicalAddressForTdsLoginOnly() } } - if (null == nicAddress) + if (nicAddress == null) { nicAddress = new byte[TdsEnums.MAX_NIC_SIZE]; Random random = new Random(); 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 6b05698972..0a5144a6b8 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsValueSetter.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsValueSetter.cs @@ -250,7 +250,7 @@ internal int SetChars(long fieldOffset, char[] buffer, int bufferOffset, int len // ANSI types must convert to byte[] because that's the tool we have. if (MetaDataUtilsSmi.IsAnsiType(_metaData.SqlDbType)) { - if (null == _encoder) + if (_encoder == null) { _encoder = _stateObj.Parser._defaultEncoding.GetEncoder(); } @@ -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); @@ -452,7 +452,7 @@ internal void SetInt64(long value) SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetInt64)); if (SqlDbType.Variant == _metaData.SqlDbType) { - if (null == _variantType) + if (_variantType == null) { _stateObj.Parser.WriteSqlVariantHeader(10, TdsEnums.SQLINT8, 0, _stateObj); _stateObj.Parser.WriteLong(value, _stateObj); @@ -735,7 +735,7 @@ internal void SetDateTimeOffset(DateTimeOffset value) internal void SetVariantType(SmiMetaData value) { - Debug.Assert(null == _variantType, "Variant type can only be set once"); + Debug.Assert(_variantType == null, "Variant type can only be set once"); Debug.Assert(value != null && (value.SqlDbType == SqlDbType.Money || value.SqlDbType == SqlDbType.NVarChar || 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 9a88b2e5ee..9e69b7a39f 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs @@ -643,19 +643,19 @@ public static void DropDatabase(SqlConnection sqlConnection, string dbName) public static string GetAccessToken() { - if (null == AADAccessToken && IsAADPasswordConnStrSetup() && IsAADAuthorityURLSetup()) + if (AADAccessToken == null && IsAADPasswordConnStrSetup() && IsAADAuthorityURLSetup()) { string username = RetrieveValueFromConnStr(AADPasswordConnectionString, new string[] { "User ID", "UID" }); string password = RetrieveValueFromConnStr(AADPasswordConnectionString, new string[] { "Password", "PWD" }); 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() { - if (ManagedIdentitySupported && SupportsSystemAssignedManagedIdentity && null == AADSystemIdentityAccessToken && IsAADPasswordConnStrSetup()) + if (ManagedIdentitySupported && SupportsSystemAssignedManagedIdentity && AADSystemIdentityAccessToken == null && IsAADPasswordConnStrSetup()) { AADSystemIdentityAccessToken = AADUtility.GetManagedIdentityToken().GetAwaiter().GetResult(); if (AADSystemIdentityAccessToken == null) @@ -663,12 +663,12 @@ 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() { - if (ManagedIdentitySupported && null == AADUserIdentityAccessToken && IsAADPasswordConnStrSetup()) + if (ManagedIdentitySupported && AADUserIdentityAccessToken == null && IsAADPasswordConnStrSetup()) { // Pass User Assigned Managed Identity Client Id here. AADUserIdentityAccessToken = AADUtility.GetManagedIdentityToken(UserManagedIdentityClientId).GetAwaiter().GetResult(); @@ -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 5b11b46b8c..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); } @@ -263,7 +263,7 @@ private string FindDiffFromBaseline(string baselinePath, string outputPath) private string AssemblyFilter(StreamWriter writer) { - if (null == _outputBuilder) + if (_outputBuilder == null) { _outputBuilder = new StringBuilder(); } @@ -279,7 +279,7 @@ private string AssemblyFilter(StreamWriter writer) private void AssemblyFilter(StringBuilder builder) { string[] filter = _outputFilter; - if (null == filter) + if (filter == null) { filter = new string[5]; string tmp = typeof(System.Guid).AssemblyQualifiedName; 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 e3226c5e3c..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(); @@ -1643,7 +1643,7 @@ private void WriteObject(StringBuilder textBuilder, object value, CultureInfo cu { return; } - if (null == value) + if (value == null) { textBuilder.Append("DEFAULT"); } @@ -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; @@ -1847,7 +1847,7 @@ private void WriteObject(StringBuilder textBuilder, object value, CultureInfo cu if (property.CanRead) { ParameterInfo[] parameters = property.GetIndexParameters(); - if ((null == parameters) || (0 == parameters.Length)) + if (parameters == null || (0 == parameters.Length)) { AppendNewLineIndent(textBuilder, indent + 1); textBuilder.Append(property.Name); @@ -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/ExceptionTest/ExceptionTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ExceptionTest.cs index e34b47e262..ce751c4d29 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ExceptionTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ExceptionTest.cs @@ -201,11 +201,17 @@ public static void ExceptionTests() } // Synapse: 110003;Invalid user or password - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void VariousExceptionTests() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString); - + // Strip the password in connection string if Authentication=Active Directory Managed Identity as it can not be used with a Password + if (builder.Authentication == SqlAuthenticationMethod.ActiveDirectoryManagedIdentity) + { + string[] removeKeys = { "Password", "PWD" }; + string connStr = DataTestUtility.RemoveKeysInConnStr(DataTestUtility.TCPConnectionString, removeKeys); + builder = new SqlConnectionStringBuilder(connStr); + } // Test 1 - A SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 }; @@ -219,11 +225,14 @@ public static void VariousExceptionTests() } // Test 1 - B - badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { Password = string.Empty, IntegratedSecurity = false, Authentication = SqlAuthenticationMethod.NotSpecified }; - using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString)) + if (DataTestUtility.IsNotAzureServer()) { - string errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID); - VerifyConnectionFailure(() => sqlConnection.Open(), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14)); + badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { Password = string.Empty, IntegratedSecurity = false }; + using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString)) + { + string errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID); + VerifyConnectionFailure(() => sqlConnection.Open(), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14)); + } } } 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 b8882b451a..d1fe3bf6ac 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/TvpTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/TvpTest.cs @@ -1034,7 +1034,7 @@ private DataTable CreateNewTable(object[] row, ref Type[] lastRowTypes) { object value = row[i]; Type t; - if ((null == value || DBNull.Value == value)) + if (value == null || DBNull.Value == value) { if (lastRowTypes[i] == null) { @@ -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; } @@ -1310,16 +1310,16 @@ private IList GenerateDataTables(object[][] values) } } - if (null == targetTable) + 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); } @@ -1345,10 +1345,9 @@ private string GetTypeName(StePermutation tvpPerm) private bool IsNull(object value) { - return null == value || - DBNull.Value == value || - (value is INullable nullable && - nullable.IsNull); + return value == null || + DBNull.Value == value || + (value is INullable nullable && nullable.IsNull); } private SqlMetaData PermToSqlMetaData(StePermutation perm) @@ -1417,11 +1416,11 @@ private SqlMetaData PermToSqlMetaData(StePermutation perm) private void ReportMismatch(object source, object result, StePermutation perm) { - if (null == source) + if (source == null) { source = "(null)"; } - if (null == result) + if (result == null) { result = "(null)"; } @@ -1446,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/RetryLogic/RetryLogicTestHelper.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/RetryLogic/RetryLogicTestHelper.cs index ba83e9b22a..a9eb1b52a2 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/RetryLogic/RetryLogicTestHelper.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/RetryLogic/RetryLogicTestHelper.cs @@ -71,7 +71,8 @@ private static readonly HashSet s_defaultTransientErrors 20, 0, -2, // Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. - 207 // invalid column name + 207, // invalid column name + 18456 // Using managed identity in Azure Sql Server throws 18456 for non-existent database instead of 4060. }; internal static readonly string s_exceedErrMsgPattern = SystemDataResourceManager.Instance.SqlRetryLogic_RetryExceeded; @@ -117,7 +118,7 @@ public static IEnumerable GetConnectionAndRetryStrategy(int numberOfRe public static IEnumerable GetConnectionAndRetryStrategyInvalidCatalog(int numberOfRetries) { - return GetConnectionAndRetryStrategy(numberOfRetries, TimeSpan.FromSeconds(1), FilterSqlStatements.None, null, 250, false); + return GetConnectionAndRetryStrategy(numberOfRetries, TimeSpan.FromSeconds(1), FilterSqlStatements.None, null, 250, true); } public static IEnumerable GetConnectionAndRetryStrategyInvalidCommand(int numberOfRetries) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/RetryLogic/SqlConnectionReliabilityTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/RetryLogic/SqlConnectionReliabilityTest.cs index 285da7f5ac..7bdebfcfc1 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/RetryLogic/SqlConnectionReliabilityTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/RetryLogic/SqlConnectionReliabilityTest.cs @@ -17,7 +17,7 @@ public class SqlConnectionReliabilityTest #region Sync // Test relies on error 4060 for automatic retry, which is not reliable when using Azure or AAD auth - [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] + [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] [MemberData(nameof(RetryLogicTestHelper.GetConnectionAndRetryStrategyInvalidCatalog), parameters: new object[] { 2 }, MemberType = typeof(RetryLogicTestHelper), DisableDiscoveryEnumeration = true)] public void ConnectionRetryOpenInvalidCatalogFailed(string cnnString, SqlRetryLogicBaseProvider provider) { @@ -35,7 +35,7 @@ public void ConnectionRetryOpenInvalidCatalogFailed(string cnnString, SqlRetryLo } // Test relies on error 4060 for automatic retry, which is not reliable when using Azure or AAD auth - [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] + [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] [MemberData(nameof(RetryLogicTestHelper.GetConnectionAndRetryStrategyInvalidCatalog), parameters: new object[] { 2 }, MemberType = typeof(RetryLogicTestHelper), DisableDiscoveryEnumeration = true)] public void ConnectionCancelRetryOpenInvalidCatalog(string cnnString, SqlRetryLogicBaseProvider provider) { @@ -158,7 +158,7 @@ public void DefaultOpenWithoutRetry(string connectionString, SqlRetryLogicBasePr #region Async // Test relies on error 4060 for automatic retry, which is not reliable when using Azure or AAD auth - [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] + [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] [MemberData(nameof(RetryLogicTestHelper.GetConnectionAndRetryStrategyInvalidCatalog), parameters: new object[] { 5 }, MemberType = typeof(RetryLogicTestHelper), DisableDiscoveryEnumeration = true)] public async void ConnectionRetryOpenAsyncInvalidCatalogFailed(string cnnString, SqlRetryLogicBaseProvider provider) { 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 f799796bec..c22039c2de 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/InvalidAccessFromEvent.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/InvalidAccessFromEvent.cs @@ -104,7 +104,7 @@ internal static void InnerTest(SqlRowsCopiedEventHandler eventHandler) bool hitException = false; try { - if (null == _tx || null == _tx.Connection) + if (_tx == null || _tx.Connection == null) { _tx = _dstConn.BeginTransaction(); _dstcmd.Transaction = _tx; @@ -134,7 +134,7 @@ internal static void InnerTest(SqlRowsCopiedEventHandler eventHandler) } catch (Exception e) { - while (null != e.InnerException) + while (e.InnerException != null) { e = e.InnerException; } diff --git a/tools/props/Versions.props b/tools/props/Versions.props index 9c83ce6dd6..3e85dd49d0 100644 --- a/tools/props/Versions.props +++ b/tools/props/Versions.props @@ -23,7 +23,7 @@ - 5.2.0 + 6.0.0-preview1.24226.4 @@ -36,7 +36,7 @@ - 5.2.0 + 6.0.0-preview1.24226.4 6.0.1 1.0.0 6.0.1 diff --git a/tools/specs/Microsoft.Data.SqlClient.nuspec b/tools/specs/Microsoft.Data.SqlClient.nuspec index 9c96324945..e54a6e7674 100644 --- a/tools/specs/Microsoft.Data.SqlClient.nuspec +++ b/tools/specs/Microsoft.Data.SqlClient.nuspec @@ -28,7 +28,7 @@ When using NuGet 3.x this package requires at least version 3.4. sqlclient microsoft.data.sqlclient - + @@ -38,7 +38,7 @@ When using NuGet 3.x this package requires at least version 3.4. - + @@ -47,7 +47,7 @@ When using NuGet 3.x this package requires at least version 3.4. - +