From 4f04db72a2f5bafd26a728cda14c129be9d1a2a6 Mon Sep 17 00:00:00 2001 From: Wraith Date: Fri, 7 Aug 2020 17:39:23 +0100 Subject: [PATCH 01/24] Rename netcore string resource file and helpers (#671) --- .../CoreLib/Interop/Unix/Interop.IOErrors.cs | 24 +- .../Interop.GssApiException.cs | 4 +- .../Interop.GssBuffer.cs | 2 +- .../Interop.EcDsa.ImportExport.cs | 8 +- .../Interop.OpenSsl.cs | 32 +- .../Interop.SslCtx.cs | 2 +- .../Interop/Windows/sspicli/SSPIAuthType.cs | 4 +- .../Windows/sspicli/SSPISecureChannelType.cs | 6 +- .../Interop/Windows/sspicli/SSPIWrapper.cs | 16 +- .../src/Microsoft/Data/Common/AdapterUtil.cs | 62 +- .../src/Microsoft/Data/Common/SQLResource.cs | 48 +- .../Net/Security/NegotiateStreamPal.Unix.cs | 14 +- .../Security/NegotiateStreamPal.Windows.cs | 2 +- .../src/Microsoft.Data.SqlClient.csproj | 12 +- .../Data/Common/AdapterUtil.SqlClient.cs | 170 ++--- .../src/Microsoft/Data/DataException.cs | 2 +- .../Data/OperationAbortedException.cs | 4 +- ...estationBasedEnclaveProvider.NetCoreApp.cs | 26 +- .../EnclaveSessionCache.NetCoreApp.cs | 2 +- .../Data/SqlClient/LocalDBAPI.Common.cs | 6 +- .../Data/SqlClient/LocalDBAPI.Unix.cs | 2 +- .../Data/SqlClient/LocalDBAPI.Windows.cs | 2 +- .../Data/SqlClient/LocalDBAPI.uap.cs | 2 +- .../Data/SqlClient/SNI/LocalDB.Unix.cs | 2 +- .../Data/SqlClient/SNI/LocalDB.uap.cs | 2 +- .../SqlClient/Server/InvalidUdtException.cs | 4 +- .../Data/SqlClient/Server/SqlMetaData.cs | 26 +- .../Data/SqlClient/Server/SqlNorm.cs | 2 +- .../Microsoft/Data/SqlClient/Server/SqlSer.cs | 4 +- .../SqlUserDefinedAggregateAttribute.cs | 2 +- .../SimulatorEnclaveProvider.NetCoreApp.cs | 2 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 4 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 2 +- .../SqlClient/SqlFileStream.Unsupported.cs | 28 +- .../SqlClient/SqlInternalConnectionTds.cs | 4 +- .../Microsoft/Data/SqlClient/SqlParameter.cs | 2 +- .../Microsoft/Data/SqlClient/SqlStatistics.cs | 6 +- .../Microsoft/Data/SqlClient/SqlUdtInfo.cs | 2 +- .../src/Microsoft/Data/SqlClient/SqlUtil.cs | 650 +++++++++--------- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 6 +- .../Data/SqlClient/TdsParserHelperClasses.cs | 4 +- .../Data/SqlClient/TdsParserStateObject.cs | 4 +- .../SqlClient/TdsParserStateObjectNative.cs | 2 +- ...ualSecureModeEnclaveProvider.NetCoreApp.cs | 4 +- ...ecureModeEnclaveProviderBase.NetCoreApp.cs | 18 +- .../Data/SqlTypes/SqlFileStream.Windows.cs | 12 +- .../{SR.Designer.cs => Strings.Designer.cs} | 8 +- .../src/Resources/{SR.resx => Strings.resx} | 0 .../{SRHelper.cs => StringsHelper.cs} | 18 +- .../DataCommon/AssemblyResourceManager.cs | 4 - 50 files changed, 635 insertions(+), 639 deletions(-) rename src/Microsoft.Data.SqlClient/netcore/src/Resources/{SR.Designer.cs => Strings.Designer.cs} (99%) rename src/Microsoft.Data.SqlClient/netcore/src/Resources/{SR.resx => Strings.resx} (100%) rename src/Microsoft.Data.SqlClient/netcore/src/Resources/{SRHelper.cs => StringsHelper.cs} (89%) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.IOErrors.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.IOErrors.cs index 5babcd1d05..d23744fba2 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.IOErrors.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.IOErrors.cs @@ -119,14 +119,14 @@ internal static Exception GetExceptionForIoErrno(ErrorInfo errorInfo, string pat if (isDirectory) { return !string.IsNullOrEmpty(path) ? - new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, path)) : - new DirectoryNotFoundException(SR.IO_PathNotFound_NoPathName); + new DirectoryNotFoundException(Strings.Format(Strings.IO_PathNotFound_Path, path)) : + new DirectoryNotFoundException(Strings.IO_PathNotFound_NoPathName); } else { return !string.IsNullOrEmpty(path) ? - new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, path), path) : - new FileNotFoundException(SR.IO_FileNotFound); + new FileNotFoundException(Strings.Format(Strings.IO_FileNotFound_FileName, path), path) : + new FileNotFoundException(Strings.IO_FileNotFound); } case Error.EACCES: @@ -134,29 +134,29 @@ internal static Exception GetExceptionForIoErrno(ErrorInfo errorInfo, string pat case Error.EPERM: Exception inner = GetIOException(errorInfo); return !string.IsNullOrEmpty(path) ? - new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, path), inner) : - new UnauthorizedAccessException(SR.UnauthorizedAccess_IODenied_NoPathName, inner); + new UnauthorizedAccessException(Strings.Format(Strings.UnauthorizedAccess_IODenied_Path, path), inner) : + new UnauthorizedAccessException(Strings.UnauthorizedAccess_IODenied_NoPathName, inner); case Error.ENAMETOOLONG: return !string.IsNullOrEmpty(path) ? - new PathTooLongException(SR.Format(SR.IO_PathTooLong_Path, path)) : - new PathTooLongException(SR.IO_PathTooLong); + new PathTooLongException(Strings.Format(Strings.IO_PathTooLong_Path, path)) : + new PathTooLongException(Strings.IO_PathTooLong); case Error.EWOULDBLOCK: return !string.IsNullOrEmpty(path) ? - new IOException(SR.Format(SR.IO_SharingViolation_File, path), errorInfo.RawErrno) : - new IOException(SR.IO_SharingViolation_NoFileName, errorInfo.RawErrno); + new IOException(Strings.Format(Strings.IO_SharingViolation_File, path), errorInfo.RawErrno) : + new IOException(Strings.IO_SharingViolation_NoFileName, errorInfo.RawErrno); case Error.ECANCELED: return new OperationCanceledException(); case Error.EFBIG: - return new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_FileLengthTooBig); + return new ArgumentOutOfRangeException("value", Strings.ArgumentOutOfRange_FileLengthTooBig); case Error.EEXIST: if (!string.IsNullOrEmpty(path)) { - return new IOException(SR.Format(SR.IO_FileExists_Name, path), errorInfo.RawErrno); + return new IOException(Strings.Format(Strings.IO_FileExists_Name, path), errorInfo.RawErrno); } goto default; diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssApiException.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssApiException.cs index 0da9396f54..88c07619c4 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssApiException.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssApiException.cs @@ -37,8 +37,8 @@ private static string GetGssApiDisplayStatus(Status majorStatus, Status minorSta string minorError = GetGssApiDisplayStatus(minorStatus, isMinor: true); return (majorError != null && minorError != null) ? - SRHelper.Format(SR.net_gssapi_operation_failed_detailed, majorError, minorError) : - SRHelper.Format(SR.net_gssapi_operation_failed, majorStatus.ToString("x"), minorStatus.ToString("x")); + StringsHelper.Format(Strings.net_gssapi_operation_failed_detailed, majorError, minorError) : + StringsHelper.Format(Strings.net_gssapi_operation_failed, majorStatus.ToString("x"), minorStatus.ToString("x")); } private static string GetGssApiDisplayStatus(Status status, bool isMinor) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs index 8bed992b93..f70aabfb68 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs @@ -32,7 +32,7 @@ internal int Copy(byte[] destination, int offset) int destinationAvailable = destination.Length - offset; // amount of space in the given buffer if (sourceLength > destinationAvailable) { - throw new NetSecurityNative.GssApiException(SRHelper.Format(SR.net_context_buffer_too_small, sourceLength, destinationAvailable)); + throw new NetSecurityNative.GssApiException(StringsHelper.Format(Strings.net_context_buffer_too_small, sourceLength, destinationAvailable)); } Marshal.Copy(_data, destination, offset, sourceLength); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs index 5f72e26625..f2b0bfc192 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs @@ -36,7 +36,7 @@ internal static SafeEcKeyHandle EcKeyCreateByKeyParameters( key?.Dispose(); Interop.Crypto.ErrClearError(); - throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, oid)); + throw new PlatformNotSupportedException(Strings.Format(Strings.Cryptography_CurveNotSupported, oid)); } return key; } @@ -69,7 +69,7 @@ internal static SafeEcKeyHandle EcKeyCreateByExplicitCurve(ECCurve curve) } else { - throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString())); + throw new PlatformNotSupportedException(Strings.Format(Strings.Cryptography_CurveNotSupported, curve.CurveType.ToString())); } SafeEcKeyHandle key = Interop.Crypto.EcKeyCreateByExplicitParameters( @@ -131,7 +131,7 @@ internal static ECParameters GetECKeyParameters( if (rc == -1) { - throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); + throw new CryptographicException(Strings.Cryptography_CSP_NoPrivateKey); } else if (rc != 1) { @@ -218,7 +218,7 @@ internal static ECParameters GetECCurveParameters( if (rc == -1) { - throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); + throw new CryptographicException(Strings.Cryptography_CSP_NoPrivateKey); } else if (rc != 1) { diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs index 1f9530594c..108b6a64e6 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs @@ -61,7 +61,7 @@ internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX50 { if (innerContext.IsInvalid) { - throw CreateSslException(SR.net_allocate_ssl_context_failed); + throw CreateSslException(Strings.net_allocate_ssl_context_failed); } // Configure allowed protocols. It's ok to use DangerousGetHandle here without AddRef/Release as we just @@ -80,7 +80,7 @@ internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX50 if (!Ssl.SetEncryptionPolicy(innerContext, policy)) { Crypto.ErrClearError(); - throw new PlatformNotSupportedException(SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy)); + throw new PlatformNotSupportedException(Strings.Format(Strings.net_ssl_encryptionpolicy_notsupported, policy)); } bool hasCertificateAndKey = @@ -111,7 +111,7 @@ internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX50 { if (Interop.Ssl.SslCtxSetAlpnProtos(innerContext, sslAuthenticationOptions.ApplicationProtocols) != 0) { - throw CreateSslException(SR.net_alpn_config_failed); + throw CreateSslException(Strings.net_alpn_config_failed); } } } @@ -121,7 +121,7 @@ internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX50 if (context.IsInvalid) { context.Dispose(); - throw CreateSslException(SR.net_allocate_ssl_context_failed); + throw CreateSslException(Strings.net_allocate_ssl_context_failed); } if (!sslAuthenticationOptions.IsServer) @@ -147,7 +147,7 @@ internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX50 using (X509Chain chain = TLSCertificateExtensions.BuildNewChain(cert, includeClientApplicationPolicy: false)) { if (chain != null && !Ssl.AddExtraChainCertificates(context, chain)) - throw CreateSslException(SR.net_ssl_use_cert_failed); + throw CreateSslException(Strings.net_ssl_use_cert_failed); } } } @@ -196,7 +196,7 @@ internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int r if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ)) { - throw new SslException(SR.Format(SR.net_ssl_handshake_failed_error, error), innerError); + throw new SslException(Strings.Format(Strings.net_ssl_handshake_failed_error, error), innerError); } } @@ -259,7 +259,7 @@ internal static int Encrypt(SafeSslHandle context, ReadOnlyMemory input, r break; default: - throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError); + throw new SslException(Strings.Format(Strings.net_ssl_encrypt_failed, errorCode), innerError); } } else @@ -328,7 +328,7 @@ internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int offset, break; default: - throw new SslException(SR.Format(SR.net_ssl_decrypt_failed, errorCode), innerError); + throw new SslException(Strings.Format(Strings.net_ssl_decrypt_failed, errorCode), innerError); } } @@ -358,7 +358,7 @@ private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannel if (0 == certHashLength) { - throw CreateSslException(SR.net_ssl_get_channel_binding_token_failed); + throw CreateSslException(Strings.net_ssl_get_channel_binding_token_failed); } bindingHandle.SetCertHashLength(certHashLength); @@ -430,7 +430,7 @@ private static int BioRead(SafeBioHandle bio, byte[] buffer, int count) int bytes = Crypto.BioRead(bio, buffer, count); if (bytes != count) { - throw CreateSslException(SR.net_ssl_read_bio_failed_error); + throw CreateSslException(Strings.net_ssl_read_bio_failed_error); } return bytes; } @@ -453,7 +453,7 @@ private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int co if (bytes != count) { - throw CreateSslException(SR.net_ssl_write_bio_failed_error); + throw CreateSslException(Strings.net_ssl_write_bio_failed_error); } return bytes; } @@ -496,14 +496,14 @@ private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509H if (1 != retVal) { - throw CreateSslException(SR.net_ssl_use_cert_failed); + throw CreateSslException(Strings.net_ssl_use_cert_failed); } retVal = Ssl.SslCtxUsePrivateKey(contextPtr, keyPtr); if (1 != retVal) { - throw CreateSslException(SR.net_ssl_use_private_key_failed); + throw CreateSslException(Strings.net_ssl_use_private_key_failed); } //check private key @@ -511,7 +511,7 @@ private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509H if (1 != retVal) { - throw CreateSslException(SR.net_ssl_check_private_key_failed); + throw CreateSslException(Strings.net_ssl_check_private_key_failed); } } @@ -520,7 +520,7 @@ internal static SslException CreateSslException(string message) // Capture last error to be consistent with CreateOpenSslCryptographicException ulong errorVal = Crypto.ErrPeekLastError(); Crypto.ErrClearError(); - string msg = SR.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal))); + string msg = Strings.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal))); return new SslException(msg, (int)errorVal); } @@ -547,7 +547,7 @@ public SslException(string inputMessage, int error) } public SslException(int error) - : this(SR.Format(SR.net_generic_operation_failed, error)) + : this(Strings.Format(Strings.net_generic_operation_failed, error)) { HResult = error; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs index b1996871d9..e796f7c661 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs @@ -51,7 +51,7 @@ internal static byte[] ConvertAlpnProtocolListToByteArray(List byte.MaxValue) { - throw new ArgumentException(SR.net_ssl_app_protocols_invalid, nameof(applicationProtocols)); + throw new ArgumentException(Strings.net_ssl_app_protocols_invalid, nameof(applicationProtocols)); } protocolSize += protocol.Protocol.Length + 1; diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs index 8855379df7..cfec6e4e44 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIAuthType.cs @@ -96,7 +96,7 @@ public unsafe int DecryptMessage(SafeDeleteContext context, ref Interop.SspiCli. if (status == 0 && qop == Interop.SspiCli.SECQOP_WRAP_NO_ENCRYPT) { NetEventSource.Fail(this, $"Expected qop = 0, returned value = {qop}"); - throw new InvalidOperationException(SR.net_auth_message_not_encrypted); + throw new InvalidOperationException(Strings.net_auth_message_not_encrypted); } return status; @@ -156,7 +156,7 @@ public unsafe int QueryContextAttributes(SafeDeleteContext context, Interop.Sspi } else { - throw new ArgumentException(SRHelper.Format(SR.SSPIInvalidHandleType, handleType.FullName), nameof(handleType)); + throw new ArgumentException(StringsHelper.Format(Strings.SSPIInvalidHandleType, handleType.FullName), nameof(handleType)); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs index c46f602221..1f0f472d40 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPISecureChannelType.cs @@ -97,12 +97,12 @@ public unsafe int DecryptMessage(SafeDeleteContext context, ref Interop.SspiCli. public int MakeSignature(SafeDeleteContext context, ref Interop.SspiCli.SecBufferDesc inputOutput, uint sequenceNumber) { - throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); + throw NotImplemented.ByDesignWithMessage(Strings.net_MethodNotImplementedException); } public int VerifySignature(SafeDeleteContext context, ref Interop.SspiCli.SecBufferDesc inputOutput, uint sequenceNumber) { - throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); + throw NotImplemented.ByDesignWithMessage(Strings.net_MethodNotImplementedException); } public unsafe int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.SspiCli.ContextAttribute attribute, out SafeFreeContextBufferChannelBinding refHandle) @@ -129,7 +129,7 @@ public unsafe int QueryContextAttributes(SafeDeleteContext phContext, Interop.Ss } else { - throw new ArgumentException(System.SRHelper.Format(SR.SSPIInvalidHandleType, handleType.FullName), nameof(handleType)); + throw new ArgumentException(System.StringsHelper.Format(Strings.SSPIInvalidHandleType, handleType.FullName), nameof(handleType)); } } fixed (byte* bufferPtr = buffer) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs index 3e31c0c845..ea8e713529 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/SSPIWrapper.cs @@ -81,7 +81,7 @@ internal static SecurityPackageInfoClass GetVerifyPackageInfo(SSPIInterface secM if (throwIfMissing) { - throw new NotSupportedException(SR.net_securitypackagesupport); + throw new NotSupportedException(Strings.net_securitypackagesupport); } return null; @@ -101,7 +101,7 @@ public static SafeFreeCredentials AcquireDefaultCredential(SSPIInterface secModu if (errorCode != 0) { if (NetEventSource.IsEnabled) - NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, nameof(AcquireDefaultCredential), $"0x{errorCode:X}")); + NetEventSource.Error(null, System.StringsHelper.Format(Strings.net_log_operation_failed_with_error, nameof(AcquireDefaultCredential), $"0x{errorCode:X}")); throw new Win32Exception(errorCode); } return outCredential; @@ -118,7 +118,7 @@ public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModu if (errorCode != 0) { if (NetEventSource.IsEnabled) - NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}")); + NetEventSource.Error(null, System.StringsHelper.Format(Strings.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}")); throw new Win32Exception(errorCode); } @@ -143,7 +143,7 @@ public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModu if (errorCode != 0) { if (NetEventSource.IsEnabled) - NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}")); + NetEventSource.Error(null, System.StringsHelper.Format(Strings.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}")); throw new Win32Exception(errorCode); } @@ -295,7 +295,7 @@ private static unsafe int EncryptDecryptHelper(OP op, SSPIInterface secModule, S default: NetEventSource.Fail(null, $"Unknown OP: {op}"); - throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); + throw NotImplemented.ByDesignWithMessage(Strings.net_MethodNotImplementedException); } // Marshalling back returned sizes / data. @@ -359,11 +359,11 @@ private static unsafe int EncryptDecryptHelper(OP op, SSPIInterface secModule, S { if (errorCode == Interop.SspiCli.SEC_I_RENEGOTIATE) { - NetEventSource.Error(null, System.SRHelper.Format(SR.event_OperationReturnedSomething, op, "SEC_I_RENEGOTIATE")); + NetEventSource.Error(null, System.StringsHelper.Format(Strings.event_OperationReturnedSomething, op, "SEC_I_RENEGOTIATE")); } else { - NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, op, $"0x{0:X}")); + NetEventSource.Error(null, System.StringsHelper.Format(Strings.net_log_operation_failed_with_error, op, $"0x{0:X}")); } } @@ -466,7 +466,7 @@ public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteC break; default: - throw new ArgumentException(System.SRHelper.Format(SR.net_invalid_enum, nameof(contextAttribute)), nameof(contextAttribute)); + throw new ArgumentException(System.StringsHelper.Format(Strings.net_invalid_enum, nameof(contextAttribute)), nameof(contextAttribute)); } SafeHandle sspiHandle = null; diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs index d98dc914d3..74d812cf5d 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs @@ -200,7 +200,7 @@ internal static bool RemoveStringQuotes(string quotePrefix, string quoteSuffix, internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, string value, string method) { - return ArgumentOutOfRange(System.SRHelper.Format(SR.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name); + return ArgumentOutOfRange(System.StringsHelper.Format(Strings.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name); } internal static InvalidOperationException DataAdapter(string error) @@ -215,21 +215,21 @@ private static InvalidOperationException Provider(string error) internal static ArgumentException InvalidMultipartName(string property, string value) { - ArgumentException e = new ArgumentException(System.SRHelper.Format(SR.ADP_InvalidMultipartName, property, value)); + ArgumentException e = new ArgumentException(System.StringsHelper.Format(Strings.ADP_InvalidMultipartName, property, value)); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value) { - ArgumentException e = new ArgumentException(System.SRHelper.Format(SR.ADP_InvalidMultipartNameQuoteUsage, property, value)); + ArgumentException e = new ArgumentException(System.StringsHelper.Format(Strings.ADP_InvalidMultipartNameQuoteUsage, property, value)); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit) { - ArgumentException e = new ArgumentException(System.SRHelper.Format(SR.ADP_InvalidMultipartNameToManyParts, property, value, limit)); + ArgumentException e = new ArgumentException(System.StringsHelper.Format(Strings.ADP_InvalidMultipartNameToManyParts, property, value, limit)); TraceExceptionAsReturnValue(e); return e; } @@ -286,7 +286,7 @@ internal static bool IsCatchableOrSecurityExceptionType(Exception e) // Invalid Enumeration internal static ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value) { - return ArgumentOutOfRange(System.SRHelper.Format(SR.ADP_InvalidEnumerationValue, type.Name, value.ToString(CultureInfo.InvariantCulture)), type.Name); + return ArgumentOutOfRange(System.StringsHelper.Format(Strings.ADP_InvalidEnumerationValue, type.Name, value.ToString(CultureInfo.InvariantCulture)), type.Name); } // @@ -294,15 +294,15 @@ internal static ArgumentOutOfRangeException InvalidEnumerationValue(Type type, i // internal static ArgumentException ConnectionStringSyntax(int index) { - return Argument(System.SRHelper.Format(SR.ADP_ConnectionStringSyntax, index)); + return Argument(System.StringsHelper.Format(Strings.ADP_ConnectionStringSyntax, index)); } internal static ArgumentException KeywordNotSupported(string keyword) { - return Argument(System.SRHelper.Format(SR.ADP_KeywordNotSupported, keyword)); + return Argument(System.StringsHelper.Format(Strings.ADP_KeywordNotSupported, keyword)); } internal static ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException) { - return ADP.Argument(System.SRHelper.Format(SR.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException); + return ADP.Argument(System.StringsHelper.Format(Strings.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException); } // @@ -314,11 +314,11 @@ internal static Exception InvalidConnectionOptionValue(string key) } internal static Exception InvalidConnectionOptionValue(string key, Exception inner) { - return Argument(System.SRHelper.Format(SR.ADP_InvalidConnectionOptionValue, key), inner); + return Argument(System.StringsHelper.Format(Strings.ADP_InvalidConnectionOptionValue, key), inner); } static internal InvalidOperationException InvalidDataDirectory() { - InvalidOperationException e = new InvalidOperationException(SR.ADP_InvalidDataDirectory); + InvalidOperationException e = new InvalidOperationException(Strings.ADP_InvalidDataDirectory); return e; } @@ -327,23 +327,23 @@ static internal InvalidOperationException InvalidDataDirectory() // internal static ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection) { - return Argument(System.SRHelper.Format(SR.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name)); + return Argument(System.StringsHelper.Format(Strings.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name)); } internal static ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType) { - return ArgumentNull(parameter, System.SRHelper.Format(SR.ADP_CollectionNullValue, collection.Name, itemType.Name)); + return ArgumentNull(parameter, System.StringsHelper.Format(Strings.ADP_CollectionNullValue, collection.Name, itemType.Name)); } internal static IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count) { - return IndexOutOfRange(System.SRHelper.Format(SR.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture))); + return IndexOutOfRange(System.StringsHelper.Format(Strings.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture))); } internal static IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection) { - return IndexOutOfRange(System.SRHelper.Format(SR.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name)); + return IndexOutOfRange(System.StringsHelper.Format(Strings.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name)); } internal static InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue) { - return InvalidCast(System.SRHelper.Format(SR.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name)); + return InvalidCast(System.StringsHelper.Format(Strings.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name)); } // @@ -355,17 +355,17 @@ private static string ConnectionStateMsg(ConnectionState state) { case (ConnectionState.Closed): case (ConnectionState.Connecting | ConnectionState.Broken): // treated the same as closed - return SR.ADP_ConnectionStateMsg_Closed; + return Strings.ADP_ConnectionStateMsg_Closed; case (ConnectionState.Connecting): - return SR.ADP_ConnectionStateMsg_Connecting; + return Strings.ADP_ConnectionStateMsg_Connecting; case (ConnectionState.Open): - return SR.ADP_ConnectionStateMsg_Open; + return Strings.ADP_ConnectionStateMsg_Open; case (ConnectionState.Open | ConnectionState.Executing): - return SR.ADP_ConnectionStateMsg_OpenExecuting; + return Strings.ADP_ConnectionStateMsg_OpenExecuting; case (ConnectionState.Open | ConnectionState.Fetching): - return SR.ADP_ConnectionStateMsg_OpenFetching; + return Strings.ADP_ConnectionStateMsg_OpenFetching; default: - return System.SRHelper.Format(SR.ADP_ConnectionStateMsg, state.ToString()); + return System.StringsHelper.Format(Strings.ADP_ConnectionStateMsg, state.ToString()); } } @@ -374,7 +374,7 @@ private static string ConnectionStateMsg(ConnectionState state) // internal static Exception StreamClosed([CallerMemberName] string method = "") { - return InvalidOperation(System.SRHelper.Format(SR.ADP_StreamClosed, method)); + return InvalidOperation(System.StringsHelper.Format(Strings.ADP_StreamClosed, method)); } internal static string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString) @@ -424,11 +424,11 @@ static internal string BuildMultiPartName(string[] strings) // internal static ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection) { - return Argument(System.SRHelper.Format(SR.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); + return Argument(System.StringsHelper.Format(Strings.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); } internal static ArgumentException ParametersIsParent(Type parameterType, ICollection collection) { - return Argument(System.SRHelper.Format(SR.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); + return Argument(System.StringsHelper.Format(Strings.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name)); } @@ -474,7 +474,7 @@ internal enum InternalErrorCode internal static Exception InternalError(InternalErrorCode internalError) { - return InvalidOperation(System.SRHelper.Format(SR.ADP_InternalProviderError, (int)internalError)); + return InvalidOperation(System.StringsHelper.Format(Strings.ADP_InternalProviderError, (int)internalError)); } // @@ -482,23 +482,23 @@ internal static Exception InternalError(InternalErrorCode internalError) // internal static Exception DataReaderClosed([CallerMemberName] string method = "") { - return InvalidOperation(System.SRHelper.Format(SR.ADP_DataReaderClosed, method)); + return InvalidOperation(System.StringsHelper.Format(Strings.ADP_DataReaderClosed, method)); } internal static ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName) { - return ArgumentOutOfRange(System.SRHelper.Format(SR.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName); + return ArgumentOutOfRange(System.StringsHelper.Format(Strings.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName); } internal static ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName) { - return ArgumentOutOfRange(System.SRHelper.Format(SR.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName); + return ArgumentOutOfRange(System.StringsHelper.Format(Strings.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName); } internal static IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex) { - return IndexOutOfRange(System.SRHelper.Format(SR.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture))); + return IndexOutOfRange(System.StringsHelper.Format(Strings.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture))); } internal static Exception InvalidDataLength(long length) { - return IndexOutOfRange(System.SRHelper.Format(SR.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture))); + return IndexOutOfRange(System.StringsHelper.Format(Strings.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture))); } internal static bool CompareInsensitiveInvariant(string strvalue, string strconst) => @@ -520,7 +520,7 @@ internal static bool IsNull(object value) internal static Exception InvalidSeekOrigin(string parameterName) { - return ArgumentOutOfRange(SR.ADP_InvalidSeekOrigin, parameterName); + return ArgumentOutOfRange(Strings.ADP_InvalidSeekOrigin, parameterName); } internal static void SetCurrentTransaction(Transaction transaction) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/SQLResource.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/SQLResource.cs index 0647326e69..9d4a0818cb 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/SQLResource.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/SQLResource.cs @@ -8,64 +8,64 @@ namespace Microsoft.Data.SqlTypes { internal static class SQLResource { - internal static string NullString => SR.SqlMisc_NullString; + internal static string NullString => Strings.SqlMisc_NullString; - internal static string MessageString => SR.SqlMisc_MessageString; + internal static string MessageString => Strings.SqlMisc_MessageString; - internal static string ArithOverflowMessage => SR.SqlMisc_ArithOverflowMessage; + internal static string ArithOverflowMessage => Strings.SqlMisc_ArithOverflowMessage; - internal static string DivideByZeroMessage => SR.SqlMisc_DivideByZeroMessage; + internal static string DivideByZeroMessage => Strings.SqlMisc_DivideByZeroMessage; - internal static string NullValueMessage => SR.SqlMisc_NullValueMessage; + internal static string NullValueMessage => Strings.SqlMisc_NullValueMessage; - internal static string TruncationMessage => SR.SqlMisc_TruncationMessage; + internal static string TruncationMessage => Strings.SqlMisc_TruncationMessage; - internal static string DateTimeOverflowMessage => SR.SqlMisc_DateTimeOverflowMessage; + internal static string DateTimeOverflowMessage => Strings.SqlMisc_DateTimeOverflowMessage; - internal static string ConcatDiffCollationMessage => SR.SqlMisc_ConcatDiffCollationMessage; + internal static string ConcatDiffCollationMessage => Strings.SqlMisc_ConcatDiffCollationMessage; - internal static string CompareDiffCollationMessage => SR.SqlMisc_CompareDiffCollationMessage; + internal static string CompareDiffCollationMessage => Strings.SqlMisc_CompareDiffCollationMessage; - internal static string InvalidFlagMessage => SR.SqlMisc_InvalidFlagMessage; + internal static string InvalidFlagMessage => Strings.SqlMisc_InvalidFlagMessage; - internal static string NumeToDecOverflowMessage => SR.SqlMisc_NumeToDecOverflowMessage; + internal static string NumeToDecOverflowMessage => Strings.SqlMisc_NumeToDecOverflowMessage; - internal static string ConversionOverflowMessage => SR.SqlMisc_ConversionOverflowMessage; + internal static string ConversionOverflowMessage => Strings.SqlMisc_ConversionOverflowMessage; - internal static string InvalidDateTimeMessage => SR.SqlMisc_InvalidDateTimeMessage; + internal static string InvalidDateTimeMessage => Strings.SqlMisc_InvalidDateTimeMessage; - internal static string TimeZoneSpecifiedMessage => SR.SqlMisc_TimeZoneSpecifiedMessage; + internal static string TimeZoneSpecifiedMessage => Strings.SqlMisc_TimeZoneSpecifiedMessage; - internal static string InvalidArraySizeMessage => SR.SqlMisc_InvalidArraySizeMessage; + internal static string InvalidArraySizeMessage => Strings.SqlMisc_InvalidArraySizeMessage; - internal static string InvalidPrecScaleMessage => SR.SqlMisc_InvalidPrecScaleMessage; + internal static string InvalidPrecScaleMessage => Strings.SqlMisc_InvalidPrecScaleMessage; - internal static string FormatMessage => SR.SqlMisc_FormatMessage; + internal static string FormatMessage => Strings.SqlMisc_FormatMessage; - internal static string NotFilledMessage => SR.SqlMisc_NotFilledMessage; + internal static string NotFilledMessage => Strings.SqlMisc_NotFilledMessage; - internal static string AlreadyFilledMessage => SR.SqlMisc_AlreadyFilledMessage; + internal static string AlreadyFilledMessage => Strings.SqlMisc_AlreadyFilledMessage; - internal static string ClosedXmlReaderMessage => SR.SqlMisc_ClosedXmlReaderMessage; + internal static string ClosedXmlReaderMessage => Strings.SqlMisc_ClosedXmlReaderMessage; internal static string InvalidOpStreamClosed(string method) { - return System.SRHelper.Format(SR.SqlMisc_InvalidOpStreamClosed, method); + return System.StringsHelper.Format(Strings.SqlMisc_InvalidOpStreamClosed, method); } internal static string InvalidOpStreamNonWritable(string method) { - return System.SRHelper.Format(SR.SqlMisc_InvalidOpStreamNonWritable, method); + return System.StringsHelper.Format(Strings.SqlMisc_InvalidOpStreamNonWritable, method); } internal static string InvalidOpStreamNonReadable(string method) { - return System.SRHelper.Format(SR.SqlMisc_InvalidOpStreamNonReadable, method); + return System.StringsHelper.Format(Strings.SqlMisc_InvalidOpStreamNonReadable, method); } internal static string InvalidOpStreamNonSeekable(string method) { - return System.SRHelper.Format(SR.SqlMisc_InvalidOpStreamNonSeekable, method); + return System.StringsHelper.Format(Strings.SqlMisc_InvalidOpStreamNonSeekable, method); } } // SqlResource } // namespace System diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs index 74ed1b5d61..a759af1db0 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs @@ -28,7 +28,7 @@ internal static partial class NegotiateStreamPal internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext) { - throw new PlatformNotSupportedException(SR.net_nego_server_not_supported); + throw new PlatformNotSupportedException(Strings.net_nego_server_not_supported); } internal static string QueryContextAuthenticationPackage(SafeDeleteContext securityContext) @@ -227,14 +227,14 @@ internal static SecurityStatusPal InitializeSecurityContext( // TODO (Issue #3718): The second buffer can contain a channel binding which is not supported if ((null != inSecurityBufferArray) && (inSecurityBufferArray.Length > 1)) { - throw new PlatformNotSupportedException(SR.net_nego_channel_binding_not_supported); + throw new PlatformNotSupportedException(Strings.net_nego_channel_binding_not_supported); } SafeFreeNegoCredentials negoCredentialsHandle = (SafeFreeNegoCredentials)credentialsHandle; if (negoCredentialsHandle.IsDefault && string.IsNullOrEmpty(spn)) { - throw new PlatformNotSupportedException(SR.net_nego_not_supported_empty_target_with_defaultcreds); + throw new PlatformNotSupportedException(Strings.net_nego_not_supported_empty_target_with_defaultcreds); } SecurityStatusPal status = EstablishSecurityContext( @@ -252,7 +252,7 @@ internal static SecurityStatusPal InitializeSecurityContext( ContextFlagsPal mask = ContextFlagsPal.Confidentiality; if ((requestedContextFlags & mask) != (contextFlags & mask)) { - throw new PlatformNotSupportedException(SR.net_nego_protection_level_not_supported); + throw new PlatformNotSupportedException(Strings.net_nego_protection_level_not_supported); } } @@ -267,7 +267,7 @@ internal static SecurityStatusPal AcceptSecurityContext( SecurityBuffer outSecurityBuffer, ref ContextFlagsPal contextFlags) { - throw new PlatformNotSupportedException(SR.net_nego_server_not_supported); + throw new PlatformNotSupportedException(Strings.net_nego_server_not_supported); } internal static Win32Exception CreateExceptionFromError(SecurityStatusPal statusCode) @@ -290,7 +290,7 @@ internal static SafeFreeCredentials AcquireCredentialsHandle(string package, boo { if (isServer) { - throw new PlatformNotSupportedException(SR.net_nego_server_not_supported); + throw new PlatformNotSupportedException(Strings.net_nego_server_not_supported); } bool isEmptyCredential = string.IsNullOrWhiteSpace(credential.UserName) || @@ -299,7 +299,7 @@ internal static SafeFreeCredentials AcquireCredentialsHandle(string package, boo if (ntlmOnly && isEmptyCredential) { // NTLM authentication is not possible with default credentials which are no-op - throw new PlatformNotSupportedException(SR.net_ntlm_not_possible_default_cred); + throw new PlatformNotSupportedException(Strings.net_ntlm_not_possible_default_cred); } try diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs index 961086a6fe..58bf635657 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs @@ -40,7 +40,7 @@ internal static unsafe SafeFreeCredentials AcquireCredentialsHandle(string packa if (result != Interop.SECURITY_STATUS.OK) { if (NetEventSource.IsEnabled) - NetEventSource.Error(null, System.SRHelper.Format(SR.net_log_operation_failed_with_error, nameof(Interop.SspiCli.SspiEncodeStringsAsAuthIdentity), $"0x{(int)result:X}")); + NetEventSource.Error(null, System.StringsHelper.Format(Strings.net_log_operation_failed_with_error, nameof(Interop.SspiCli.SspiEncodeStringsAsAuthIdentity), $"0x{(int)result:X}")); throw new Win32Exception((int)result); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj index 7d6f362461..9232078830 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj @@ -2,7 +2,7 @@ Microsoft.Data.SqlClient netcoreapp2.1;netcoreapp3.1;netstandard2.0 - SR.PlatformNotSupported_DataSqlClient + Strings.PlatformNotSupported_DataSqlClient $(OS) true true @@ -710,12 +710,12 @@ - + True True - SR.resx + Strings.resx - + @@ -744,9 +744,9 @@ - + ResXFileCodeGenerator - SR.Designer.cs + Strings.Designer.cs System diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/AdapterUtil.SqlClient.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/AdapterUtil.SqlClient.cs index 9f891ff04c..2c66613ca0 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/AdapterUtil.SqlClient.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/AdapterUtil.SqlClient.cs @@ -74,7 +74,7 @@ internal static TypeLoadException TypeLoad(string error) } internal static PlatformNotSupportedException DbTypeNotSupported(string dbType) { - PlatformNotSupportedException e = new PlatformNotSupportedException(System.SRHelper.GetString(SR.SQL_DbTypeNotSupportedOnThisPlatform, dbType)); + PlatformNotSupportedException e = new PlatformNotSupportedException(System.StringsHelper.GetString(Strings.SQL_DbTypeNotSupportedOnThisPlatform, dbType)); return e; } internal static InvalidCastException InvalidCast() @@ -100,12 +100,12 @@ internal static ObjectDisposedException ObjectDisposed(object instance) internal static Exception DataTableDoesNotExist(string collectionName) { - return Argument(System.SRHelper.GetString(SR.MDF_DataTableDoesNotExist, collectionName)); + return Argument(System.StringsHelper.GetString(Strings.MDF_DataTableDoesNotExist, collectionName)); } internal static InvalidOperationException MethodCalledTwice(string method) { - InvalidOperationException e = new InvalidOperationException(System.SRHelper.GetString(SR.ADP_CalledTwice, method)); + InvalidOperationException e = new InvalidOperationException(System.StringsHelper.GetString(Strings.ADP_CalledTwice, method)); return e; } @@ -166,7 +166,7 @@ internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterD internal static Exception TooManyRestrictions(string collectionName) { - return Argument(System.SRHelper.GetString(SR.MDF_TooManyRestrictions, collectionName)); + return Argument(System.StringsHelper.GetString(Strings.MDF_TooManyRestrictions, collectionName)); } @@ -192,7 +192,7 @@ internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSour // internal static ArgumentException InvalidMinMaxPoolSizeValues() { - return ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidMinMaxPoolSizeValues)); + return ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidMinMaxPoolSizeValues)); } @@ -201,7 +201,7 @@ internal static ArgumentException InvalidMinMaxPoolSizeValues() // internal static InvalidOperationException NoConnectionString() { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_NoConnectionString)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_NoConnectionString)); } internal static Exception MethodNotImplemented([CallerMemberName] string methodName = "") @@ -211,7 +211,7 @@ internal static Exception MethodNotImplemented([CallerMemberName] string methodN internal static Exception QueryFailed(string collectionName, Exception e) { - return InvalidOperation(System.SRHelper.GetString(SR.MDF_QueryFailed, collectionName), e); + return InvalidOperation(System.StringsHelper.GetString(Strings.MDF_QueryFailed, collectionName), e); } @@ -220,11 +220,11 @@ internal static Exception QueryFailed(string collectionName, Exception e) // internal static Exception InvalidConnectionOptionValueLength(string key, int limit) { - return Argument(System.SRHelper.GetString(SR.ADP_InvalidConnectionOptionValueLength, key, limit)); + return Argument(System.StringsHelper.GetString(Strings.ADP_InvalidConnectionOptionValueLength, key, limit)); } internal static Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey) { - return Argument(System.SRHelper.GetString(SR.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey)); + return Argument(System.StringsHelper.GetString(Strings.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey)); } @@ -233,12 +233,12 @@ internal static Exception MissingConnectionOptionValue(string key, string requir // internal static Exception PooledOpenTimeout() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.ADP_PooledOpenTimeout)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.ADP_PooledOpenTimeout)); } internal static Exception NonPooledOpenTimeout() { - return ADP.TimeoutException(System.SRHelper.GetString(SR.ADP_NonPooledOpenTimeout)); + return ADP.TimeoutException(System.StringsHelper.GetString(Strings.ADP_NonPooledOpenTimeout)); } // @@ -246,31 +246,31 @@ internal static Exception NonPooledOpenTimeout() // internal static InvalidOperationException TransactionConnectionMismatch() { - return Provider(System.SRHelper.GetString(SR.ADP_TransactionConnectionMismatch)); + return Provider(System.StringsHelper.GetString(Strings.ADP_TransactionConnectionMismatch)); } internal static InvalidOperationException TransactionRequired(string method) { - return Provider(System.SRHelper.GetString(SR.ADP_TransactionRequired, method)); + return Provider(System.StringsHelper.GetString(Strings.ADP_TransactionRequired, method)); } internal static Exception CommandTextRequired(string method) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_CommandTextRequired, method)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_CommandTextRequired, method)); } internal static Exception NoColumns() { - return Argument(System.SRHelper.GetString(SR.MDF_NoColumns)); + return Argument(System.StringsHelper.GetString(Strings.MDF_NoColumns)); } internal static InvalidOperationException ConnectionRequired(string method) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_ConnectionRequired, method)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_ConnectionRequired, method)); } internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state))); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state))); } internal static Exception OpenReaderExists(bool marsOn) @@ -280,7 +280,7 @@ internal static Exception OpenReaderExists(bool marsOn) internal static Exception OpenReaderExists(Exception e, bool marsOn) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_OpenReaderExists, marsOn ? ADP.Command : ADP.Connection), e); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_OpenReaderExists, marsOn ? ADP.Command : ADP.Connection), e); } @@ -289,22 +289,22 @@ internal static Exception OpenReaderExists(Exception e, bool marsOn) // internal static Exception NonSeqByteAccess(long badIndex, long currIndex, string method) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method)); } internal static Exception InvalidXml() { - return Argument(System.SRHelper.GetString(SR.MDF_InvalidXml)); + return Argument(System.StringsHelper.GetString(Strings.MDF_InvalidXml)); } internal static Exception NegativeParameter(string parameterName) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_NegativeParameter, parameterName)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_NegativeParameter, parameterName)); } internal static Exception InvalidXmlMissingColumn(string collectionName, string columnName) { - return Argument(System.SRHelper.GetString(SR.MDF_InvalidXmlMissingColumn, collectionName, columnName)); + return Argument(System.StringsHelper.GetString(Strings.MDF_InvalidXmlMissingColumn, collectionName, columnName)); } // @@ -312,22 +312,22 @@ internal static Exception InvalidXmlMissingColumn(string collectionName, string // internal static Exception InvalidMetaDataValue() { - return ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidMetaDataValue)); + return ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidMetaDataValue)); } internal static InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture))); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture))); } internal static Exception InvalidXmlInvalidValue(string collectionName, string columnName) { - return Argument(System.SRHelper.GetString(SR.MDF_InvalidXmlInvalidValue, collectionName, columnName)); + return Argument(System.StringsHelper.GetString(Strings.MDF_InvalidXmlInvalidValue, collectionName, columnName)); } internal static Exception CollectionNameIsNotUnique(string collectionName) { - return Argument(System.SRHelper.GetString(SR.MDF_CollectionNameISNotUnique, collectionName)); + return Argument(System.StringsHelper.GetString(Strings.MDF_CollectionNameISNotUnique, collectionName)); } @@ -336,60 +336,60 @@ internal static Exception CollectionNameIsNotUnique(string collectionName) // internal static Exception InvalidCommandTimeout(int value, [CallerMemberName] string property = "") { - return Argument(System.SRHelper.GetString(SR.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), property); + return Argument(System.StringsHelper.GetString(Strings.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), property); } internal static Exception UninitializedParameterSize(int index, Type dataType) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name)); } internal static Exception UnableToBuildCollection(string collectionName) { - return Argument(System.SRHelper.GetString(SR.MDF_UnableToBuildCollection, collectionName)); + return Argument(System.StringsHelper.GetString(Strings.MDF_UnableToBuildCollection, collectionName)); } internal static Exception PrepareParameterType(DbCommand cmd) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_PrepareParameterType, cmd.GetType().Name)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_PrepareParameterType, cmd.GetType().Name)); } internal static Exception UndefinedCollection(string collectionName) { - return Argument(System.SRHelper.GetString(SR.MDF_UndefinedCollection, collectionName)); + return Argument(System.StringsHelper.GetString(Strings.MDF_UndefinedCollection, collectionName)); } internal static Exception UnsupportedVersion(string collectionName) { - return Argument(System.SRHelper.GetString(SR.MDF_UnsupportedVersion, collectionName)); + return Argument(System.StringsHelper.GetString(Strings.MDF_UnsupportedVersion, collectionName)); } internal static Exception AmbiguousCollectionName(string collectionName) { - return Argument(System.SRHelper.GetString(SR.MDF_AmbiguousCollectionName, collectionName)); + return Argument(System.StringsHelper.GetString(Strings.MDF_AmbiguousCollectionName, collectionName)); } internal static Exception PrepareParameterSize(DbCommand cmd) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_PrepareParameterSize, cmd.GetType().Name)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_PrepareParameterSize, cmd.GetType().Name)); } internal static Exception PrepareParameterScale(DbCommand cmd, string type) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_PrepareParameterScale, cmd.GetType().Name, type)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_PrepareParameterScale, cmd.GetType().Name, type)); } internal static Exception MissingDataSourceInformationColumn() { - return Argument(System.SRHelper.GetString(SR.MDF_MissingDataSourceInformationColumn)); + return Argument(System.StringsHelper.GetString(Strings.MDF_MissingDataSourceInformationColumn)); } internal static Exception IncorrectNumberOfDataSourceInformationRows() { - return Argument(System.SRHelper.GetString(SR.MDF_IncorrectNumberOfDataSourceInformationRows)); + return Argument(System.StringsHelper.GetString(Strings.MDF_IncorrectNumberOfDataSourceInformationRows)); } internal static Exception MismatchedAsyncResult(string expectedMethod, string gotMethod) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_MismatchedAsyncResult, expectedMethod, gotMethod)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_MismatchedAsyncResult, expectedMethod, gotMethod)); } // @@ -397,27 +397,27 @@ internal static Exception MismatchedAsyncResult(string expectedMethod, string go // internal static Exception ClosedConnectionError() { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_ClosedConnectionError)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_ClosedConnectionError)); } internal static Exception ConnectionAlreadyOpen(ConnectionState state) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state))); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state))); } internal static Exception TransactionPresent() { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_TransactionPresent)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_TransactionPresent)); } internal static Exception LocalTransactionPresent() { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_LocalTransactionPresent)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_LocalTransactionPresent)); } internal static Exception OpenConnectionPropertySet(string property, ConnectionState state) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state))); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state))); } internal static Exception EmptyDatabaseName() { - return Argument(System.SRHelper.GetString(SR.ADP_EmptyDatabaseName)); + return Argument(System.StringsHelper.GetString(Strings.ADP_EmptyDatabaseName)); } internal enum ConnectionError @@ -430,27 +430,27 @@ internal enum ConnectionError internal static Exception MissingRestrictionColumn() { - return Argument(System.SRHelper.GetString(SR.MDF_MissingRestrictionColumn)); + return Argument(System.StringsHelper.GetString(Strings.MDF_MissingRestrictionColumn)); } internal static Exception InternalConnectionError(ConnectionError internalError) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_InternalConnectionError, (int)internalError)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_InternalConnectionError, (int)internalError)); } internal static Exception InvalidConnectRetryCountValue() { - return Argument(System.SRHelper.GetString(SR.SQLCR_InvalidConnectRetryCountValue)); + return Argument(System.StringsHelper.GetString(Strings.SQLCR_InvalidConnectRetryCountValue)); } internal static Exception MissingRestrictionRow() { - return Argument(System.SRHelper.GetString(SR.MDF_MissingRestrictionRow)); + return Argument(System.StringsHelper.GetString(Strings.MDF_MissingRestrictionRow)); } internal static Exception InvalidConnectRetryIntervalValue() { - return Argument(System.SRHelper.GetString(SR.SQLCR_InvalidConnectRetryIntervalValue)); + return Argument(System.StringsHelper.GetString(Strings.SQLCR_InvalidConnectRetryIntervalValue)); } // @@ -458,7 +458,7 @@ internal static Exception InvalidConnectRetryIntervalValue() // internal static InvalidOperationException AsyncOperationPending() { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_PendingAsyncOperation)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_PendingAsyncOperation)); } // @@ -466,50 +466,50 @@ internal static InvalidOperationException AsyncOperationPending() // internal static IOException ErrorReadingFromStream(Exception internalException) { - return IO(System.SRHelper.GetString(SR.SqlMisc_StreamErrorMessage), internalException); + return IO(System.StringsHelper.GetString(Strings.SqlMisc_StreamErrorMessage), internalException); } internal static ArgumentException InvalidDataType(TypeCode typecode) { - return Argument(System.SRHelper.GetString(SR.ADP_InvalidDataType, typecode.ToString())); + return Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataType, typecode.ToString())); } internal static ArgumentException UnknownDataType(Type dataType) { - return Argument(System.SRHelper.GetString(SR.ADP_UnknownDataType, dataType.FullName)); + return Argument(System.StringsHelper.GetString(Strings.ADP_UnknownDataType, dataType.FullName)); } internal static ArgumentException DbTypeNotSupported(DbType type, Type enumtype) { - return Argument(System.SRHelper.GetString(SR.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name)); + return Argument(System.StringsHelper.GetString(Strings.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name)); } internal static ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode) { - return Argument(System.SRHelper.GetString(SR.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName)); + return Argument(System.StringsHelper.GetString(Strings.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName)); } internal static ArgumentException InvalidOffsetValue(int value) { - return Argument(System.SRHelper.GetString(SR.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture))); + return Argument(System.StringsHelper.GetString(Strings.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture))); } internal static ArgumentException InvalidSizeValue(int value) { - return Argument(System.SRHelper.GetString(SR.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture))); + return Argument(System.StringsHelper.GetString(Strings.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture))); } internal static ArgumentException ParameterValueOutOfRange(decimal value) { - return ADP.Argument(System.SRHelper.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null))); + return ADP.Argument(System.StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null))); } internal static ArgumentException ParameterValueOutOfRange(SqlDecimal value) { - return ADP.Argument(System.SRHelper.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString())); + return ADP.Argument(System.StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, value.ToString())); } internal static ArgumentException ParameterValueOutOfRange(String value) { - return ADP.Argument(System.SRHelper.GetString(SR.ADP_ParameterValueOutOfRange, value)); + return ADP.Argument(System.StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, value)); } internal static ArgumentException VersionDoesNotSupportDataType(string typeName) { - return Argument(System.SRHelper.GetString(SR.ADP_VersionDoesNotSupportDataType, typeName)); + return Argument(System.StringsHelper.GetString(Strings.ADP_VersionDoesNotSupportDataType, typeName)); } internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner) { @@ -517,7 +517,7 @@ internal static Exception ParameterConversionFailed(object value, Type destType, Debug.Assert(null != inner, "null inner on conversion failure"); Exception e; - string message = System.SRHelper.GetString(SR.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); + string message = System.StringsHelper.GetString(Strings.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); if (inner is ArgumentException) { e = new ArgumentException(message, inner); @@ -572,11 +572,11 @@ internal static Exception InvalidParameterType(DbParameterCollection collection, // internal static Exception ParallelTransactionsNotSupported(DbConnection obj) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_ParallelTransactionsNotSupported, obj.GetType().Name)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_ParallelTransactionsNotSupported, obj.GetType().Name)); } internal static Exception TransactionZombied(DbTransaction obj) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_TransactionZombied, obj.GetType().Name)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_TransactionZombied, obj.GetType().Name)); } // global constant strings @@ -754,10 +754,10 @@ internal static Version GetAssemblyVersion() } - internal static readonly string[] AzureSqlServerEndpoints = {System.SRHelper.GetString(SR.AZURESQL_GenericEndpoint), - System.SRHelper.GetString(SR.AZURESQL_GermanEndpoint), - System.SRHelper.GetString(SR.AZURESQL_UsGovEndpoint), - System.SRHelper.GetString(SR.AZURESQL_ChinaEndpoint)}; + internal static readonly string[] AzureSqlServerEndpoints = {System.StringsHelper.GetString(Strings.AZURESQL_GenericEndpoint), + System.StringsHelper.GetString(Strings.AZURESQL_GermanEndpoint), + System.StringsHelper.GetString(Strings.AZURESQL_UsGovEndpoint), + System.StringsHelper.GetString(Strings.AZURESQL_ChinaEndpoint)}; // This method assumes dataSource parameter is in TCP connection string format. internal static bool IsAzureSqlServerEndpoint(string dataSource) @@ -809,21 +809,21 @@ internal static ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion internal static ArgumentException SingleValuedProperty(string propertyName, string value) { - ArgumentException e = new ArgumentException(System.SRHelper.GetString(SR.ADP_SingleValuedProperty, propertyName, value)); + ArgumentException e = new ArgumentException(System.StringsHelper.GetString(Strings.ADP_SingleValuedProperty, propertyName, value)); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2) { - ArgumentException e = new ArgumentException(System.SRHelper.GetString(SR.ADP_DoubleValuedProperty, propertyName, value1, value2)); + ArgumentException e = new ArgumentException(System.StringsHelper.GetString(Strings.ADP_DoubleValuedProperty, propertyName, value1, value2)); TraceExceptionAsReturnValue(e); return e; } internal static ArgumentException InvalidPrefixSuffix() { - ArgumentException e = new ArgumentException(System.SRHelper.GetString(SR.ADP_InvalidPrefixSuffix)); + ArgumentException e = new ArgumentException(System.StringsHelper.GetString(Strings.ADP_InvalidPrefixSuffix)); TraceExceptionAsReturnValue(e); return e; } @@ -850,19 +850,19 @@ internal static ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandB internal static ArgumentException BadParameterName(string parameterName) { - ArgumentException e = new ArgumentException(System.SRHelper.GetString(SR.ADP_BadParameterName, parameterName)); + ArgumentException e = new ArgumentException(System.StringsHelper.GetString(Strings.ADP_BadParameterName, parameterName)); TraceExceptionAsReturnValue(e); return e; } internal static Exception DeriveParametersNotSupported(IDbCommand value) { - return DataAdapter(System.SRHelper.GetString(SR.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString())); + return DataAdapter(System.StringsHelper.GetString(Strings.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString())); } internal static Exception NoStoredProcedureExists(string sproc) { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_NoStoredProcedureExists, sproc)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_NoStoredProcedureExists, sproc)); } // @@ -870,7 +870,7 @@ internal static Exception NoStoredProcedureExists(string sproc) // internal static InvalidOperationException TransactionCompletedButNotDisposed() { - return Provider(System.SRHelper.GetString(SR.ADP_TransactionCompletedButNotDisposed)); + return Provider(System.StringsHelper.GetString(Strings.ADP_TransactionCompletedButNotDisposed)); } internal static ArgumentOutOfRangeException InvalidUserDefinedTypeSerializationFormat(Microsoft.Data.SqlClient.Server.Format value) @@ -892,50 +892,50 @@ internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, s internal static ArgumentException InvalidArgumentLength(string argumentName, int limit) { - return Argument(System.SRHelper.GetString(SR.ADP_InvalidArgumentLength, argumentName, limit)); + return Argument(System.StringsHelper.GetString(Strings.ADP_InvalidArgumentLength, argumentName, limit)); } internal static ArgumentException MustBeReadOnly(string argumentName) { - return Argument(System.SRHelper.GetString(SR.ADP_MustBeReadOnly, argumentName)); + return Argument(System.StringsHelper.GetString(Strings.ADP_MustBeReadOnly, argumentName)); } internal static InvalidOperationException InvalidMixedUsageOfSecureAndClearCredential() { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_InvalidMixedUsageOfSecureAndClearCredential)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureAndClearCredential)); } internal static ArgumentException InvalidMixedArgumentOfSecureAndClearCredential() { - return Argument(System.SRHelper.GetString(SR.ADP_InvalidMixedUsageOfSecureAndClearCredential)); + return Argument(System.StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureAndClearCredential)); } internal static InvalidOperationException InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity() { - return InvalidOperation(System.SRHelper.GetString(SR.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity)); + return InvalidOperation(System.StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity)); } internal static ArgumentException InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity() { - return Argument(System.SRHelper.GetString(SR.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity)); + return Argument(System.StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity)); } internal static InvalidOperationException InvalidMixedUsageOfAccessTokenAndIntegratedSecurity() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndIntegratedSecurity)); } static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndUserIDPassword() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndUserIDPassword)); } static internal InvalidOperationException InvalidMixedUsageOfAccessTokenAndAuthentication() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.ADP_InvalidMixedUsageOfAccessTokenAndAuthentication)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfAccessTokenAndAuthentication)); } static internal Exception InvalidMixedUsageOfCredentialAndAccessToken() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.ADP_InvalidMixedUsageOfCredentialAndAccessToken)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.ADP_InvalidMixedUsageOfCredentialAndAccessToken)); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs index 905e3b8de5..e7613a4616 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs @@ -52,7 +52,7 @@ internal static ArgumentException _Argument(string error) } public static Exception InvalidOffsetLength() { - return _Argument(SRHelper.GetString(SR.Data_InvalidOffsetLength)); + return _Argument(StringsHelper.GetString(Strings.Data_InvalidOffsetLength)); } }// ExceptionBuilder } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/OperationAbortedException.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/OperationAbortedException.cs index cea0c3f747..ea94e5405b 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/OperationAbortedException.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/OperationAbortedException.cs @@ -26,11 +26,11 @@ internal static OperationAbortedException Aborted(Exception inner) OperationAbortedException e; if (inner == null) { - e = new OperationAbortedException(SR.ADP_OperationAborted, null); + e = new OperationAbortedException(Strings.ADP_OperationAborted, null); } else { - e = new OperationAbortedException(SR.ADP_OperationAbortedExceptionMessage, inner); + e = new OperationAbortedException(Strings.ADP_OperationAbortedExceptionMessage, inner); } return e; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.NetCoreApp.cs index 4a461b0532..b41ef407bf 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.NetCoreApp.cs @@ -111,7 +111,7 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell } else { - throw new AlwaysEncryptedAttestationException(SR.FailToCreateEnclaveSession); + throw new AlwaysEncryptedAttestationException(Strings.FailToCreateEnclaveSession); } } } @@ -215,7 +215,7 @@ public AzureAttestationInfo(byte[] attestationInfo) } catch (Exception exception) { - throw new AlwaysEncryptedAttestationException(String.Format(SR.FailToParseAttestationInfo, exception.Message)); + throw new AlwaysEncryptedAttestationException(String.Format(Strings.FailToParseAttestationInfo, exception.Message)); } } } @@ -277,7 +277,7 @@ internal byte[] PrepareAttestationParameters(string attestationUrl, byte[] attes } else { - throw new AlwaysEncryptedAttestationException(SR.FailToCreateEnclaveSession); + throw new AlwaysEncryptedAttestationException(Strings.FailToCreateEnclaveSession); } } @@ -313,7 +313,7 @@ private void VerifyAzureAttestationInfo(string attestationUrl, EnclaveType encla if (!isSignatureValid) { - throw new AlwaysEncryptedAttestationException(String.Format(SR.AttestationTokenSignatureValidationFailed, exceptionMessage)); + throw new AlwaysEncryptedAttestationException(String.Format(Strings.AttestationTokenSignatureValidationFailed, exceptionMessage)); } // Validate claims in the token @@ -349,7 +349,7 @@ private OpenIdConnectConfiguration GetOpenIdConfigForSigningKeys(string url, boo } catch (Exception exception) { - throw new AlwaysEncryptedAttestationException(String.Format(SR.GetAttestationTokenSigningKeysFailed, GetInnerMostExceptionMessage(exception)), exception); + throw new AlwaysEncryptedAttestationException(String.Format(Strings.GetAttestationTokenSigningKeysFailed, GetInnerMostExceptionMessage(exception)), exception); } OpenIdConnectConfigurationCache.Add(url, openIdConnectConfig, DateTime.UtcNow.AddDays(1)); @@ -416,7 +416,7 @@ private bool VerifyTokenSignature(string attestationToken, string tokenIssuerUrl } catch (SecurityTokenExpiredException securityException) { - throw new AlwaysEncryptedAttestationException(SR.ExpiredAttestationToken, securityException); + throw new AlwaysEncryptedAttestationException(Strings.ExpiredAttestationToken, securityException); } catch (SecurityTokenValidationException securityTokenException) { @@ -428,7 +428,7 @@ private bool VerifyTokenSignature(string attestationToken, string tokenIssuerUrl } catch (Exception exception) { - throw new AlwaysEncryptedAttestationException(String.Format(SR.InvalidAttestationToken, GetInnerMostExceptionMessage(exception))); + throw new AlwaysEncryptedAttestationException(String.Format(Strings.InvalidAttestationToken, GetInnerMostExceptionMessage(exception))); } return isSignatureValid; @@ -447,7 +447,7 @@ private byte[] ComputeSHA256(byte[] data) } catch (Exception argumentException) { - throw new AlwaysEncryptedAttestationException(SR.InvalidArgumentToSHA256, argumentException); + throw new AlwaysEncryptedAttestationException(Strings.InvalidArgumentToSHA256, argumentException); } return result; } @@ -464,7 +464,7 @@ private void ValidateAttestationClaims(EnclaveType enclaveType, string attestati } catch (ArgumentException argumentException) { - throw new AlwaysEncryptedAttestationException(String.Format(SR.FailToParseAttestationToken, argumentException.Message)); + throw new AlwaysEncryptedAttestationException(String.Format(Strings.FailToParseAttestationToken, argumentException.Message)); } // Get all the claims from the token @@ -492,7 +492,7 @@ private void ValidateClaim(Dictionary claims, string claimName, bool hasClaim = claims.TryGetValue(claimName, out claimData); if (!hasClaim) { - throw new AlwaysEncryptedAttestationException(String.Format(SR.MissingClaimInAttestationToken, claimName)); + throw new AlwaysEncryptedAttestationException(String.Format(Strings.MissingClaimInAttestationToken, claimName)); } // Get the Base64Url of the actual data and compare it with claim @@ -503,13 +503,13 @@ private void ValidateClaim(Dictionary claims, string claimName, } catch (Exception) { - throw new AlwaysEncryptedAttestationException(SR.InvalidArgumentToBase64UrlDecoder); + throw new AlwaysEncryptedAttestationException(Strings.InvalidArgumentToBase64UrlDecoder); } bool hasValidClaim = String.Equals(encodedActualData, claimData, StringComparison.Ordinal); if (!hasValidClaim) { - throw new AlwaysEncryptedAttestationException(String.Format(SR.InvalidClaimInAttestationToken, claimName, claimData)); + throw new AlwaysEncryptedAttestationException(String.Format(Strings.InvalidClaimInAttestationToken, claimName, claimData)); } } @@ -534,7 +534,7 @@ private byte[] GetSharedSecret(EnclavePublicKey enclavePublicKey, byte[] nonce, { if (!rsacng.VerifyData(enclaveDHInfo.PublicKey, enclaveDHInfo.PublicKeySignature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) { - throw new ArgumentException(SR.GetSharedSecretFailed); + throw new ArgumentException(Strings.GetSharedSecretFailed); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveSessionCache.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveSessionCache.NetCoreApp.cs index 1445918d37..5cf0590d06 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveSessionCache.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveSessionCache.NetCoreApp.cs @@ -45,7 +45,7 @@ internal void InvalidateSession(string serverName, string enclaveAttestationUrl, SqlEnclaveSession enclaveSessionRemoved = enclaveMemoryCache.Remove(cacheKey) as SqlEnclaveSession; if (enclaveSessionRemoved == null) { - throw new InvalidOperationException(SR.EnclaveSessionInvalidationFailed); + throw new InvalidOperationException(Strings.EnclaveSessionInvalidationFailed); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Common.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Common.cs index c448789a51..834fa09628 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Common.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Common.cs @@ -39,7 +39,7 @@ private static LocalDBFormatMessageDelegate LocalDBFormatMessage // SNI checks for LocalDBFormatMessage during DLL loading, so it is practically impossible to get this error. int hResult = Marshal.GetLastWin32Error(); SqlClientEventSource.Log.TraceEvent(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); - throw CreateLocalDBException(errorMessage: SR.LocalDB_MethodNotFound); + throw CreateLocalDBException(errorMessage: Strings.LocalDB_MethodNotFound); } s_localDBFormatMessage = Marshal.GetDelegateForFunctionPointer(functionAddr); } @@ -83,12 +83,12 @@ internal static string GetLocalDBMessage(int hrCode) if (hResult >= 0) return buffer.ToString(); else - return string.Format(CultureInfo.CurrentCulture, "{0} (0x{1:X}).", SR.LocalDB_UnobtainableMessage, hResult); + return string.Format(CultureInfo.CurrentCulture, "{0} (0x{1:X}).", Strings.LocalDB_UnobtainableMessage, hResult); } } catch (SqlException exc) { - return string.Format(CultureInfo.CurrentCulture, "{0} ({1}).", SR.LocalDB_UnobtainableMessage, exc.Message); + return string.Format(CultureInfo.CurrentCulture, "{0} ({1}).", Strings.LocalDB_UnobtainableMessage, exc.Message); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Unix.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Unix.cs index 02258e6c29..ff85256c56 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Unix.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Unix.cs @@ -9,6 +9,6 @@ namespace Microsoft.Data internal static partial class LocalDBAPI { internal static string GetLocalDBMessage(int hrCode) => - throw new PlatformNotSupportedException(SR.LocalDBNotSupported); // LocalDB is not available for Unix and hence it cannot be supported. + throw new PlatformNotSupportedException(Strings.LocalDBNotSupported); // LocalDB is not available for Unix and hence it cannot be supported. } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs index 2c50c2ba3a..d4b3a73133 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs @@ -30,7 +30,7 @@ private static IntPtr UserInstanceDLLHandle { SNINativeMethodWrapper.SNI_Error sniError; SNINativeMethodWrapper.SNIGetLastError(out sniError); - throw CreateLocalDBException(errorMessage: SRHelper.GetString("LocalDB_FailedGetDLLHandle"), sniError: (int)sniError.sniError); + throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_FailedGetDLLHandle"), sniError: (int)sniError.sniError); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.uap.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.uap.cs index f40574502f..9ed10f0fcc 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.uap.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.uap.cs @@ -9,6 +9,6 @@ namespace System.Data internal static partial class LocalDBAPI { private static IntPtr LoadProcAddress() => - throw new PlatformNotSupportedException(SR.LocalDBNotSupported); // No Registry support on UAP + throw new PlatformNotSupportedException(Strings.LocalDBNotSupported); // No Registry support on UAP } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Unix.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Unix.cs index 6840e9207d..a9b235d47c 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Unix.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Unix.cs @@ -10,7 +10,7 @@ internal class LocalDB { internal static string GetLocalDBConnectionString(string localDbInstance) { - throw new PlatformNotSupportedException(SR.LocalDBNotSupported); // LocalDB is not available for Unix and hence it cannot be supported. + throw new PlatformNotSupportedException(Strings.LocalDBNotSupported); // LocalDB is not available for Unix and hence it cannot be supported. } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.uap.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.uap.cs index c8c35aef29..e764375802 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.uap.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.uap.cs @@ -8,7 +8,7 @@ internal class LocalDB { internal static string GetLocalDBConnectionString(string localDbInstance) { - throw new PlatformNotSupportedException(SR.LocalDBNotSupported); // No Registry support on UAP + throw new PlatformNotSupportedException(Strings.LocalDBNotSupported); // No Registry support on UAP } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/InvalidUdtException.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/InvalidUdtException.cs index 228f1b7adc..c15bee4e08 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/InvalidUdtException.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/InvalidUdtException.cs @@ -41,8 +41,8 @@ public override void GetObjectData(SerializationInfo si, StreamingContext contex internal static InvalidUdtException Create(Type udtType, string resourceReason) { - string reason = SRHelper.GetString(resourceReason); - string message = SRHelper.GetString(SR.SqlUdt_InvalidUdtMessage, udtType.FullName, reason); + string reason = StringsHelper.GetString(resourceReason); + string message = StringsHelper.GetString(Strings.SqlUdt_InvalidUdtMessage, udtType.FullName, reason); InvalidUdtException e = new InvalidUdtException(message); ADP.TraceExceptionAsReturnValue(e); return e; diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlMetaData.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlMetaData.cs index 28210ab548..8a5b0a722a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlMetaData.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlMetaData.cs @@ -502,49 +502,49 @@ private void Construct(string name, SqlDbType dbType, long maxLength, bool useSe if (SqlDbType.Char == dbType) { if (maxLength > x_lServerMaxANSI || maxLength < 0) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); lLocale = CultureInfo.CurrentCulture.LCID; } else if (SqlDbType.VarChar == dbType) { if ((maxLength > x_lServerMaxANSI || maxLength < 0) && maxLength != Max) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); lLocale = CultureInfo.CurrentCulture.LCID; } else if (SqlDbType.NChar == dbType) { if (maxLength > x_lServerMaxUnicode || maxLength < 0) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); lLocale = CultureInfo.CurrentCulture.LCID; } else if (SqlDbType.NVarChar == dbType) { if ((maxLength > x_lServerMaxUnicode || maxLength < 0) && maxLength != Max) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); lLocale = CultureInfo.CurrentCulture.LCID; } else if (SqlDbType.NText == dbType || SqlDbType.Text == dbType) { // old-style lobs only allowed with Max length if (SqlMetaData.Max != maxLength) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); lLocale = CultureInfo.CurrentCulture.LCID; } else if (SqlDbType.Binary == dbType) { if (maxLength > x_lServerMaxBinary || maxLength < 0) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); } else if (SqlDbType.VarBinary == dbType) { if ((maxLength > x_lServerMaxBinary || maxLength < 0) && maxLength != Max) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); } else if (SqlDbType.Image == dbType) { // old-style lobs only allowed with Max length if (SqlMetaData.Max != maxLength) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); } else throw SQL.InvalidSqlDbTypeForConstructor(dbType); @@ -579,28 +579,28 @@ private void Construct(string name, if (SqlDbType.Char == dbType) { if (maxLength > x_lServerMaxANSI || maxLength < 0) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); } else if (SqlDbType.VarChar == dbType) { if ((maxLength > x_lServerMaxANSI || maxLength < 0) && maxLength != Max) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); } else if (SqlDbType.NChar == dbType) { if (maxLength > x_lServerMaxUnicode || maxLength < 0) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); } else if (SqlDbType.NVarChar == dbType) { if ((maxLength > x_lServerMaxUnicode || maxLength < 0) && maxLength != Max) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); } else if (SqlDbType.NText == dbType || SqlDbType.Text == dbType) { // old-style lobs only allowed with Max length if (SqlMetaData.Max != maxLength) - throw ADP.Argument(System.SRHelper.GetString(SR.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.ADP_InvalidDataLength2, maxLength.ToString(CultureInfo.InvariantCulture)), nameof(maxLength)); } else throw SQL.InvalidSqlDbTypeForConstructor(dbType); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlNorm.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlNorm.cs index 399fff8a25..9ab047679c 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlNorm.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlNorm.cs @@ -238,7 +238,7 @@ internal static Normalizer GetNormalizer(Type t) n = new BinaryOrderedUdtNormalizer(t, false); } if (n == null) - throw new Exception(SRHelper.GetString(SR.SQL_CannotCreateNormalizer, t.FullName)); + throw new Exception(StringsHelper.GetString(Strings.SQL_CannotCreateNormalizer, t.FullName)); n._skipNormalize = false; return n; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlSer.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlSer.cs index 7ca46bb8c3..a0bbc2a463 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlSer.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlSer.cs @@ -146,7 +146,7 @@ internal static SqlUserDefinedTypeAttribute GetUdtAttribute(Type t) } else { - throw InvalidUdtException.Create(t, SR.SqlUdtReason_NoUdtAttribute); + throw InvalidUdtException.Create(t, Strings.SqlUdtReason_NoUdtAttribute); } return udtAttr; } @@ -242,7 +242,7 @@ public DummyStream() private void DontDoIt() { - throw new Exception(SRHelper.GetString(SR.Sql_InternalError)); + throw new Exception(StringsHelper.GetString(Strings.Sql_InternalError)); } public override bool CanRead => false; diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlUserDefinedAggregateAttribute.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlUserDefinedAggregateAttribute.cs index e74878e2e7..12c1149428 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlUserDefinedAggregateAttribute.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Server/SqlUserDefinedAggregateAttribute.cs @@ -56,7 +56,7 @@ public int MaxByteSize // MaxByteSize of -1 means 2GB and is valid, as well as 0 to MaxByteSizeValue if (value < -1 || value > MaxByteSizeValue) { - throw ADP.ArgumentOutOfRange(SRHelper.GetString(SR.SQLUDT_MaxByteSizeValue), nameof(MaxByteSize), value); + throw ADP.ArgumentOutOfRange(StringsHelper.GetString(Strings.SQLUDT_MaxByteSizeValue), nameof(MaxByteSize), value); } _maxByteSize = value; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs index 542af35688..811816f1e6 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs @@ -92,7 +92,7 @@ public override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellma } else { - throw new AlwaysEncryptedAttestationException(SR.FailToCreateEnclaveSession); + throw new AlwaysEncryptedAttestationException(Strings.FailToCreateEnclaveSession); } } } 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 f27482f792..75b5fb04a3 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 @@ -476,7 +476,7 @@ private string CreateInitialQuery() string[] parts; try { - parts = MultipartIdentifier.ParseMultipartIdentifier(this.DestinationTableName, "[\"", "]\"", SR.SQL_BulkCopyDestinationTableName, true); + parts = MultipartIdentifier.ParseMultipartIdentifier(this.DestinationTableName, "[\"", "]\"", Strings.SQL_BulkCopyDestinationTableName, true); } catch (Exception e) { @@ -597,7 +597,7 @@ private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet i throw SQL.BulkLoadNoCollation(); } - string[] parts = MultipartIdentifier.ParseMultipartIdentifier(this.DestinationTableName, "[\"", "]\"", SR.SQL_BulkCopyDestinationTableName, true); + string[] parts = MultipartIdentifier.ParseMultipartIdentifier(this.DestinationTableName, "[\"", "]\"", Strings.SQL_BulkCopyDestinationTableName, true); updateBulkCommandText.AppendFormat("insert bulk {0} (", ADP.BuildMultiPartName(parts)); int nmatched = 0; // Number of columns that match and are accepted int nrejected = 0; // Number of columns that match but were rejected 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 8c7d707b41..3049feb963 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 @@ -2793,7 +2793,7 @@ internal void DeriveParameters() ValidateCommand(false /*not async*/, nameof(DeriveParameters)); // Use common parser for SqlClient and OleDb - parse into 4 parts - Server, Catalog, Schema, ProcedureName - string[] parsedSProc = MultipartIdentifier.ParseMultipartIdentifier(CommandText, "[\"", "]\"", SR.SQL_SqlCommandCommandText, false); + string[] parsedSProc = MultipartIdentifier.ParseMultipartIdentifier(CommandText, "[\"", "]\"", Strings.SQL_SqlCommandCommandText, false); if (null == parsedSProc[3] || string.IsNullOrEmpty(parsedSProc[3])) { throw ADP.NoStoredProcedureExists(CommandText); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlFileStream.Unsupported.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlFileStream.Unsupported.cs index 19771d0a52..8821657bf7 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlFileStream.Unsupported.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlFileStream.Unsupported.cs @@ -13,38 +13,38 @@ public sealed partial class SqlFileStream : System.IO.Stream /// public SqlFileStream(string path, byte[] transactionContext, FileAccess access) { - throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); + throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } /// public SqlFileStream(string path, byte[] transactionContext, FileAccess access, FileOptions options, Int64 allocationSize) { - throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); + throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } /// - public string Name { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } } + public string Name { get { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } } /// - public byte[] TransactionContext { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } } + public byte[] TransactionContext { get { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } } /// - public override bool CanRead { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } } + public override bool CanRead { get { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } } /// - public override bool CanSeek { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } } + public override bool CanSeek { get { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } } /// - public override bool CanWrite { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } } + public override bool CanWrite { get { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } } /// - public override long Length { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } } + public override long Length { get { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } } /// - public override long Position { get { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } set { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } } + public override long Position { get { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } set { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } } /// - public override void Flush() { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } + public override void Flush() { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } /// - public override int Read(byte[] buffer, int offset, int count) { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } + public override int Read(byte[] buffer, int offset, int count) { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } /// - public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } + public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } /// - public override void SetLength(long value) { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } + public override void SetLength(long value) { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } /// - public override void Write(byte[] buffer, int offset, int count) { throw new PlatformNotSupportedException(SR.SqlFileStream_NotSupported); } + public override void Write(byte[] buffer, int offset, int count) { throw new PlatformNotSupportedException(Strings.SqlFileStream_NotSupported); } } } 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 3111fee442..912596b55d 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 @@ -2424,10 +2424,10 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) SqlClientEventSource.Log.TraceEvent(" {0}", msalException.ErrorCode); // Error[0] SqlErrorCollection sqlErs = new SqlErrorCollection(); - sqlErs.Add(new SqlError(0, (byte)0x00, (byte)TdsEnums.MIN_ERROR_CLASS, ConnectionOptions.DataSource, SRHelper.GetString(SR.SQL_MSALFailure, username, ConnectionOptions.Authentication.ToString("G")), ActiveDirectoryAuthentication.MSALGetAccessTokenFunctionName, 0)); + sqlErs.Add(new SqlError(0, (byte)0x00, (byte)TdsEnums.MIN_ERROR_CLASS, ConnectionOptions.DataSource, StringsHelper.GetString(Strings.SQL_MSALFailure, username, ConnectionOptions.Authentication.ToString("G")), ActiveDirectoryAuthentication.MSALGetAccessTokenFunctionName, 0)); // Error[1] - string errorMessage1 = SRHelper.GetString(SR.SQL_MSALInnerException, msalException.ErrorCode); + string errorMessage1 = StringsHelper.GetString(Strings.SQL_MSALInnerException, msalException.ErrorCode); sqlErs.Add(new SqlError(0, (byte)0x00, (byte)TdsEnums.MIN_ERROR_CLASS, ConnectionOptions.DataSource, errorMessage1, ActiveDirectoryAuthentication.MSALGetAccessTokenFunctionName, 0)); // Error[2] diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlParameter.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlParameter.cs index e646a4fbd7..08029b8a7a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlParameter.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlParameter.cs @@ -1979,7 +1979,7 @@ internal static string[] ParseTypeName(string typeName, bool isUdtTypeName) try { - string errorMsg = isUdtTypeName ? SR.SQL_UDTTypeName : SR.SQL_TypeName; + string errorMsg = isUdtTypeName ? Strings.SQL_UDTTypeName : Strings.SQL_TypeName; return MultipartIdentifier.ParseMultipartIdentifier(typeName, "[\"", "]\"", '.', 3, true, errorMsg, true); } catch (ArgumentException) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlStatistics.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlStatistics.cs index 32e06b2df0..f6abfd7354 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlStatistics.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlStatistics.cs @@ -291,11 +291,11 @@ private void ValidateCopyToArguments(Array array, int arrayIndex) if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) - throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); + throw new ArgumentException(Strings.Arg_RankMultiDimNotSupported); if (arrayIndex < 0) - throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(arrayIndex), Strings.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - arrayIndex < Count) - throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); + throw new ArgumentException(Strings.Arg_ArrayPlusOffTooSmall); } private sealed class Collection : ICollection diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlUdtInfo.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlUdtInfo.cs index fd95ad195f..7a02ba83fd 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlUdtInfo.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlUdtInfo.cs @@ -32,7 +32,7 @@ internal static SqlUdtInfo GetFromType(Type target) SqlUdtInfo udtAttr = TryGetFromType(target); if (udtAttr == null) { - throw InvalidUdtException.Create(target, SR.SqlUdtReason_NoUdtAttribute); + throw InvalidUdtException.Create(target, Strings.SqlUdtReason_NoUdtAttribute); } return udtAttr; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlUtil.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlUtil.cs index 37b42b7512..ebfe96b769 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlUtil.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlUtil.cs @@ -246,7 +246,7 @@ internal static class SQL // internal static Exception CannotGetDTCAddress() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_CannotGetDTCAddress)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_CannotGetDTCAddress)); } internal static Exception InvalidInternalPacketSize(string str) @@ -255,119 +255,119 @@ internal static Exception InvalidInternalPacketSize(string str) } internal static Exception InvalidPacketSize() { - return ADP.ArgumentOutOfRange(System.SRHelper.GetString(SR.SQL_InvalidTDSPacketSize)); + return ADP.ArgumentOutOfRange(System.StringsHelper.GetString(Strings.SQL_InvalidTDSPacketSize)); } internal static Exception InvalidPacketSizeValue() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_InvalidPacketSizeValue)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_InvalidPacketSizeValue)); } internal static Exception InvalidSSPIPacketSize() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_InvalidSSPIPacketSize)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_InvalidSSPIPacketSize)); } internal static Exception AuthenticationAndIntegratedSecurity() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_AuthenticationAndIntegratedSecurity)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_AuthenticationAndIntegratedSecurity)); } internal static Exception IntegratedWithPassword() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_IntegratedWithPassword)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_IntegratedWithPassword)); } internal static Exception InteractiveWithPassword() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_InteractiveWithPassword)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_InteractiveWithPassword)); } internal static Exception DeviceFlowWithUsernamePassword() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_DeviceFlowWithUsernamePassword)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_DeviceFlowWithUsernamePassword)); } static internal Exception SettingIntegratedWithCredential() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_SettingIntegratedWithCredential)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_SettingIntegratedWithCredential)); } static internal Exception SettingInteractiveWithCredential() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_SettingInteractiveWithCredential)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_SettingInteractiveWithCredential)); } static internal Exception SettingDeviceFlowWithCredential() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_SettingDeviceFlowWithCredential)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_SettingDeviceFlowWithCredential)); } static internal Exception SettingCredentialWithIntegratedArgument() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_SettingCredentialWithIntegrated)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_SettingCredentialWithIntegrated)); } static internal Exception SettingCredentialWithInteractiveArgument() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_SettingCredentialWithInteractive)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_SettingCredentialWithInteractive)); } static internal Exception SettingCredentialWithDeviceFlowArgument() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_SettingCredentialWithDeviceFlow)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_SettingCredentialWithDeviceFlow)); } static internal Exception SettingCredentialWithIntegratedInvalid() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_SettingCredentialWithIntegrated)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_SettingCredentialWithIntegrated)); } static internal Exception SettingCredentialWithInteractiveInvalid() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_SettingCredentialWithInteractive)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_SettingCredentialWithInteractive)); } static internal Exception SettingCredentialWithDeviceFlowInvalid() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_SettingCredentialWithDeviceFlow)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_SettingCredentialWithDeviceFlow)); } internal static Exception NullEmptyTransactionName() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_NullEmptyTransactionName)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_NullEmptyTransactionName)); } internal static Exception UserInstanceFailoverNotCompatible() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_UserInstanceFailoverNotCompatible)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_UserInstanceFailoverNotCompatible)); } internal static Exception CredentialsNotProvided(SqlAuthenticationMethod auth) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_CredentialsNotProvided, DbConnectionStringBuilderUtil.AuthenticationTypeToString(auth))); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_CredentialsNotProvided, DbConnectionStringBuilderUtil.AuthenticationTypeToString(auth))); } internal static Exception ParsingErrorLibraryType(ParsingErrorState state, int libraryType) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ParsingErrorAuthLibraryType, ((int)state).ToString(CultureInfo.InvariantCulture), libraryType)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ParsingErrorAuthLibraryType, ((int)state).ToString(CultureInfo.InvariantCulture), libraryType)); } internal static Exception InvalidSQLServerVersionUnknown() { - return ADP.DataAdapter(System.SRHelper.GetString(SR.SQL_InvalidSQLServerVersionUnknown)); + return ADP.DataAdapter(System.StringsHelper.GetString(Strings.SQL_InvalidSQLServerVersionUnknown)); } internal static Exception SynchronousCallMayNotPend() { - return new Exception(System.SRHelper.GetString(SR.Sql_InternalError)); + return new Exception(System.StringsHelper.GetString(Strings.Sql_InternalError)); } internal static Exception ConnectionLockedForBcpEvent() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ConnectionLockedForBcpEvent)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ConnectionLockedForBcpEvent)); } internal static Exception InstanceFailure() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_InstanceFailure)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_InstanceFailure)); } internal static Exception ChangePasswordArgumentMissing(string argumentName) { - return ADP.ArgumentNull(System.SRHelper.GetString(SR.SQL_ChangePasswordArgumentMissing, argumentName)); + return ADP.ArgumentNull(System.StringsHelper.GetString(Strings.SQL_ChangePasswordArgumentMissing, argumentName)); } internal static Exception ChangePasswordConflictsWithSSPI() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_ChangePasswordConflictsWithSSPI)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_ChangePasswordConflictsWithSSPI)); } internal static Exception ChangePasswordRequiresYukon() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ChangePasswordRequiresYukon)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ChangePasswordRequiresYukon)); } internal static Exception ChangePasswordUseOfUnallowedKey(string key) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ChangePasswordUseOfUnallowedKey, key)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ChangePasswordUseOfUnallowedKey, key)); } internal static Exception GlobalizationInvariantModeNotSupported() { - return ADP.NotSupported(System.SRHelper.GetString(SR.SQL_GlobalizationInvariantModeNotSupported)); + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SQL_GlobalizationInvariantModeNotSupported)); } // @@ -375,97 +375,97 @@ internal static Exception GlobalizationInvariantModeNotSupported() // internal static Exception GlobalTransactionsNotEnabled() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.GT_Disabled)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.GT_Disabled)); } internal static Exception UnknownSysTxIsolationLevel(System.Transactions.IsolationLevel isolationLevel) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_UnknownSysTxIsolationLevel, isolationLevel.ToString())); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_UnknownSysTxIsolationLevel, isolationLevel.ToString())); } internal static Exception InvalidPartnerConfiguration(string server, string database) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_InvalidPartnerConfiguration, server, database)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_InvalidPartnerConfiguration, server, database)); } internal static Exception BatchedUpdateColumnEncryptionSettingMismatch() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_BatchedUpdateColumnEncryptionSettingMismatch, "SqlCommandColumnEncryptionSetting", "SelectCommand", "InsertCommand", "UpdateCommand", "DeleteCommand")); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_BatchedUpdateColumnEncryptionSettingMismatch, "SqlCommandColumnEncryptionSetting", "SelectCommand", "InsertCommand", "UpdateCommand", "DeleteCommand")); } internal static Exception MARSUnsupportedOnConnection() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_MarsUnsupportedOnConnection)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_MarsUnsupportedOnConnection)); } internal static Exception CannotModifyPropertyAsyncOperationInProgress([CallerMemberName] string property = "") { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_CannotModifyPropertyAsyncOperationInProgress, property)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_CannotModifyPropertyAsyncOperationInProgress, property)); } internal static Exception NonLocalSSEInstance() { - return ADP.NotSupported(System.SRHelper.GetString(SR.SQL_NonLocalSSEInstance)); + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SQL_NonLocalSSEInstance)); } // SQL.ActiveDirectoryAuth // internal static Exception UnsupportedAuthentication(string authentication) { - return ADP.NotSupported(System.SRHelper.GetString(SR.SQL_UnsupportedAuthentication, authentication)); + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SQL_UnsupportedAuthentication, authentication)); } internal static Exception UnsupportedSqlAuthenticationMethod(SqlAuthenticationMethod authentication) { - return ADP.NotSupported(System.SRHelper.GetString(SR.SQL_UnsupportedSqlAuthenticationMethod, authentication)); + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SQL_UnsupportedSqlAuthenticationMethod, authentication)); } internal static Exception UnsupportedAuthenticationSpecified(SqlAuthenticationMethod authentication) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_UnsupportedAuthenticationSpecified, authentication)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_UnsupportedAuthenticationSpecified, authentication)); } internal static Exception CannotCreateAuthProvider(string authentication, string type, Exception e) { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_CannotCreateAuthProvider, authentication, type), e); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_CannotCreateAuthProvider, authentication, type), e); } internal static Exception CannotCreateSqlAuthInitializer(string type, Exception e) { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_CannotCreateAuthInitializer, type), e); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_CannotCreateAuthInitializer, type), e); } internal static Exception CannotInitializeAuthProvider(string type, Exception e) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_CannotInitializeAuthProvider, type), e); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_CannotInitializeAuthProvider, type), e); } internal static Exception UnsupportedAuthenticationByProvider(string authentication, string type) { - return ADP.NotSupported(System.SRHelper.GetString(SR.SQL_UnsupportedAuthenticationByProvider, type, authentication)); + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SQL_UnsupportedAuthenticationByProvider, type, authentication)); } internal static Exception CannotFindAuthProvider(string authentication) { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_CannotFindAuthProvider, authentication)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_CannotFindAuthProvider, authentication)); } internal static Exception CannotGetAuthProviderConfig(Exception e) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_CannotGetAuthProviderConfig), e); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_CannotGetAuthProviderConfig), e); } internal static Exception ParameterCannotBeEmpty(string paramName) { - return ADP.ArgumentNull(System.SRHelper.GetString(SR.SQL_ParameterCannotBeEmpty, paramName)); + return ADP.ArgumentNull(System.StringsHelper.GetString(Strings.SQL_ParameterCannotBeEmpty, paramName)); } internal static Exception ActiveDirectoryInteractiveTimeout() { - return ADP.TimeoutException(SR.SQL_Timeout_Active_Directory_Interactive_Authentication); + return ADP.TimeoutException(Strings.SQL_Timeout_Active_Directory_Interactive_Authentication); } internal static Exception ActiveDirectoryDeviceFlowTimeout() { - return ADP.TimeoutException(SR.SQL_Timeout_Active_Directory_DeviceFlow_Authentication); + return ADP.TimeoutException(Strings.SQL_Timeout_Active_Directory_DeviceFlow_Authentication); } @@ -475,7 +475,7 @@ internal static Exception ActiveDirectoryDeviceFlowTimeout() internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, int value) { - return ADP.ArgumentOutOfRange(System.SRHelper.GetString(SR.SQL_NotSupportedEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name); + return ADP.ArgumentOutOfRange(System.StringsHelper.GetString(Strings.SQL_NotSupportedEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name); } internal static ArgumentOutOfRangeException NotSupportedCommandType(CommandType value) @@ -521,23 +521,23 @@ internal static ArgumentOutOfRangeException NotSupportedIsolationLevel(System.Da internal static Exception OperationCancelled() { - Exception exception = ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_OperationCancelled)); + Exception exception = ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_OperationCancelled)); return exception; } internal static Exception PendingBeginXXXExists() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_PendingBeginXXXExists)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_PendingBeginXXXExists)); } internal static ArgumentOutOfRangeException InvalidSqlDependencyTimeout(string param) { - return ADP.ArgumentOutOfRange(System.SRHelper.GetString(SR.SqlDependency_InvalidTimeout), param); + return ADP.ArgumentOutOfRange(System.StringsHelper.GetString(Strings.SqlDependency_InvalidTimeout), param); } internal static Exception NonXmlResult() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_NonXmlResult)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_NonXmlResult)); } // @@ -545,27 +545,27 @@ internal static Exception NonXmlResult() // internal static Exception InvalidUdt3PartNameFormat() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_InvalidUdt3PartNameFormat)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_InvalidUdt3PartNameFormat)); } internal static Exception InvalidParameterTypeNameFormat() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_InvalidParameterTypeNameFormat)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_InvalidParameterTypeNameFormat)); } internal static Exception InvalidParameterNameLength(string value) { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_InvalidParameterNameLength, value)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_InvalidParameterNameLength, value)); } internal static Exception PrecisionValueOutOfRange(byte precision) { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_PrecisionValueOutOfRange, precision.ToString(CultureInfo.InvariantCulture))); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_PrecisionValueOutOfRange, precision.ToString(CultureInfo.InvariantCulture))); } internal static Exception ScaleValueOutOfRange(byte scale) { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_ScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture))); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_ScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture))); } internal static Exception TimeScaleValueOutOfRange(byte scale) { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_TimeScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture))); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_TimeScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture))); } internal static Exception InvalidSqlDbType(SqlDbType value) { @@ -573,41 +573,41 @@ internal static Exception InvalidSqlDbType(SqlDbType value) } internal static Exception UnsupportedTVPOutputParameter(ParameterDirection direction, string paramName) { - return ADP.NotSupported(System.SRHelper.GetString(SR.SqlParameter_UnsupportedTVPOutputParameter, + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SqlParameter_UnsupportedTVPOutputParameter, direction.ToString(), paramName)); } internal static Exception DBNullNotSupportedForTVPValues(string paramName) { - return ADP.NotSupported(System.SRHelper.GetString(SR.SqlParameter_DBNullNotSupportedForTVP, paramName)); + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SqlParameter_DBNullNotSupportedForTVP, paramName)); } internal static Exception UnexpectedTypeNameForNonStructParams(string paramName) { - return ADP.NotSupported(System.SRHelper.GetString(SR.SqlParameter_UnexpectedTypeNameForNonStruct, paramName)); + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SqlParameter_UnexpectedTypeNameForNonStruct, paramName)); } internal static Exception ParameterInvalidVariant(string paramName) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ParameterInvalidVariant, paramName)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ParameterInvalidVariant, paramName)); } internal static Exception MustSetTypeNameForParam(string paramType, string paramName) { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_ParameterTypeNameRequired, paramType, paramName)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_ParameterTypeNameRequired, paramType, paramName)); } internal static Exception NullSchemaTableDataTypeNotSupported(string columnName) { - return ADP.Argument(System.SRHelper.GetString(SR.NullSchemaTableDataTypeNotSupported, columnName)); + return ADP.Argument(System.StringsHelper.GetString(Strings.NullSchemaTableDataTypeNotSupported, columnName)); } internal static Exception InvalidSchemaTableOrdinals() { - return ADP.Argument(System.SRHelper.GetString(SR.InvalidSchemaTableOrdinals)); + return ADP.Argument(System.StringsHelper.GetString(Strings.InvalidSchemaTableOrdinals)); } internal static Exception EnumeratedRecordMetaDataChanged(string fieldName, int recordNumber) { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_EnumeratedRecordMetaDataChanged, fieldName, recordNumber)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_EnumeratedRecordMetaDataChanged, fieldName, recordNumber)); } internal static Exception EnumeratedRecordFieldCountChanged(int recordNumber) { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_EnumeratedRecordFieldCountChanged, recordNumber)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_EnumeratedRecordFieldCountChanged, recordNumber)); } // @@ -619,59 +619,59 @@ internal static Exception EnumeratedRecordFieldCountChanged(int recordNumber) // internal static Exception InvalidTDSVersion() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_InvalidTDSVersion)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_InvalidTDSVersion)); } internal static Exception ParsingError() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ParsingError)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ParsingError)); } internal static Exception ParsingError(ParsingErrorState state) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ParsingErrorWithState, ((int)state).ToString(CultureInfo.InvariantCulture))); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ParsingErrorWithState, ((int)state).ToString(CultureInfo.InvariantCulture))); } internal static Exception ParsingError(ParsingErrorState state, Exception innerException) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ParsingErrorWithState, ((int)state).ToString(CultureInfo.InvariantCulture)), innerException); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ParsingErrorWithState, ((int)state).ToString(CultureInfo.InvariantCulture)), innerException); } internal static Exception ParsingErrorValue(ParsingErrorState state, int value) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ParsingErrorValue, ((int)state).ToString(CultureInfo.InvariantCulture), value)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ParsingErrorValue, ((int)state).ToString(CultureInfo.InvariantCulture), value)); } internal static Exception ParsingErrorFeatureId(ParsingErrorState state, int featureId) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ParsingErrorFeatureId, ((int)state).ToString(CultureInfo.InvariantCulture), featureId)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ParsingErrorFeatureId, ((int)state).ToString(CultureInfo.InvariantCulture), featureId)); } internal static Exception ParsingErrorToken(ParsingErrorState state, int token) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ParsingErrorToken, ((int)state).ToString(CultureInfo.InvariantCulture), token)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ParsingErrorToken, ((int)state).ToString(CultureInfo.InvariantCulture), token)); } internal static Exception ParsingErrorLength(ParsingErrorState state, int length) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ParsingErrorLength, ((int)state).ToString(CultureInfo.InvariantCulture), length)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ParsingErrorLength, ((int)state).ToString(CultureInfo.InvariantCulture), length)); } internal static Exception ParsingErrorStatus(ParsingErrorState state, int status) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ParsingErrorStatus, ((int)state).ToString(CultureInfo.InvariantCulture), status)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ParsingErrorStatus, ((int)state).ToString(CultureInfo.InvariantCulture), status)); } internal static Exception ParsingErrorOffset(ParsingErrorState state, int offset) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ParsingErrorOffset, ((int)state).ToString(CultureInfo.InvariantCulture), offset)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ParsingErrorOffset, ((int)state).ToString(CultureInfo.InvariantCulture), offset)); } internal static Exception MoneyOverflow(string moneyValue) { - return ADP.Overflow(System.SRHelper.GetString(SR.SQL_MoneyOverflow, moneyValue)); + return ADP.Overflow(System.StringsHelper.GetString(Strings.SQL_MoneyOverflow, moneyValue)); } internal static Exception SmallDateTimeOverflow(string datetime) { - return ADP.Overflow(System.SRHelper.GetString(SR.SQL_SmallDateTimeOverflow, datetime)); + return ADP.Overflow(System.StringsHelper.GetString(Strings.SQL_SmallDateTimeOverflow, datetime)); } internal static Exception SNIPacketAllocationFailure() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_SNIPacketAllocationFailure)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_SNIPacketAllocationFailure)); } internal static Exception TimeOverflow(string time) { - return ADP.Overflow(System.SRHelper.GetString(SR.SQL_TimeOverflow, time)); + return ADP.Overflow(System.StringsHelper.GetString(Strings.SQL_TimeOverflow, time)); } // @@ -679,47 +679,47 @@ internal static Exception TimeOverflow(string time) // internal static Exception InvalidRead() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_InvalidRead)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_InvalidRead)); } internal static Exception NonBlobColumn(string columnName) { - return ADP.InvalidCast(System.SRHelper.GetString(SR.SQL_NonBlobColumn, columnName)); + return ADP.InvalidCast(System.StringsHelper.GetString(Strings.SQL_NonBlobColumn, columnName)); } internal static Exception NonCharColumn(string columnName) { - return ADP.InvalidCast(System.SRHelper.GetString(SR.SQL_NonCharColumn, columnName)); + return ADP.InvalidCast(System.StringsHelper.GetString(Strings.SQL_NonCharColumn, columnName)); } internal static Exception StreamNotSupportOnColumnType(string columnName) { - return ADP.InvalidCast(System.SRHelper.GetString(SR.SQL_StreamNotSupportOnColumnType, columnName)); + return ADP.InvalidCast(System.StringsHelper.GetString(Strings.SQL_StreamNotSupportOnColumnType, columnName)); } internal static Exception StreamNotSupportOnEncryptedColumn(string columnName) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_StreamNotSupportOnEncryptedColumn, columnName, "Stream")); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_StreamNotSupportOnEncryptedColumn, columnName, "Stream")); } internal static Exception SequentialAccessNotSupportedOnEncryptedColumn(string columnName) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_SequentialAccessNotSupportedOnEncryptedColumn, columnName, "CommandBehavior=SequentialAccess")); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_SequentialAccessNotSupportedOnEncryptedColumn, columnName, "CommandBehavior=SequentialAccess")); } internal static Exception TextReaderNotSupportOnColumnType(string columnName) { - return ADP.InvalidCast(System.SRHelper.GetString(SR.SQL_TextReaderNotSupportOnColumnType, columnName)); + return ADP.InvalidCast(System.StringsHelper.GetString(Strings.SQL_TextReaderNotSupportOnColumnType, columnName)); } internal static Exception XmlReaderNotSupportOnColumnType(string columnName) { - return ADP.InvalidCast(System.SRHelper.GetString(SR.SQL_XmlReaderNotSupportOnColumnType, columnName)); + return ADP.InvalidCast(System.StringsHelper.GetString(Strings.SQL_XmlReaderNotSupportOnColumnType, columnName)); } internal static Exception UDTUnexpectedResult(string exceptionText) { - return ADP.TypeLoad(System.SRHelper.GetString(SR.SQLUDT_Unexpected, exceptionText)); + return ADP.TypeLoad(System.StringsHelper.GetString(Strings.SQLUDT_Unexpected, exceptionText)); } // @@ -727,42 +727,42 @@ internal static Exception UDTUnexpectedResult(string exceptionText) // internal static Exception SqlCommandHasExistingSqlNotificationRequest() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQLNotify_AlreadyHasCommand)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQLNotify_AlreadyHasCommand)); } internal static Exception SqlDepDefaultOptionsButNoStart() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlDependency_DefaultOptionsButNoStart)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlDependency_DefaultOptionsButNoStart)); } internal static Exception SqlDependencyDatabaseBrokerDisabled() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlDependency_DatabaseBrokerDisabled)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlDependency_DatabaseBrokerDisabled)); } internal static Exception SqlDependencyEventNoDuplicate() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlDependency_EventNoDuplicate)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlDependency_EventNoDuplicate)); } internal static Exception SqlDependencyDuplicateStart() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlDependency_DuplicateStart)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlDependency_DuplicateStart)); } internal static Exception SqlDependencyIdMismatch() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlDependency_IdMismatch)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlDependency_IdMismatch)); } internal static Exception SqlDependencyNoMatchingServerStart() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlDependency_NoMatchingServerStart)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlDependency_NoMatchingServerStart)); } internal static Exception SqlDependencyNoMatchingServerDatabaseStart() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlDependency_NoMatchingServerDatabaseStart)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlDependency_NoMatchingServerDatabaseStart)); } // @@ -770,7 +770,7 @@ internal static Exception SqlDependencyNoMatchingServerDatabaseStart() // internal static TransactionPromotionException PromotionFailed(Exception inner) { - TransactionPromotionException e = new TransactionPromotionException(System.SRHelper.GetString(SR.SqlDelegatedTransaction_PromotionFailed), inner); + TransactionPromotionException e = new TransactionPromotionException(System.StringsHelper.GetString(Strings.SqlDelegatedTransaction_PromotionFailed), inner); ADP.TraceExceptionAsReturnValue(e); return e; } @@ -781,30 +781,30 @@ internal static TransactionPromotionException PromotionFailed(Exception inner) // internal static Exception UnexpectedUdtTypeNameForNonUdtParams() { - return ADP.Argument(System.SRHelper.GetString(SR.SQLUDT_UnexpectedUdtTypeName)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQLUDT_UnexpectedUdtTypeName)); } internal static Exception MustSetUdtTypeNameForUdtParams() { - return ADP.Argument(System.SRHelper.GetString(SR.SQLUDT_InvalidUdtTypeName)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQLUDT_InvalidUdtTypeName)); } internal static Exception UDTInvalidSqlType(string typeName) { - return ADP.Argument(System.SRHelper.GetString(SR.SQLUDT_InvalidSqlType, typeName)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQLUDT_InvalidSqlType, typeName)); } internal static Exception UDTInvalidSize(int maxSize, int maxSupportedSize) { - throw ADP.ArgumentOutOfRange(System.SRHelper.GetString(SR.SQLUDT_InvalidSize, maxSize, maxSupportedSize)); + throw ADP.ArgumentOutOfRange(System.StringsHelper.GetString(Strings.SQLUDT_InvalidSize, maxSize, maxSupportedSize)); } internal static Exception InvalidSqlDbTypeForConstructor(SqlDbType type) { - return ADP.Argument(System.SRHelper.GetString(SR.SqlMetaData_InvalidSqlDbTypeForConstructorFormat, type.ToString())); + return ADP.Argument(System.StringsHelper.GetString(Strings.SqlMetaData_InvalidSqlDbTypeForConstructorFormat, type.ToString())); } internal static Exception NameTooLong(string parameterName) { - return ADP.Argument(System.SRHelper.GetString(SR.SqlMetaData_NameTooLong), parameterName); + return ADP.Argument(System.StringsHelper.GetString(Strings.SqlMetaData_NameTooLong), parameterName); } internal static Exception InvalidSortOrder(SortOrder order) @@ -814,40 +814,40 @@ internal static Exception InvalidSortOrder(SortOrder order) internal static Exception MustSpecifyBothSortOrderAndOrdinal(SortOrder order, int ordinal) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlMetaData_SpecifyBothSortOrderAndOrdinal, order.ToString(), ordinal)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlMetaData_SpecifyBothSortOrderAndOrdinal, order.ToString(), ordinal)); } internal static Exception UnsupportedColumnTypeForSqlProvider(string columnName, string typeName) { - return ADP.Argument(System.SRHelper.GetString(SR.SqlProvider_InvalidDataColumnType, columnName, typeName)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SqlProvider_InvalidDataColumnType, columnName, typeName)); } internal static Exception InvalidColumnMaxLength(string columnName, long maxLength) { - return ADP.Argument(System.SRHelper.GetString(SR.SqlProvider_InvalidDataColumnMaxLength, columnName, maxLength)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SqlProvider_InvalidDataColumnMaxLength, columnName, maxLength)); } internal static Exception InvalidColumnPrecScale() { - return ADP.Argument(System.SRHelper.GetString(SR.SqlMisc_InvalidPrecScaleMessage)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SqlMisc_InvalidPrecScaleMessage)); } internal static Exception NotEnoughColumnsInStructuredType() { - return ADP.Argument(System.SRHelper.GetString(SR.SqlProvider_NotEnoughColumnsInStructuredType)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SqlProvider_NotEnoughColumnsInStructuredType)); } internal static Exception DuplicateSortOrdinal(int sortOrdinal) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlProvider_DuplicateSortOrdinal, sortOrdinal)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlProvider_DuplicateSortOrdinal, sortOrdinal)); } internal static Exception MissingSortOrdinal(int sortOrdinal) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlProvider_MissingSortOrdinal, sortOrdinal)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlProvider_MissingSortOrdinal, sortOrdinal)); } internal static Exception SortOrdinalGreaterThanFieldCount(int columnOrdinal, int sortOrdinal) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlProvider_SortOrdinalGreaterThanFieldCount, sortOrdinal, columnOrdinal)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlProvider_SortOrdinalGreaterThanFieldCount, sortOrdinal, columnOrdinal)); } internal static Exception IEnumerableOfSqlDataRecordHasNoRows() { - return ADP.Argument(System.SRHelper.GetString(SR.IEnumerableOfSqlDataRecordHasNoRows)); + return ADP.Argument(System.StringsHelper.GetString(Strings.IEnumerableOfSqlDataRecordHasNoRows)); } @@ -858,11 +858,11 @@ internal static Exception IEnumerableOfSqlDataRecordHasNoRows() // internal static Exception BulkLoadMappingInaccessible() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadMappingInaccessible)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadMappingInaccessible)); } internal static Exception BulkLoadMappingsNamesOrOrdinalsOnly() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadMappingsNamesOrOrdinalsOnly)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadMappingsNamesOrOrdinalsOnly)); } internal static Exception BulkLoadCannotConvertValue(Type sourcetype, MetaType metatype, int ordinal, int rowNumber, bool isEncrypted, string columnName, string value, Exception e) { @@ -873,16 +873,16 @@ internal static Exception BulkLoadCannotConvertValue(Type sourcetype, MetaType m } if (rowNumber == -1) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadCannotConvertValueWithoutRowNo, quotedValue, sourcetype.Name, metatype.TypeName, ordinal, columnName), e); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadCannotConvertValueWithoutRowNo, quotedValue, sourcetype.Name, metatype.TypeName, ordinal, columnName), e); } else { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadCannotConvertValue, quotedValue, sourcetype.Name, metatype.TypeName, ordinal, columnName, rowNumber), e); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadCannotConvertValue, quotedValue, sourcetype.Name, metatype.TypeName, ordinal, columnName, rowNumber), e); } } internal static Exception BulkLoadNonMatchingColumnMapping() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadNonMatchingColumnMapping)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadNonMatchingColumnMapping)); } internal static Exception BulkLoadNonMatchingColumnName(string columnName) { @@ -890,79 +890,79 @@ internal static Exception BulkLoadNonMatchingColumnName(string columnName) } internal static Exception BulkLoadNonMatchingColumnName(string columnName, Exception e) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadNonMatchingColumnName, columnName), e); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadNonMatchingColumnName, columnName), e); } internal static Exception BulkLoadNullEmptyColumnName(string paramName) { - return ADP.Argument(string.Format(System.SRHelper.GetString(SR.SQL_ParameterCannotBeEmpty), paramName)); + return ADP.Argument(string.Format(System.StringsHelper.GetString(Strings.SQL_ParameterCannotBeEmpty), paramName)); } internal static Exception BulkLoadUnspecifiedSortOrder() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_BulkLoadUnspecifiedSortOrder)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_BulkLoadUnspecifiedSortOrder)); } internal static Exception BulkLoadInvalidOrderHint() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_BulkLoadInvalidOrderHint)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_BulkLoadInvalidOrderHint)); } internal static Exception BulkLoadOrderHintInvalidColumn(string columnName) { - return ADP.InvalidOperation(string.Format(System.SRHelper.GetString(SR.SQL_BulkLoadOrderHintInvalidColumn), columnName)); + return ADP.InvalidOperation(string.Format(System.StringsHelper.GetString(Strings.SQL_BulkLoadOrderHintInvalidColumn), columnName)); } internal static Exception BulkLoadOrderHintDuplicateColumn(string columnName) { - return ADP.InvalidOperation(string.Format(System.SRHelper.GetString(SR.SQL_BulkLoadOrderHintDuplicateColumn), columnName)); + return ADP.InvalidOperation(string.Format(System.StringsHelper.GetString(Strings.SQL_BulkLoadOrderHintDuplicateColumn), columnName)); } internal static Exception BulkLoadStringTooLong(string tableName, string columnName, string truncatedValue) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadStringTooLong, tableName, columnName, truncatedValue)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadStringTooLong, tableName, columnName, truncatedValue)); } internal static Exception BulkLoadInvalidVariantValue() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadInvalidVariantValue)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadInvalidVariantValue)); } internal static Exception BulkLoadInvalidTimeout(int timeout) { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_BulkLoadInvalidTimeout, timeout.ToString(CultureInfo.InvariantCulture))); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_BulkLoadInvalidTimeout, timeout.ToString(CultureInfo.InvariantCulture))); } internal static Exception BulkLoadExistingTransaction() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadExistingTransaction)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadExistingTransaction)); } internal static Exception BulkLoadNoCollation() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadNoCollation)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadNoCollation)); } internal static Exception BulkLoadConflictingTransactionOption() { - return ADP.Argument(System.SRHelper.GetString(SR.SQL_BulkLoadConflictingTransactionOption)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQL_BulkLoadConflictingTransactionOption)); } internal static Exception BulkLoadLcidMismatch(int sourceLcid, string sourceColumnName, int destinationLcid, string destinationColumnName) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.Sql_BulkLoadLcidMismatch, sourceLcid, sourceColumnName, destinationLcid, destinationColumnName)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.Sql_BulkLoadLcidMismatch, sourceLcid, sourceColumnName, destinationLcid, destinationColumnName)); } internal static Exception InvalidOperationInsideEvent() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadInvalidOperationInsideEvent)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadInvalidOperationInsideEvent)); } internal static Exception BulkLoadMissingDestinationTable() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadMissingDestinationTable)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadMissingDestinationTable)); } internal static Exception BulkLoadInvalidDestinationTable(string tableName, Exception inner) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadInvalidDestinationTable, tableName), inner); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadInvalidDestinationTable, tableName), inner); } internal static Exception BulkLoadBulkLoadNotAllowDBNull(string columnName) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadNotAllowDBNull, columnName)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadNotAllowDBNull, columnName)); } internal static Exception BulkLoadPendingOperation() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BulkLoadPendingOperation)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BulkLoadPendingOperation)); } internal static Exception InvalidTableDerivedPrecisionForTvp(string columnName, byte precision) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlParameter_InvalidTableDerivedPrecisionForTvp, precision, columnName, System.Data.SqlTypes.SqlDecimal.MaxPrecision)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlParameter_InvalidTableDerivedPrecisionForTvp, precision, columnName, System.Data.SqlTypes.SqlDecimal.MaxPrecision)); } // @@ -970,17 +970,17 @@ internal static Exception InvalidTableDerivedPrecisionForTvp(string columnName, // internal static Exception ConnectionDoomed() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_ConnectionDoomed)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_ConnectionDoomed)); } internal static Exception OpenResultCountExceeded() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_OpenResultCountExceeded)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_OpenResultCountExceeded)); } internal static Exception UnsupportedSysTxForGlobalTransactions() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_UnsupportedSysTxVersion)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_UnsupportedSysTxVersion)); } internal static readonly byte[] AttentionHeader = new byte[] { @@ -1005,7 +1005,7 @@ internal static Exception UnsupportedSysTxForGlobalTransactions() /// internal static Exception MultiSubnetFailoverWithFailoverPartner(bool serverProvidedFailoverPartner, SqlInternalConnectionTds internalConnection) { - string msg = System.SRHelper.GetString(SR.SQLMSF_FailoverPartnerNotSupported); + string msg = System.StringsHelper.GetString(Strings.SQLMSF_FailoverPartnerNotSupported); if (serverProvidedFailoverPartner) { // Replacing InvalidOperation with SQL exception @@ -1045,13 +1045,13 @@ internal static Exception MultiSubnetFailoverWithNonTcpProtocol() internal static Exception ROR_FailoverNotSupportedConnString() { - return ADP.Argument(System.SRHelper.GetString(SR.SQLROR_FailoverNotSupported)); + return ADP.Argument(System.StringsHelper.GetString(Strings.SQLROR_FailoverNotSupported)); } internal static Exception ROR_FailoverNotSupportedServer(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (System.SRHelper.GetString(SR.SQLROR_FailoverNotSupported)), "", 0)); + errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (System.StringsHelper.GetString(Strings.SQLROR_FailoverNotSupported)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; @@ -1060,7 +1060,7 @@ internal static Exception ROR_FailoverNotSupportedServer(SqlInternalConnectionTd internal static Exception ROR_RecursiveRoutingNotSupported(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (System.SRHelper.GetString(SR.SQLROR_RecursiveRoutingNotSupported)), "", 0)); + errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (System.StringsHelper.GetString(Strings.SQLROR_RecursiveRoutingNotSupported)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; @@ -1069,7 +1069,7 @@ internal static Exception ROR_RecursiveRoutingNotSupported(SqlInternalConnection internal static Exception ROR_UnexpectedRoutingInfo(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (System.SRHelper.GetString(SR.SQLROR_UnexpectedRoutingInfo)), "", 0)); + errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (System.StringsHelper.GetString(Strings.SQLROR_UnexpectedRoutingInfo)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; @@ -1078,7 +1078,7 @@ internal static Exception ROR_UnexpectedRoutingInfo(SqlInternalConnectionTds int internal static Exception ROR_InvalidRoutingInfo(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (System.SRHelper.GetString(SR.SQLROR_InvalidRoutingInfo)), "", 0)); + errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (System.StringsHelper.GetString(Strings.SQLROR_InvalidRoutingInfo)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; @@ -1087,7 +1087,7 @@ internal static Exception ROR_InvalidRoutingInfo(SqlInternalConnectionTds intern internal static Exception ROR_TimeoutAfterRoutingInfo(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (System.SRHelper.GetString(SR.SQLROR_TimeoutAfterRoutingInfo)), "", 0)); + errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (System.StringsHelper.GetString(Strings.SQLROR_TimeoutAfterRoutingInfo)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; @@ -1115,7 +1115,7 @@ internal static SqlException CR_ReconnectionCancelled() internal static Exception CR_NextAttemptWillExceedQueryTimeout(SqlException innerException, Guid connectionId) { SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, System.SRHelper.GetString(SR.SQLCR_NextAttemptWillExceedQueryTimeout), "", 0)); + errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, System.StringsHelper.GetString(Strings.SQLCR_NextAttemptWillExceedQueryTimeout), "", 0)); SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException); return exc; } @@ -1123,7 +1123,7 @@ internal static Exception CR_NextAttemptWillExceedQueryTimeout(SqlException inne internal static Exception CR_EncryptionChanged(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, System.SRHelper.GetString(SR.SQLCR_EncryptionChanged), "", 0)); + errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, System.StringsHelper.GetString(Strings.SQLCR_EncryptionChanged), "", 0)); SqlException exc = SqlException.CreateException(errors, "", internalConnection); return exc; } @@ -1131,7 +1131,7 @@ internal static Exception CR_EncryptionChanged(SqlInternalConnectionTds internal internal static SqlException CR_AllAttemptsFailed(SqlException innerException, Guid connectionId) { SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, System.SRHelper.GetString(SR.SQLCR_AllAttemptsFailed), "", 0)); + errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, System.StringsHelper.GetString(Strings.SQLCR_AllAttemptsFailed), "", 0)); SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException); return exc; } @@ -1139,7 +1139,7 @@ internal static SqlException CR_AllAttemptsFailed(SqlException innerException, G internal static SqlException CR_NoCRAckAtReconnection(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, System.SRHelper.GetString(SR.SQLCR_NoCRAckAtReconnection), "", 0)); + errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, System.StringsHelper.GetString(Strings.SQLCR_NoCRAckAtReconnection), "", 0)); SqlException exc = SqlException.CreateException(errors, "", internalConnection); return exc; } @@ -1147,7 +1147,7 @@ internal static SqlException CR_NoCRAckAtReconnection(SqlInternalConnectionTds i internal static SqlException CR_TDSVersionNotPreserved(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, System.SRHelper.GetString(SR.SQLCR_TDSVestionNotPreserved), "", 0)); + errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, System.StringsHelper.GetString(Strings.SQLCR_TDSVestionNotPreserved), "", 0)); SqlException exc = SqlException.CreateException(errors, "", internalConnection); return exc; } @@ -1155,7 +1155,7 @@ internal static SqlException CR_TDSVersionNotPreserved(SqlInternalConnectionTds internal static SqlException CR_UnrecoverableServer(Guid connectionId) { SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, System.SRHelper.GetString(SR.SQLCR_UnrecoverableServer), "", 0)); + errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, System.StringsHelper.GetString(Strings.SQLCR_UnrecoverableServer), "", 0)); SqlException exc = SqlException.CreateException(errors, "", connectionId); return exc; } @@ -1163,22 +1163,22 @@ internal static SqlException CR_UnrecoverableServer(Guid connectionId) internal static SqlException CR_UnrecoverableClient(Guid connectionId) { SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, System.SRHelper.GetString(SR.SQLCR_UnrecoverableClient), "", 0)); + errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, System.StringsHelper.GetString(Strings.SQLCR_UnrecoverableClient), "", 0)); SqlException exc = SqlException.CreateException(errors, "", connectionId); return exc; } internal static Exception StreamWriteNotSupported() { - return ADP.NotSupported(System.SRHelper.GetString(SR.SQL_StreamWriteNotSupported)); + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SQL_StreamWriteNotSupported)); } internal static Exception StreamReadNotSupported() { - return ADP.NotSupported(System.SRHelper.GetString(SR.SQL_StreamReadNotSupported)); + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SQL_StreamReadNotSupported)); } internal static Exception StreamSeekNotSupported() { - return ADP.NotSupported(System.SRHelper.GetString(SR.SQL_StreamSeekNotSupported)); + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SQL_StreamSeekNotSupported)); } internal static System.Data.SqlTypes.SqlNullValueException SqlNullValue() { @@ -1187,31 +1187,31 @@ internal static System.Data.SqlTypes.SqlNullValueException SqlNullValue() } internal static Exception SubclassMustOverride() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlMisc_SubclassMustOverride)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlMisc_SubclassMustOverride)); } // ProjectK\CoreCLR specific errors internal static Exception UnsupportedKeyword(string keyword) { - return ADP.NotSupported(System.SRHelper.GetString(SR.SQL_UnsupportedKeyword, keyword)); + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SQL_UnsupportedKeyword, keyword)); } internal static Exception NetworkLibraryKeywordNotSupported() { - return ADP.NotSupported(System.SRHelper.GetString(SR.SQL_NetworkLibraryNotSupported)); + return ADP.NotSupported(System.StringsHelper.GetString(Strings.SQL_NetworkLibraryNotSupported)); } internal static Exception UnsupportedFeatureAndToken(SqlInternalConnectionTds internalConnection, string token) { - var innerException = ADP.NotSupported(System.SRHelper.GetString(SR.SQL_UnsupportedToken, token)); + var innerException = ADP.NotSupported(System.StringsHelper.GetString(Strings.SQL_UnsupportedToken, token)); SqlErrorCollection errors = new SqlErrorCollection(); - errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, System.SRHelper.GetString(SR.SQL_UnsupportedFeature), "", 0)); + errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, System.StringsHelper.GetString(Strings.SQL_UnsupportedFeature), "", 0)); SqlException exc = SqlException.CreateException(errors, "", internalConnection, innerException); return exc; } internal static Exception BatchedUpdatesNotAvailableOnContextConnection() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.SQL_BatchedUpdatesNotAvailableOnContextConnection)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SQL_BatchedUpdatesNotAvailableOnContextConnection)); } #region Always Encrypted Errors @@ -1219,291 +1219,291 @@ internal static Exception BatchedUpdatesNotAvailableOnContextConnection() #region Always Encrypted - Certificate Store Provider Errors internal static Exception InvalidKeyEncryptionAlgorithm(string encryptionAlgorithm, string validEncryptionAlgorithm, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_InvalidKeyEncryptionAlgorithmSysErr : SR.TCE_InvalidKeyEncryptionAlgorithm; - return ADP.Argument(System.SRHelper.GetString(message, encryptionAlgorithm, validEncryptionAlgorithm), TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM); + string message = isSystemOp ? Strings.TCE_InvalidKeyEncryptionAlgorithmSysErr : Strings.TCE_InvalidKeyEncryptionAlgorithm; + return ADP.Argument(System.StringsHelper.GetString(message, encryptionAlgorithm, validEncryptionAlgorithm), TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM); } internal static Exception NullKeyEncryptionAlgorithm(bool isSystemOp) { - string message = isSystemOp ? SR.TCE_NullKeyEncryptionAlgorithmSysErr : SR.TCE_NullKeyEncryptionAlgorithm; - return ADP.ArgumentNull(TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM, System.SRHelper.GetString(message)); + string message = isSystemOp ? Strings.TCE_NullKeyEncryptionAlgorithmSysErr : Strings.TCE_NullKeyEncryptionAlgorithm; + return ADP.ArgumentNull(TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM, System.StringsHelper.GetString(message)); } internal static Exception EmptyColumnEncryptionKey() { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_EmptyColumnEncryptionKey), TdsEnums.TCE_PARAM_COLUMNENCRYPTION_KEY); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_EmptyColumnEncryptionKey), TdsEnums.TCE_PARAM_COLUMNENCRYPTION_KEY); } internal static Exception NullColumnEncryptionKey() { - return ADP.ArgumentNull(TdsEnums.TCE_PARAM_COLUMNENCRYPTION_KEY, System.SRHelper.GetString(SR.TCE_NullColumnEncryptionKey)); + return ADP.ArgumentNull(TdsEnums.TCE_PARAM_COLUMNENCRYPTION_KEY, System.StringsHelper.GetString(Strings.TCE_NullColumnEncryptionKey)); } internal static Exception EmptyEncryptedColumnEncryptionKey() { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_EmptyEncryptedColumnEncryptionKey), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_EmptyEncryptedColumnEncryptionKey), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); } internal static Exception NullEncryptedColumnEncryptionKey() { - return ADP.ArgumentNull(TdsEnums.TCE_PARAM_ENCRYPTED_CEK, System.SRHelper.GetString(SR.TCE_NullEncryptedColumnEncryptionKey)); + return ADP.ArgumentNull(TdsEnums.TCE_PARAM_ENCRYPTED_CEK, System.StringsHelper.GetString(Strings.TCE_NullEncryptedColumnEncryptionKey)); } internal static Exception LargeCertificatePathLength(int actualLength, int maxLength, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_LargeCertificatePathLengthSysErr : SR.TCE_LargeCertificatePathLength; - return ADP.Argument(System.SRHelper.GetString(message, actualLength, maxLength), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_LargeCertificatePathLengthSysErr : Strings.TCE_LargeCertificatePathLength; + return ADP.Argument(System.StringsHelper.GetString(message, actualLength, maxLength), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception NullCertificatePath(string[] validLocations, bool isSystemOp) { Debug.Assert(2 == validLocations.Length); - string message = isSystemOp ? SR.TCE_NullCertificatePathSysErr : SR.TCE_NullCertificatePath; - return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, System.SRHelper.GetString(message, validLocations[0], validLocations[1], @"/")); + string message = isSystemOp ? Strings.TCE_NullCertificatePathSysErr : Strings.TCE_NullCertificatePath; + return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, System.StringsHelper.GetString(message, validLocations[0], validLocations[1], @"/")); } internal static Exception NullCspKeyPath(bool isSystemOp) { - string message = isSystemOp ? SR.TCE_NullCspPathSysErr : SR.TCE_NullCspPath; - return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, System.SRHelper.GetString(message, @"/")); + string message = isSystemOp ? Strings.TCE_NullCspPathSysErr : Strings.TCE_NullCspPath; + return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, System.StringsHelper.GetString(message, @"/")); } internal static Exception NullCngKeyPath(bool isSystemOp) { - string message = isSystemOp ? SR.TCE_NullCngPathSysErr : SR.TCE_NullCngPath; - return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, System.SRHelper.GetString(message, @"/")); + string message = isSystemOp ? Strings.TCE_NullCngPathSysErr : Strings.TCE_NullCngPath; + return ADP.ArgumentNull(TdsEnums.TCE_PARAM_MASTERKEY_PATH, System.StringsHelper.GetString(message, @"/")); } internal static Exception InvalidCertificatePath(string actualCertificatePath, string[] validLocations, bool isSystemOp) { Debug.Assert(2 == validLocations.Length); - string message = isSystemOp ? SR.TCE_InvalidCertificatePathSysErr : SR.TCE_InvalidCertificatePath; - return ADP.Argument(System.SRHelper.GetString(message, actualCertificatePath, validLocations[0], validLocations[1], @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_InvalidCertificatePathSysErr : Strings.TCE_InvalidCertificatePath; + return ADP.Argument(System.StringsHelper.GetString(message, actualCertificatePath, validLocations[0], validLocations[1], @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception InvalidCspPath(string masterKeyPath, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_InvalidCspPathSysErr : SR.TCE_InvalidCspPath; - return ADP.Argument(System.SRHelper.GetString(message, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_InvalidCspPathSysErr : Strings.TCE_InvalidCspPath; + return ADP.Argument(System.StringsHelper.GetString(message, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception InvalidCngPath(string masterKeyPath, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_InvalidCngPathSysErr : SR.TCE_InvalidCngPath; - return ADP.Argument(System.SRHelper.GetString(message, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_InvalidCngPathSysErr : Strings.TCE_InvalidCngPath; + return ADP.Argument(System.StringsHelper.GetString(message, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception EmptyCspName(string masterKeyPath, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_EmptyCspNameSysErr : SR.TCE_EmptyCspName; - return ADP.Argument(System.SRHelper.GetString(message, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_EmptyCspNameSysErr : Strings.TCE_EmptyCspName; + return ADP.Argument(System.StringsHelper.GetString(message, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception EmptyCngName(string masterKeyPath, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_EmptyCngNameSysErr : SR.TCE_EmptyCngName; - return ADP.Argument(System.SRHelper.GetString(message, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_EmptyCngNameSysErr : Strings.TCE_EmptyCngName; + return ADP.Argument(System.StringsHelper.GetString(message, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception EmptyCspKeyId(string masterKeyPath, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_EmptyCspKeyIdSysErr : SR.TCE_EmptyCspKeyId; - return ADP.Argument(System.SRHelper.GetString(message, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_EmptyCspKeyIdSysErr : Strings.TCE_EmptyCspKeyId; + return ADP.Argument(System.StringsHelper.GetString(message, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception EmptyCngKeyId(string masterKeyPath, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_EmptyCngKeyIdSysErr : SR.TCE_EmptyCngKeyId; - return ADP.Argument(System.SRHelper.GetString(message, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_EmptyCngKeyIdSysErr : Strings.TCE_EmptyCngKeyId; + return ADP.Argument(System.StringsHelper.GetString(message, masterKeyPath, @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception InvalidCspName(string cspName, string masterKeyPath, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_InvalidCspNameSysErr : SR.TCE_InvalidCspName; - return ADP.Argument(System.SRHelper.GetString(message, cspName, masterKeyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_InvalidCspNameSysErr : Strings.TCE_InvalidCspName; + return ADP.Argument(System.StringsHelper.GetString(message, cspName, masterKeyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception InvalidCspKeyIdentifier(string keyIdentifier, string masterKeyPath, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_InvalidCspKeyIdSysErr : SR.TCE_InvalidCspKeyId; - return ADP.Argument(System.SRHelper.GetString(message, keyIdentifier, masterKeyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_InvalidCspKeyIdSysErr : Strings.TCE_InvalidCspKeyId; + return ADP.Argument(System.StringsHelper.GetString(message, keyIdentifier, masterKeyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception InvalidCngKey(string masterKeyPath, string cngProviderName, string keyIdentifier, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_InvalidCngKeySysErr : SR.TCE_InvalidCngKey; - return ADP.Argument(System.SRHelper.GetString(message, masterKeyPath, cngProviderName, keyIdentifier), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_InvalidCngKeySysErr : Strings.TCE_InvalidCngKey; + return ADP.Argument(System.StringsHelper.GetString(message, masterKeyPath, cngProviderName, keyIdentifier), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception InvalidCertificateLocation(string certificateLocation, string certificatePath, string[] validLocations, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_InvalidCertificateLocationSysErr : SR.TCE_InvalidCertificateLocation; - return ADP.Argument(System.SRHelper.GetString(message, certificateLocation, certificatePath, validLocations[0], validLocations[1], @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_InvalidCertificateLocationSysErr : Strings.TCE_InvalidCertificateLocation; + return ADP.Argument(System.StringsHelper.GetString(message, certificateLocation, certificatePath, validLocations[0], validLocations[1], @"/"), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception InvalidCertificateStore(string certificateStore, string certificatePath, string validCertificateStore, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_InvalidCertificateStoreSysErr : SR.TCE_InvalidCertificateStore; - return ADP.Argument(System.SRHelper.GetString(message, certificateStore, certificatePath, validCertificateStore), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_InvalidCertificateStoreSysErr : Strings.TCE_InvalidCertificateStore; + return ADP.Argument(System.StringsHelper.GetString(message, certificateStore, certificatePath, validCertificateStore), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception EmptyCertificateThumbprint(string certificatePath, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_EmptyCertificateThumbprintSysErr : SR.TCE_EmptyCertificateThumbprint; - return ADP.Argument(System.SRHelper.GetString(message, certificatePath), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_EmptyCertificateThumbprintSysErr : Strings.TCE_EmptyCertificateThumbprint; + return ADP.Argument(System.StringsHelper.GetString(message, certificatePath), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception CertificateNotFound(string thumbprint, string certificateLocation, string certificateStore, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_CertificateNotFoundSysErr : SR.TCE_CertificateNotFound; - return ADP.Argument(System.SRHelper.GetString(message, thumbprint, certificateLocation, certificateStore), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_CertificateNotFoundSysErr : Strings.TCE_CertificateNotFound; + return ADP.Argument(System.StringsHelper.GetString(message, thumbprint, certificateLocation, certificateStore), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } internal static Exception InvalidAlgorithmVersionInEncryptedCEK(byte actual, byte expected) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidAlgorithmVersionInEncryptedCEK, actual.ToString(@"X2"), expected.ToString(@"X2")), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidAlgorithmVersionInEncryptedCEK, actual.ToString(@"X2"), expected.ToString(@"X2")), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); } internal static Exception InvalidCiphertextLengthInEncryptedCEK(int actual, int expected, string certificateName) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidCiphertextLengthInEncryptedCEK, actual, expected, certificateName), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidCiphertextLengthInEncryptedCEK, actual, expected, certificateName), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); } internal static Exception InvalidCiphertextLengthInEncryptedCEKCsp(int actual, int expected, string masterKeyPath) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidCiphertextLengthInEncryptedCEKCsp, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidCiphertextLengthInEncryptedCEKCsp, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); } internal static Exception InvalidCiphertextLengthInEncryptedCEKCng(int actual, int expected, string masterKeyPath) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidCiphertextLengthInEncryptedCEKCng, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidCiphertextLengthInEncryptedCEKCng, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); } internal static Exception InvalidSignatureInEncryptedCEK(int actual, int expected, string masterKeyPath) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidSignatureInEncryptedCEK, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidSignatureInEncryptedCEK, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); } internal static Exception InvalidSignatureInEncryptedCEKCsp(int actual, int expected, string masterKeyPath) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidSignatureInEncryptedCEKCsp, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidSignatureInEncryptedCEKCsp, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); } internal static Exception InvalidSignatureInEncryptedCEKCng(int actual, int expected, string masterKeyPath) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidSignatureInEncryptedCEKCng, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidSignatureInEncryptedCEKCng, actual, expected, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); } internal static Exception InvalidCertificateSignature(string certificatePath) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidCertificateSignature, certificatePath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidCertificateSignature, certificatePath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); } internal static Exception InvalidSignature(string masterKeyPath) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidSignature, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidSignature, masterKeyPath), TdsEnums.TCE_PARAM_ENCRYPTED_CEK); } internal static Exception CertificateWithNoPrivateKey(string keyPath, bool isSystemOp) { - string message = isSystemOp ? SR.TCE_CertificateWithNoPrivateKeySysErr : SR.TCE_CertificateWithNoPrivateKey; - return ADP.Argument(System.SRHelper.GetString(message, keyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH); + string message = isSystemOp ? Strings.TCE_CertificateWithNoPrivateKeySysErr : Strings.TCE_CertificateWithNoPrivateKey; + return ADP.Argument(System.StringsHelper.GetString(message, keyPath), TdsEnums.TCE_PARAM_MASTERKEY_PATH); } #endregion Always Encrypted - Certificate Store Provider Errors #region Always Encrypted - Cryptographic Algorithms Error messages internal static Exception NullPlainText() { - return ADP.ArgumentNull(System.SRHelper.GetString(SR.TCE_NullPlainText)); + return ADP.ArgumentNull(System.StringsHelper.GetString(Strings.TCE_NullPlainText)); } internal static Exception NullCipherText() { - return ADP.ArgumentNull(System.SRHelper.GetString(SR.TCE_NullCipherText)); + return ADP.ArgumentNull(System.StringsHelper.GetString(Strings.TCE_NullCipherText)); } internal static Exception NullColumnEncryptionAlgorithm(string supportedAlgorithms) { - return ADP.ArgumentNull(TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM, System.SRHelper.GetString(SR.TCE_NullColumnEncryptionAlgorithm, supportedAlgorithms)); + return ADP.ArgumentNull(TdsEnums.TCE_PARAM_ENCRYPTION_ALGORITHM, System.StringsHelper.GetString(Strings.TCE_NullColumnEncryptionAlgorithm, supportedAlgorithms)); } internal static Exception NullColumnEncryptionKeySysErr() { - return ADP.ArgumentNull(TdsEnums.TCE_PARAM_ENCRYPTIONKEY, System.SRHelper.GetString(SR.TCE_NullColumnEncryptionKeySysErr)); + return ADP.ArgumentNull(TdsEnums.TCE_PARAM_ENCRYPTIONKEY, System.StringsHelper.GetString(Strings.TCE_NullColumnEncryptionKeySysErr)); } internal static Exception InvalidKeySize(string algorithmName, int actualKeylength, int expectedLength) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidKeySize, algorithmName, actualKeylength, expectedLength), TdsEnums.TCE_PARAM_ENCRYPTIONKEY); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidKeySize, algorithmName, actualKeylength, expectedLength), TdsEnums.TCE_PARAM_ENCRYPTIONKEY); } internal static Exception InvalidEncryptionType(string algorithmName, SqlClientEncryptionType encryptionType, params SqlClientEncryptionType[] validEncryptionTypes) { const string valueSeparator = @", "; - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidEncryptionType, algorithmName, encryptionType.ToString(), string.Join(valueSeparator, validEncryptionTypes.Select((validEncryptionType => @"'" + validEncryptionType + @"'")))), TdsEnums.TCE_PARAM_ENCRYPTIONTYPE); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidEncryptionType, algorithmName, encryptionType.ToString(), string.Join(valueSeparator, validEncryptionTypes.Select((validEncryptionType => @"'" + validEncryptionType + @"'")))), TdsEnums.TCE_PARAM_ENCRYPTIONTYPE); } internal static Exception InvalidCipherTextSize(int actualSize, int minimumSize) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidCipherTextSize, actualSize, minimumSize), TdsEnums.TCE_PARAM_CIPHERTEXT); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidCipherTextSize, actualSize, minimumSize), TdsEnums.TCE_PARAM_CIPHERTEXT); } internal static Exception InvalidAlgorithmVersion(byte actual, byte expected) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidAlgorithmVersion, actual.ToString(@"X2"), expected.ToString(@"X2")), TdsEnums.TCE_PARAM_CIPHERTEXT); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidAlgorithmVersion, actual.ToString(@"X2"), expected.ToString(@"X2")), TdsEnums.TCE_PARAM_CIPHERTEXT); } internal static Exception InvalidAuthenticationTag() { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidAuthenticationTag), TdsEnums.TCE_PARAM_CIPHERTEXT); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidAuthenticationTag), TdsEnums.TCE_PARAM_CIPHERTEXT); } #endregion Always Encrypted - Cryptographic Algorithms Error messages #region Always Encrypted - Errors from sp_describe_parameter_encryption internal static Exception UnexpectedDescribeParamFormatParameterMetadata() { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_UnexpectedDescribeParamFormatParameterMetadata, "sp_describe_parameter_encryption")); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_UnexpectedDescribeParamFormatParameterMetadata, "sp_describe_parameter_encryption")); } internal static Exception UnexpectedDescribeParamFormatAttestationInfo(string enclaveType) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_UnexpectedDescribeParamFormatAttestationInfo, "sp_describe_parameter_encryption", enclaveType)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_UnexpectedDescribeParamFormatAttestationInfo, "sp_describe_parameter_encryption", enclaveType)); } internal static Exception InvalidEncryptionKeyOrdinalEnclaveMetadata(int ordinal, int maxOrdinal) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_InvalidEncryptionKeyOrdinalEnclaveMetadata, ordinal, maxOrdinal)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_InvalidEncryptionKeyOrdinalEnclaveMetadata, ordinal, maxOrdinal)); } internal static Exception InvalidEncryptionKeyOrdinalParameterMetadata(int ordinal, int maxOrdinal) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_InvalidEncryptionKeyOrdinalParameterMetadata, ordinal, maxOrdinal)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_InvalidEncryptionKeyOrdinalParameterMetadata, ordinal, maxOrdinal)); } public static Exception MultipleRowsReturnedForAttestationInfo() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_MultipleRowsReturnedForAttestationInfo, "sp_describe_parameter_encryption")); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_MultipleRowsReturnedForAttestationInfo, "sp_describe_parameter_encryption")); } internal static Exception ParamEncryptionMetadataMissing(string paramName, string procedureName) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_ParamEncryptionMetaDataMissing, "sp_describe_parameter_encryption", paramName, procedureName)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_ParamEncryptionMetaDataMissing, "sp_describe_parameter_encryption", paramName, procedureName)); } internal static Exception ProcEncryptionMetadataMissing(string procedureName) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_ProcEncryptionMetaDataMissing, "sp_describe_parameter_encryption", procedureName)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_ProcEncryptionMetaDataMissing, "sp_describe_parameter_encryption", procedureName)); } internal static Exception UnableToVerifyColumnMasterKeySignature(Exception innerException) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_UnableToVerifyColumnMasterKeySignature, innerException.Message), innerException); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_UnableToVerifyColumnMasterKeySignature, innerException.Message), innerException); } internal static Exception ColumnMasterKeySignatureVerificationFailed(string cmkPath) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_ColumnMasterKeySignatureVerificationFailed, cmkPath)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_ColumnMasterKeySignatureVerificationFailed, cmkPath)); } internal static Exception InvalidKeyStoreProviderName(string providerName, List systemProviders, List customProviders) @@ -1511,22 +1511,22 @@ internal static Exception InvalidKeyStoreProviderName(string providerName, List< const string valueSeparator = @", "; string systemProviderStr = string.Join(valueSeparator, systemProviders.Select(provider => $"'{provider}'")); string customProviderStr = string.Join(valueSeparator, customProviders.Select(provider => $"'{provider}'")); - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidKeyStoreProviderName, providerName, systemProviderStr, customProviderStr)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidKeyStoreProviderName, providerName, systemProviderStr, customProviderStr)); } internal static Exception ParamInvalidForceColumnEncryptionSetting(string paramName, string procedureName) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_ParamInvalidForceColumnEncryptionSetting, TdsEnums.TCE_PARAM_FORCE_COLUMN_ENCRYPTION, paramName, procedureName, "SqlParameter")); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_ParamInvalidForceColumnEncryptionSetting, TdsEnums.TCE_PARAM_FORCE_COLUMN_ENCRYPTION, paramName, procedureName, "SqlParameter")); } internal static Exception ParamUnExpectedEncryptionMetadata(string paramName, string procedureName) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_ParamUnExpectedEncryptionMetadata, paramName, procedureName, TdsEnums.TCE_PARAM_FORCE_COLUMN_ENCRYPTION, "SqlParameter")); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_ParamUnExpectedEncryptionMetadata, paramName, procedureName, TdsEnums.TCE_PARAM_FORCE_COLUMN_ENCRYPTION, "SqlParameter")); } internal static Exception ColumnMasterKeySignatureNotFound(string cmkPath) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_ColumnMasterKeySignatureNotFound, cmkPath)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_ColumnMasterKeySignatureNotFound, cmkPath)); } #endregion Always Encrypted - Errors from sp_describe_parameter_encryption @@ -1534,42 +1534,42 @@ internal static Exception ColumnMasterKeySignatureNotFound(string cmkPath) internal static Exception ExceptionWhenGeneratingEnclavePackage(Exception innerException) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_ExceptionWhenGeneratingEnclavePackage, innerException.Message), innerException); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_ExceptionWhenGeneratingEnclavePackage, innerException.Message), innerException); } internal static Exception FailedToEncryptRegisterRulesBytePackage(Exception innerException) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_FailedToEncryptRegisterRulesBytePackage, innerException.Message), innerException); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_FailedToEncryptRegisterRulesBytePackage, innerException.Message), innerException); } internal static Exception InvalidKeyIdUnableToCastToUnsignedShort(int keyId, Exception innerException) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidKeyIdUnableToCastToUnsignedShort, keyId, innerException.Message), innerException); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidKeyIdUnableToCastToUnsignedShort, keyId, innerException.Message), innerException); } internal static Exception InvalidDatabaseIdUnableToCastToUnsignedInt(int databaseId, Exception innerException) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidDatabaseIdUnableToCastToUnsignedInt, databaseId, innerException.Message), innerException); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidDatabaseIdUnableToCastToUnsignedInt, databaseId, innerException.Message), innerException); } internal static Exception InvalidAttestationParameterUnableToConvertToUnsignedInt(string variableName, int intValue, string enclaveType, Exception innerException) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidAttestationParameterUnableToConvertToUnsignedInt, enclaveType, intValue, variableName, innerException.Message), innerException); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidAttestationParameterUnableToConvertToUnsignedInt, enclaveType, intValue, variableName, innerException.Message), innerException); } internal static Exception OffsetOutOfBounds(string argument, string type, string method) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_OffsetOutOfBounds, type, method)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_OffsetOutOfBounds, type, method)); } internal static Exception InsufficientBuffer(string argument, string type, string method) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InsufficientBuffer, argument, type, method)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InsufficientBuffer, argument, type, method)); } internal static Exception ColumnEncryptionKeysNotFound() { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_ColumnEncryptionKeysNotFound)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_ColumnEncryptionKeysNotFound)); } #endregion Always Encrypted - Errors from secure channel Communication @@ -1577,29 +1577,29 @@ internal static Exception ColumnEncryptionKeysNotFound() #region Always Encrypted - Errors when performing attestation internal static Exception AttestationInfoNotReturnedFromSqlServer(string enclaveType, string enclaveAttestationUrl) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_AttestationInfoNotReturnedFromSQLServer, enclaveType, enclaveAttestationUrl)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_AttestationInfoNotReturnedFromSQLServer, enclaveType, enclaveAttestationUrl)); } #endregion Always Encrypted - Errors when performing attestation #region Always Encrypted - Errors when establishing secure channel internal static Exception NullArgumentInConstructorInternal(string argumentName, string objectUnderConstruction) { - return ADP.ArgumentNull(argumentName, System.SRHelper.GetString(SR.TCE_NullArgumentInConstructorInternal, argumentName, objectUnderConstruction)); + return ADP.ArgumentNull(argumentName, System.StringsHelper.GetString(Strings.TCE_NullArgumentInConstructorInternal, argumentName, objectUnderConstruction)); } internal static Exception EmptyArgumentInConstructorInternal(string argumentName, string objectUnderConstruction) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_EmptyArgumentInConstructorInternal, argumentName, objectUnderConstruction)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_EmptyArgumentInConstructorInternal, argumentName, objectUnderConstruction)); } internal static Exception NullArgumentInternal(string argumentName, string type, string method) { - return ADP.ArgumentNull(argumentName, System.SRHelper.GetString(SR.TCE_NullArgumentInternal, argumentName, type, method)); + return ADP.ArgumentNull(argumentName, System.StringsHelper.GetString(Strings.TCE_NullArgumentInternal, argumentName, type, method)); } internal static Exception EmptyArgumentInternal(string argumentName, string type, string method) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_EmptyArgumentInternal, argumentName, type, method)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_EmptyArgumentInternal, argumentName, type, method)); } #endregion Always Encrypted - Errors when establishing secure channel @@ -1607,47 +1607,47 @@ internal static Exception EmptyArgumentInternal(string argumentName, string type internal static Exception CannotGetSqlColumnEncryptionEnclaveProviderConfig(Exception innerException) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_CannotGetSqlColumnEncryptionEnclaveProviderConfig, innerException.Message), innerException); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_CannotGetSqlColumnEncryptionEnclaveProviderConfig, innerException.Message), innerException); } internal static Exception CannotCreateSqlColumnEncryptionEnclaveProvider(string providerName, string type, Exception innerException) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_CannotCreateSqlColumnEncryptionEnclaveProvider, providerName, type, innerException.Message), innerException); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_CannotCreateSqlColumnEncryptionEnclaveProvider, providerName, type, innerException.Message), innerException); } internal static Exception SqlColumnEncryptionEnclaveProviderNameCannotBeEmpty() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_SqlColumnEncryptionEnclaveProviderNameCannotBeEmpty)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_SqlColumnEncryptionEnclaveProviderNameCannotBeEmpty)); } internal static Exception NoAttestationUrlSpecifiedForEnclaveBasedQuerySpDescribe(string enclaveType) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_NoAttestationUrlSpecifiedForEnclaveBasedQuerySpDescribe, "sp_describe_parameter_encryption", enclaveType)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_NoAttestationUrlSpecifiedForEnclaveBasedQuerySpDescribe, "sp_describe_parameter_encryption", enclaveType)); } internal static Exception NoAttestationUrlSpecifiedForEnclaveBasedQueryGeneratingEnclavePackage(string enclaveType) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_NoAttestationUrlSpecifiedForEnclaveBasedQueryGeneratingEnclavePackage, enclaveType)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_NoAttestationUrlSpecifiedForEnclaveBasedQueryGeneratingEnclavePackage, enclaveType)); } internal static Exception EnclaveTypeNullForEnclaveBasedQuery() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_EnclaveTypeNullForEnclaveBasedQuery)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_EnclaveTypeNullForEnclaveBasedQuery)); } internal static Exception EnclaveProvidersNotConfiguredForEnclaveBasedQuery() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_EnclaveProvidersNotConfiguredForEnclaveBasedQuery)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_EnclaveProvidersNotConfiguredForEnclaveBasedQuery)); } internal static Exception EnclaveProviderNotFound(string enclaveType) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_EnclaveProviderNotFound, enclaveType)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_EnclaveProviderNotFound, enclaveType)); } internal static Exception NullEnclaveSessionReturnedFromProvider(string enclaveType, string attestationUrl) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_NullEnclaveSessionReturnedFromProvider, enclaveType, attestationUrl)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_NullEnclaveSessionReturnedFromProvider, enclaveType, attestationUrl)); } #endregion Always Encrypted - Enclave provider/configuration errors @@ -1680,17 +1680,17 @@ internal static Exception GetExceptionArray(string serverName, string errorMessa internal static Exception ColumnDecryptionFailed(string columnName, string serverName, Exception e) { - return GetExceptionArray(serverName, System.SRHelper.GetString(SR.TCE_ColumnDecryptionFailed, columnName), e); + return GetExceptionArray(serverName, System.StringsHelper.GetString(Strings.TCE_ColumnDecryptionFailed, columnName), e); } internal static Exception ParamEncryptionFailed(string paramName, string serverName, Exception e) { - return GetExceptionArray(serverName, System.SRHelper.GetString(SR.TCE_ParamEncryptionFailed, paramName), e); + return GetExceptionArray(serverName, System.StringsHelper.GetString(Strings.TCE_ParamEncryptionFailed, paramName), e); } internal static Exception ParamDecryptionFailed(string paramName, string serverName, Exception e) { - return GetExceptionArray(serverName, System.SRHelper.GetString(SR.TCE_ParamDecryptionFailed, paramName), e); + return GetExceptionArray(serverName, System.StringsHelper.GetString(Strings.TCE_ParamDecryptionFailed, paramName), e); } #endregion Always Encrypted - Generic toplevel failures @@ -1698,17 +1698,17 @@ internal static Exception ParamDecryptionFailed(string paramName, string serverN internal static Exception UnknownColumnEncryptionAlgorithm(string algorithmName, string supportedAlgorithms) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_UnknownColumnEncryptionAlgorithm, algorithmName, supportedAlgorithms)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_UnknownColumnEncryptionAlgorithm, algorithmName, supportedAlgorithms)); } internal static Exception UnknownColumnEncryptionAlgorithmId(int algoId, string supportAlgorithmIds) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_UnknownColumnEncryptionAlgorithmId, algoId, supportAlgorithmIds), TdsEnums.TCE_PARAM_CIPHER_ALGORITHM_ID); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_UnknownColumnEncryptionAlgorithmId, algoId, supportAlgorithmIds), TdsEnums.TCE_PARAM_CIPHER_ALGORITHM_ID); } internal static Exception UnsupportedNormalizationVersion(byte version) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_UnsupportedNormalizationVersion, version, "'1'", "SQL Server")); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_UnsupportedNormalizationVersion, version, "'1'", "SQL Server")); } internal static Exception UnrecognizedKeyStoreProviderName(string providerName, List systemProviders, List customProviders) @@ -1716,12 +1716,12 @@ internal static Exception UnrecognizedKeyStoreProviderName(string providerName, const string valueSeparator = @", "; string systemProviderStr = string.Join(valueSeparator, systemProviders.Select(provider => @"'" + provider + @"'")); string customProviderStr = string.Join(valueSeparator, customProviders.Select(provider => @"'" + provider + @"'")); - return ADP.Argument(System.SRHelper.GetString(SR.TCE_UnrecognizedKeyStoreProviderName, providerName, systemProviderStr, customProviderStr)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_UnrecognizedKeyStoreProviderName, providerName, systemProviderStr, customProviderStr)); } internal static Exception InvalidDataTypeForEncryptedParameter(string parameterName, int actualDataType, int expectedDataType) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_NullProviderValue, parameterName, actualDataType, expectedDataType)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_NullProviderValue, parameterName, actualDataType, expectedDataType)); } internal static Exception KeyDecryptionFailed(string providerName, string keyHex, Exception e) @@ -1729,57 +1729,57 @@ internal static Exception KeyDecryptionFailed(string providerName, string keyHex if (providerName.Equals(SqlColumnEncryptionCertificateStoreProvider.ProviderName)) { - return GetExceptionArray(null, System.SRHelper.GetString(SR.TCE_KeyDecryptionFailedCertStore, providerName, keyHex), e); + return GetExceptionArray(null, System.StringsHelper.GetString(Strings.TCE_KeyDecryptionFailedCertStore, providerName, keyHex), e); } else { - return GetExceptionArray(null, System.SRHelper.GetString(SR.TCE_KeyDecryptionFailed, providerName, keyHex), e); + return GetExceptionArray(null, System.StringsHelper.GetString(Strings.TCE_KeyDecryptionFailed, providerName, keyHex), e); } } internal static Exception UntrustedKeyPath(string keyPath, string serverName) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_UntrustedKeyPath, keyPath, serverName)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_UntrustedKeyPath, keyPath, serverName)); } internal static Exception UnsupportedDatatypeEncryption(string dataType) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_UnsupportedDatatype, dataType)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_UnsupportedDatatype, dataType)); } internal static Exception ThrowDecryptionFailed(string keyStr, string valStr, Exception e) { - return GetExceptionArray(null, System.SRHelper.GetString(SR.TCE_DecryptionFailed, keyStr, valStr), e); + return GetExceptionArray(null, System.StringsHelper.GetString(Strings.TCE_DecryptionFailed, keyStr, valStr), e); } internal static Exception NullEnclaveSessionDuringQueryExecution(string enclaveType, string enclaveAttestationUrl) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_NullEnclaveSessionDuringQueryExecution, enclaveType, enclaveAttestationUrl)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_NullEnclaveSessionDuringQueryExecution, enclaveType, enclaveAttestationUrl)); } internal static Exception NullEnclavePackageForEnclaveBasedQuery(string enclaveType, string enclaveAttestationUrl) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_NullEnclavePackageForEnclaveBasedQuery, enclaveType, enclaveAttestationUrl)); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_NullEnclavePackageForEnclaveBasedQuery, enclaveType, enclaveAttestationUrl)); } internal static Exception EnclaveProviderNotFound(string enclaveType, string attestationProtocol) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_EnclaveProviderNotFound, enclaveType, attestationProtocol)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_EnclaveProviderNotFound, enclaveType, attestationProtocol)); } internal static Exception EnclaveTypeNotSupported(string enclaveType) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_EnclaveTypeNotSupported, enclaveType)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_EnclaveTypeNotSupported, enclaveType)); } internal static Exception AttestationProtocolNotSupportEnclaveType(string attestationProtocolStr, string enclaveType) { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_AttestationProtocolNotSupportEnclaveType, attestationProtocolStr, enclaveType)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_AttestationProtocolNotSupportEnclaveType, attestationProtocolStr, enclaveType)); } internal static Exception AttestationProtocolNotSpecifiedForGeneratingEnclavePackage() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_AttestationProtocolNotSpecifiedForGeneratingEnclavePackage)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_AttestationProtocolNotSpecifiedForGeneratingEnclavePackage)); } #endregion Always Encrypted - Client side query processing errors @@ -1788,27 +1788,27 @@ internal static Exception AttestationProtocolNotSpecifiedForGeneratingEnclavePac internal static Exception TceNotSupported() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_NotSupportedByServer, "SQL Server")); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_NotSupportedByServer, "SQL Server")); } internal static Exception EnclaveComputationsNotSupported() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_EnclaveComputationsNotSupported)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_EnclaveComputationsNotSupported)); } internal static Exception AttestationURLNotSupported() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_AttestationURLNotSupported)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_AttestationURLNotSupported)); } internal static Exception AttestationProtocolNotSupported() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_AttestationProtocolNotSupported)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_AttestationProtocolNotSupported)); } internal static Exception EnclaveTypeNotReturned() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_EnclaveTypeNotReturned)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_EnclaveTypeNotReturned)); } #endregion Always Encrypted - SQL connection related error messages @@ -1816,27 +1816,27 @@ internal static Exception EnclaveTypeNotReturned() internal static Exception CanOnlyCallOnce() { - return ADP.InvalidOperation(System.SRHelper.GetString(SR.TCE_CanOnlyCallOnce)); + return ADP.InvalidOperation(System.StringsHelper.GetString(Strings.TCE_CanOnlyCallOnce)); } internal static Exception NullCustomKeyStoreProviderDictionary() { - return ADP.ArgumentNull(TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS, System.SRHelper.GetString(SR.TCE_NullCustomKeyStoreProviderDictionary)); + return ADP.ArgumentNull(TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS, System.StringsHelper.GetString(Strings.TCE_NullCustomKeyStoreProviderDictionary)); } internal static Exception InvalidCustomKeyStoreProviderName(string providerName, string prefix) { - return ADP.Argument(System.SRHelper.GetString(SR.TCE_InvalidCustomKeyStoreProviderName, providerName, prefix), TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS); + return ADP.Argument(System.StringsHelper.GetString(Strings.TCE_InvalidCustomKeyStoreProviderName, providerName, prefix), TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS); } internal static Exception NullProviderValue(string providerName) { - return ADP.ArgumentNull(TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS, System.SRHelper.GetString(SR.TCE_NullProviderValue, providerName)); + return ADP.ArgumentNull(TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS, System.StringsHelper.GetString(Strings.TCE_NullProviderValue, providerName)); } internal static Exception EmptyProviderName() { - return ADP.ArgumentNull(TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS, System.SRHelper.GetString(SR.TCE_EmptyProviderName)); + return ADP.ArgumentNull(TdsEnums.TCE_PARAM_CLIENT_KEYSTORE_PROVIDERS, System.StringsHelper.GetString(Strings.TCE_EmptyProviderName)); } #endregion Always Encrypted - Extensibility related error messages @@ -1850,7 +1850,7 @@ internal static string GetSNIErrorMessage(int sniError) Debug.Assert(sniError > 0 && sniError <= (int)SNINativeMethodWrapper.SniSpecialErrors.MaxErrorValue, "SNI error is out of range"); string errorMessageId = string.Format("SNI_ERROR_{0}", sniError); - return System.SRHelper.GetResourceString(errorMessageId); + return System.StringsHelper.GetResourceString(errorMessageId); } // Default values for SqlDependency and SqlNotificationRequest @@ -1875,123 +1875,123 @@ private SQLMessage() { /* prevent utility class from being instantiated*/ } internal static string CultureIdError() { - return System.SRHelper.GetString(SR.SQL_CultureIdError); + return System.StringsHelper.GetString(Strings.SQL_CultureIdError); } internal static string EncryptionNotSupportedByClient() { - return System.SRHelper.GetString(SR.SQL_EncryptionNotSupportedByClient); + return System.StringsHelper.GetString(Strings.SQL_EncryptionNotSupportedByClient); } internal static string EncryptionNotSupportedByServer() { - return System.SRHelper.GetString(SR.SQL_EncryptionNotSupportedByServer); + return System.StringsHelper.GetString(Strings.SQL_EncryptionNotSupportedByServer); } internal static string OperationCancelled() { - return System.SRHelper.GetString(SR.SQL_OperationCancelled); + return System.StringsHelper.GetString(Strings.SQL_OperationCancelled); } internal static string SevereError() { - return System.SRHelper.GetString(SR.SQL_SevereError); + return System.StringsHelper.GetString(Strings.SQL_SevereError); } internal static string SSPIInitializeError() { - return System.SRHelper.GetString(SR.SQL_SSPIInitializeError); + return System.StringsHelper.GetString(Strings.SQL_SSPIInitializeError); } internal static string SSPIGenerateError() { - return System.SRHelper.GetString(SR.SQL_SSPIGenerateError); + return System.StringsHelper.GetString(Strings.SQL_SSPIGenerateError); } internal static string SqlServerBrowserNotAccessible() { - return System.SRHelper.GetString(SR.SQL_SqlServerBrowserNotAccessible); + return System.StringsHelper.GetString(Strings.SQL_SqlServerBrowserNotAccessible); } internal static string KerberosTicketMissingError() { - return System.SRHelper.GetString(SR.SQL_KerberosTicketMissingError); + return System.StringsHelper.GetString(Strings.SQL_KerberosTicketMissingError); } internal static string Timeout() { - return System.SRHelper.GetString(SR.SQL_Timeout_Execution); + return System.StringsHelper.GetString(Strings.SQL_Timeout_Execution); } internal static string Timeout_PreLogin_Begin() { - return System.SRHelper.GetString(SR.SQL_Timeout_PreLogin_Begin); + return System.StringsHelper.GetString(Strings.SQL_Timeout_PreLogin_Begin); } internal static string Timeout_PreLogin_InitializeConnection() { - return System.SRHelper.GetString(SR.SQL_Timeout_PreLogin_InitializeConnection); + return System.StringsHelper.GetString(Strings.SQL_Timeout_PreLogin_InitializeConnection); } internal static string Timeout_PreLogin_SendHandshake() { - return System.SRHelper.GetString(SR.SQL_Timeout_PreLogin_SendHandshake); + return System.StringsHelper.GetString(Strings.SQL_Timeout_PreLogin_SendHandshake); } internal static string Timeout_PreLogin_ConsumeHandshake() { - return System.SRHelper.GetString(SR.SQL_Timeout_PreLogin_ConsumeHandshake); + return System.StringsHelper.GetString(Strings.SQL_Timeout_PreLogin_ConsumeHandshake); } internal static string Timeout_Login_Begin() { - return System.SRHelper.GetString(SR.SQL_Timeout_Login_Begin); + return System.StringsHelper.GetString(Strings.SQL_Timeout_Login_Begin); } internal static string Timeout_Login_ProcessConnectionAuth() { - return System.SRHelper.GetString(SR.SQL_Timeout_Login_ProcessConnectionAuth); + return System.StringsHelper.GetString(Strings.SQL_Timeout_Login_ProcessConnectionAuth); } internal static string Timeout_PostLogin() { - return System.SRHelper.GetString(SR.SQL_Timeout_PostLogin); + return System.StringsHelper.GetString(Strings.SQL_Timeout_PostLogin); } internal static string Timeout_FailoverInfo() { - return System.SRHelper.GetString(SR.SQL_Timeout_FailoverInfo); + return System.StringsHelper.GetString(Strings.SQL_Timeout_FailoverInfo); } internal static string Timeout_RoutingDestination() { - return System.SRHelper.GetString(SR.SQL_Timeout_RoutingDestinationInfo); + return System.StringsHelper.GetString(Strings.SQL_Timeout_RoutingDestinationInfo); } internal static string Duration_PreLogin_Begin(long PreLoginBeginDuration) { - return System.SRHelper.GetString(SR.SQL_Duration_PreLogin_Begin, PreLoginBeginDuration); + return System.StringsHelper.GetString(Strings.SQL_Duration_PreLogin_Begin, PreLoginBeginDuration); } internal static string Duration_PreLoginHandshake(long PreLoginBeginDuration, long PreLoginHandshakeDuration) { - return System.SRHelper.GetString(SR.SQL_Duration_PreLoginHandshake, PreLoginBeginDuration, PreLoginHandshakeDuration); + return System.StringsHelper.GetString(Strings.SQL_Duration_PreLoginHandshake, PreLoginBeginDuration, PreLoginHandshakeDuration); } internal static string Duration_Login_Begin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration) { - return System.SRHelper.GetString(SR.SQL_Duration_Login_Begin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration); + return System.StringsHelper.GetString(Strings.SQL_Duration_Login_Begin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration); } internal static string Duration_Login_ProcessConnectionAuth(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration) { - return System.SRHelper.GetString(SR.SQL_Duration_Login_ProcessConnectionAuth, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration); + return System.StringsHelper.GetString(Strings.SQL_Duration_Login_ProcessConnectionAuth, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration); } internal static string Duration_PostLogin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration, long PostLoginDuration) { - return System.SRHelper.GetString(SR.SQL_Duration_PostLogin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration, PostLoginDuration); + return System.StringsHelper.GetString(Strings.SQL_Duration_PostLogin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration, PostLoginDuration); } internal static string UserInstanceFailure() { - return System.SRHelper.GetString(SR.SQL_UserInstanceFailure); + return System.StringsHelper.GetString(Strings.SQL_UserInstanceFailure); } internal static string PreloginError() { - return System.SRHelper.GetString(SR.Snix_PreLogin); + return System.StringsHelper.GetString(Strings.Snix_PreLogin); } internal static string ExClientConnectionId() { - return System.SRHelper.GetString(SR.SQL_ExClientConnectionId); + return System.StringsHelper.GetString(Strings.SQL_ExClientConnectionId); } internal static string ExErrorNumberStateClass() { - return System.SRHelper.GetString(SR.SQL_ExErrorNumberStateClass); + return System.StringsHelper.GetString(Strings.SQL_ExErrorNumberStateClass); } internal static string ExOriginalClientConnectionId() { - return System.SRHelper.GetString(SR.SQL_ExOriginalClientConnectionId); + return System.StringsHelper.GetString(Strings.SQL_ExOriginalClientConnectionId); } internal static string ExRoutingDestination() { - return System.SRHelper.GetString(SR.SQL_ExRoutingDestination); + return System.StringsHelper.GetString(Strings.SQL_ExRoutingDestination); } } 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 4d9c34247b..7a0e4620b2 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 @@ -1381,9 +1381,9 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) string sniContextEnumName = TdsEnums.GetSniContextEnumName(stateObj.SniContext); - string sqlContextInfo = SRHelper.GetResourceString(sniContextEnumName); + string sqlContextInfo = StringsHelper.GetResourceString(sniContextEnumName); string providerRid = string.Format("SNI_PN{0}", details.provider); - string providerName = SRHelper.GetResourceString(providerRid); + string providerName = StringsHelper.GetResourceString(providerRid); Debug.Assert(!string.IsNullOrEmpty(providerName), $"invalid providerResourceId '{providerRid}'"); uint win32ErrorCode = details.nativeError; SqlClientEventSource.Log.AdvancedTraceEvent(" SNI Native Error Code = {0}", win32ErrorCode); @@ -5308,7 +5308,7 @@ private bool TryProcessRow(_SqlMetaDataSet columns, object[] buffer, int[] map, buffer[map[i]] = data.SqlValue; if (stateObj._longlen != 0) { - throw new SqlTruncateException(SRHelper.GetString(SR.SqlMisc_TruncationMaxDataMessage)); + throw new SqlTruncateException(StringsHelper.GetString(Strings.SqlMisc_TruncationMaxDataMessage)); } } data.Clear(); 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 66c0966e7d..b2fa724102 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 @@ -907,7 +907,7 @@ private void ParseMultipartName() { if (null != _multipartName) { - string[] parts = MultipartIdentifier.ParseMultipartIdentifier(_multipartName, "[\"", "]\"", SR.SQL_TDSParserTableName, false); + string[] parts = MultipartIdentifier.ParseMultipartIdentifier(_multipartName, "[\"", "]\"", Strings.SQL_TDSParserTableName, false); _serverName = parts[0]; _catalogName = parts[1]; _schemaName = parts[2]; @@ -973,7 +973,7 @@ public static string GetProtocolWarning(this SslProtocols protocol) if ((protocol & (SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11)) != SslProtocols.None) #pragma warning restore CS0618 // Type or member is obsolete : SSL is depricated { - message = SRHelper.Format(SR.SEC_ProtocolWarning, protocol.ToFriendlyName()); + message = StringsHelper.Format(Strings.SEC_ProtocolWarning, protocol.ToFriendlyName()); } return message; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index 167954fbc0..78bdda5c7c 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -1237,7 +1237,7 @@ internal bool SetPacketSize(int size) int remainingData = _inBytesRead - _inBytesUsed; if ((temp.Length < _inBytesUsed + remainingData) || (_inBuff.Length < remainingData)) { - string errormessage = SRHelper.GetString(SR.SQL_InvalidInternalPacketSize) + ' ' + temp.Length + ", " + _inBytesUsed + ", " + remainingData + ", " + _inBuff.Length; + string errormessage = StringsHelper.GetString(Strings.SQL_InvalidInternalPacketSize) + ' ' + temp.Length + ", " + _inBytesUsed + ", " + remainingData + ", " + _inBuff.Length; throw SQL.InvalidInternalPacketSize(errormessage); } Buffer.BlockCopy(temp, _inBytesUsed, _inBuff, 0, remainingData); @@ -2706,7 +2706,7 @@ public void ProcessSniPacket(PacketHandle packet, uint error) if (_inBuff.Length < dataSize) { Debug.Assert(true, "Unexpected dataSize on Read"); - throw SQL.InvalidInternalPacketSize(SRHelper.GetString(SR.SqlMisc_InvalidArraySizeMessage)); + throw SQL.InvalidInternalPacketSize(StringsHelper.GetString(Strings.SqlMisc_InvalidArraySizeMessage)); } _lastSuccessfulIOTimer._value = DateTime.UtcNow.Ticks; 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 a358992399..2e638a0502 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 @@ -427,7 +427,7 @@ internal override uint WaitForSSLHandShakeToComplete(out int protocolVersion) } else { - throw new ArgumentException(SRHelper.Format(SRHelper.net_invalid_enum, nameof(NativeProtocols)), nameof(NativeProtocols)); + throw new ArgumentException(StringsHelper.Format(StringsHelper.net_invalid_enum, nameof(NativeProtocols)), nameof(NativeProtocols)); } return returnValue; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProvider.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProvider.NetCoreApp.cs index b9308cbba6..fa86cd7954 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProvider.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProvider.NetCoreApp.cs @@ -35,7 +35,7 @@ public int EnclaveRetrySleepInSeconds { if (value < 1) { - throw new ArgumentException(SR.EnclaveRetrySleepInSecondsValueException); + throw new ArgumentException(Strings.EnclaveRetrySleepInSecondsValueException); } enclaveRetrySleepInSeconds = value; @@ -81,7 +81,7 @@ protected override byte[] MakeRequest(string url) } } - throw new AlwaysEncryptedAttestationException(String.Format(SR.GetAttestationSigningCertificateRequestFailedFormat, url, exception.Message), exception); + throw new AlwaysEncryptedAttestationException(String.Format(Strings.GetAttestationSigningCertificateRequestFailedFormat, url, exception.Message), exception); } #endregion diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.NetCoreApp.cs index 207c5ef11a..1be443edbe 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.NetCoreApp.cs @@ -130,7 +130,7 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell } else { - throw new AlwaysEncryptedAttestationException(SR.FailToCreateEnclaveSession); + throw new AlwaysEncryptedAttestationException(Strings.FailToCreateEnclaveSession); } } } @@ -175,7 +175,7 @@ private void VerifyAttestationInfo(string attestationUrl, HealthReport healthRep } else { - throw new AlwaysEncryptedAttestationException(String.Format(SR.VerifyHealthCertificateChainFormat, attestationUrl, chainStatus)); + throw new AlwaysEncryptedAttestationException(String.Format(Strings.VerifyHealthCertificateChainFormat, attestationUrl, chainStatus)); } } } while (shouldRetryValidation); @@ -207,7 +207,7 @@ private X509Certificate2Collection GetSigningCertificate(string attestationUrl, } catch (CryptographicException exception) { - throw new AlwaysEncryptedAttestationException(String.Format(SR.GetAttestationSigningCertificateFailedInvalidCertificate, attestationUrl), exception); + throw new AlwaysEncryptedAttestationException(String.Format(Strings.GetAttestationSigningCertificateFailedInvalidCertificate, attestationUrl), exception); } rootSigningCertificateCache.Add(attestationUrl, certificateCollection, DateTime.Now.AddDays(1)); @@ -291,7 +291,7 @@ private void VerifyEnclaveReportSignature(EnclaveReportPackage enclaveReportPack if (calculatedSize != enclaveReportPackage.PackageHeader.PackageSize) { - throw new ArgumentException(SR.VerifyEnclaveReportFormatFailed); + throw new ArgumentException(Strings.VerifyEnclaveReportFormatFailed); } // IDK_S is contained in healthReport cert public key @@ -302,7 +302,7 @@ private void VerifyEnclaveReportSignature(EnclaveReportPackage enclaveReportPack if (!rsacng.VerifyData(enclaveReportPackage.ReportAsBytes, enclaveReportPackage.SignatureBlob, HashAlgorithmName.SHA256, RSASignaturePadding.Pss)) { - throw new ArgumentException(SR.VerifyEnclaveReportFailed); + throw new ArgumentException(Strings.VerifyEnclaveReportFailed); } } @@ -324,7 +324,7 @@ private void VerifyEnclavePolicy(EnclaveReportPackage enclaveReportPackage) // if (identity.Flags != ExpectedPolicy.Flags) { - throw new InvalidOperationException(SR.VerifyEnclaveDebuggable); + throw new InvalidOperationException(Strings.VerifyEnclaveDebuggable); } } @@ -333,7 +333,7 @@ private void VerifyEnclavePolicyProperty(string property, byte[] actual, byte[] { if (!actual.SequenceEqual(expected)) { - string exceptionMessage = String.Format(SR.VerifyEnclavePolicyFailedFormat, property, BitConverter.ToString(actual), BitConverter.ToString(expected)); + string exceptionMessage = String.Format(Strings.VerifyEnclavePolicyFailedFormat, property, BitConverter.ToString(actual), BitConverter.ToString(expected)); throw new ArgumentException(exceptionMessage); } } @@ -343,7 +343,7 @@ private void VerifyEnclavePolicyProperty(string property, uint actual, uint expe { if (actual < expected) { - string exceptionMessage = String.Format(SR.VerifyEnclavePolicyFailedFormat, property, actual, expected); + string exceptionMessage = String.Format(Strings.VerifyEnclavePolicyFailedFormat, property, actual, expected); throw new ArgumentException(exceptionMessage); } } @@ -356,7 +356,7 @@ private byte[] GetSharedSecret(EnclavePublicKey enclavePublicKey, EnclaveDiffieH RSACng rsacng = new RSACng(cngkey); if (!rsacng.VerifyData(enclaveDHInfo.PublicKey, enclaveDHInfo.PublicKeySignature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) { - throw new ArgumentException(SR.GetSharedSecretFailed); + throw new ArgumentException(Strings.GetSharedSecretFailed); } CngKey key = CngKey.Import(enclaveDHInfo.PublicKey, CngKeyBlobFormat.GenericPublicBlob); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlTypes/SqlFileStream.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlTypes/SqlFileStream.Windows.cs index 5ac0634202..fec2f1f768 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlTypes/SqlFileStream.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlTypes/SqlFileStream.Windows.cs @@ -450,13 +450,13 @@ static private string GetFullPathInternal(string path) path = path.Trim(); if (path.Length == 0) { - throw ADP.Argument(System.SRHelper.GetString(SR.SqlFileStream_InvalidPath), "path"); + throw ADP.Argument(System.StringsHelper.GetString(Strings.SqlFileStream_InvalidPath), "path"); } // make sure path is not DOS device path if (!path.StartsWith(@"\\") && !System.IO.PathInternal.IsDevice(path.AsSpan())) { - throw ADP.Argument(System.SRHelper.GetString(SR.SqlFileStream_InvalidPath), "path"); + throw ADP.Argument(System.StringsHelper.GetString(Strings.SqlFileStream_InvalidPath), "path"); } // normalize the path @@ -465,7 +465,7 @@ static private string GetFullPathInternal(string path) // make sure path is a UNC path if (System.IO.PathInternal.IsDeviceUNC(path.AsSpan())) { - throw ADP.Argument(System.SRHelper.GetString(SR.SqlFileStream_PathNotValidDiskResource), "path"); + throw ADP.Argument(System.StringsHelper.GetString(Strings.SqlFileStream_PathNotValidDiskResource), "path"); } return path; @@ -619,10 +619,10 @@ long allocationSize break; case Interop.Errors.ERROR_SHARING_VIOLATION: - throw ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlFileStream_FileAlreadyInTransaction)); + throw ADP.InvalidOperation(System.StringsHelper.GetString(Strings.SqlFileStream_FileAlreadyInTransaction)); case Interop.Errors.ERROR_INVALID_PARAMETER: - throw ADP.Argument(System.SRHelper.GetString(SR.SqlFileStream_InvalidParameter)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.SqlFileStream_InvalidParameter)); case Interop.Errors.ERROR_FILE_NOT_FOUND: { @@ -655,7 +655,7 @@ long allocationSize if (Interop.Kernel32.GetFileType(hFile) != Interop.Kernel32.FileTypes.FILE_TYPE_DISK) { hFile.Dispose(); - throw ADP.Argument(System.SRHelper.GetString(SR.SqlFileStream_PathNotValidDiskResource)); + throw ADP.Argument(System.StringsHelper.GetString(Strings.SqlFileStream_PathNotValidDiskResource)); } // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Resources/SR.Designer.cs b/src/Microsoft.Data.SqlClient/netcore/src/Resources/Strings.Designer.cs similarity index 99% rename from src/Microsoft.Data.SqlClient/netcore/src/Resources/SR.Designer.cs rename to src/Microsoft.Data.SqlClient/netcore/src/Resources/Strings.Designer.cs index 44caedd695..aa3f051d37 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Resources/SR.Designer.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Resources/Strings.Designer.cs @@ -22,14 +22,14 @@ namespace System { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + internal class Strings { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal SR() { + internal Strings() { } /// @@ -39,7 +39,7 @@ internal SR() { internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Data.SqlClient.Resources.SR", typeof(SR).Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Data.SqlClient.Resources.Strings", typeof(Strings).Assembly); resourceMan = temp; } return resourceMan; @@ -1429,7 +1429,7 @@ internal static string PlatformNotSupported_DataSqlClient { } /// - /// Looks up a localized string similar to Security Warning: The negotiated '{0}' is an insecured protocol and is supported for backward compatibility only. The recommended protocol is TLS 1.2 and later.. + /// Looks up a localized string similar to Security Warning: The negotiated {0} is an insecure protocol and is supported for backward compatibility only. The recommended protocol version is TLS 1.2 and later.. /// internal static string SEC_ProtocolWarning { get { diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Resources/SR.resx b/src/Microsoft.Data.SqlClient/netcore/src/Resources/Strings.resx similarity index 100% rename from src/Microsoft.Data.SqlClient/netcore/src/Resources/SR.resx rename to src/Microsoft.Data.SqlClient/netcore/src/Resources/Strings.resx diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Resources/SRHelper.cs b/src/Microsoft.Data.SqlClient/netcore/src/Resources/StringsHelper.cs similarity index 89% rename from src/Microsoft.Data.SqlClient/netcore/src/Resources/SRHelper.cs rename to src/Microsoft.Data.SqlClient/netcore/src/Resources/StringsHelper.cs index baee5a3b65..1a12852bc7 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Resources/SRHelper.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Resources/StringsHelper.cs @@ -9,21 +9,21 @@ namespace System { - internal class SRHelper : SR + internal class StringsHelper : Strings { - static SRHelper loader = null; + static StringsHelper loader = null; ResourceManager resources; - internal SRHelper() + internal StringsHelper() { - resources = new ResourceManager("Microsoft.Data.SqlClient.Resources.SR", this.GetType().Assembly); + resources = new ResourceManager("Microsoft.Data.SqlClient.Resources.Strings", this.GetType().Assembly); } - private static SRHelper GetLoader() + private static StringsHelper GetLoader() { if (loader == null) { - SRHelper sr = new SRHelper(); + StringsHelper sr = new StringsHelper(); Interlocked.CompareExchange(ref loader, sr, null); } return loader; @@ -34,7 +34,7 @@ private static SRHelper GetLoader() public static ResourceManager Resources => GetLoader().resources; - // This method is used to decide if we need to append the exception message parameters to the message when calling SR.Format. + // This method is used to decide if we need to append the exception message parameters to the message when calling Strings.Format. // by default it returns false. // Native code generators can replace the value this returns based on user input at the time of native code generation. // Marked as NoInlining because if this is used in an AoT compiled app that is not compiled into a single file, the user @@ -48,13 +48,13 @@ private static bool UsingResourceKeys() public static string GetResourceString(string res) { - SRHelper sys = GetLoader(); + StringsHelper sys = GetLoader(); if (sys == null) return null; // If "res" is a resource id, temp will not be null, "res" will contain the retrieved resource string. // If "res" is not a resource id, temp will be null. - string temp = sys.resources.GetString(res, SRHelper.Culture); + string temp = sys.resources.GetString(res, StringsHelper.Culture); if (temp != null) res = temp; diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/AssemblyResourceManager.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/AssemblyResourceManager.cs index 357c45f82f..c277ca7da4 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/AssemblyResourceManager.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/AssemblyResourceManager.cs @@ -63,11 +63,7 @@ private bool TryGetResourceValue(string resourceName, object[] args, out object } else { -#if netcoreapp - var type = _resourceAssembly.GetType("System.SR"); -#else var type = _resourceAssembly.GetType("System.Strings"); -#endif var info = type.GetProperty(resourceName, BindingFlags.NonPublic | BindingFlags.Static); result = null; From cc9ddb56e08711fdedbd044b96a63bade41bc9fd Mon Sep 17 00:00:00 2001 From: Wraith Date: Fri, 7 Aug 2020 17:41:54 +0100 Subject: [PATCH 02/24] Change _SqlMetaData to lazy initialize hidden column map (#521) --- .../SqlClient/AlwaysEncryptedHelperClasses.cs | 6 +- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 52 +++++-------- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 6 -- .../Data/SqlClient/TdsParserHelperClasses.cs | 78 ++++++++++++++++--- .../SQL/DataReaderTest/DataReaderTest.cs | 77 ++++++++++++++++++ 5 files changed, 164 insertions(+), 55 deletions(-) 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 0268f59f39..5d8cda08e4 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 @@ -234,13 +234,9 @@ sealed internal partial class _SqlMetaDataSet internal readonly SqlTceCipherInfoTable? cekTable; // table of "column encryption keys" used for this metadataset internal _SqlMetaDataSet(int count, SqlTceCipherInfoTable? cipherTable) + : this(count) { cekTable = cipherTable; - _metaDataArray = new _SqlMetaData[count]; - for (int i = 0; i < _metaDataArray.Length; ++i) - { - _metaDataArray[i] = new _SqlMetaData(i); - } } } 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 d467c61ca2..d926a0da62 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 @@ -276,8 +276,8 @@ internal virtual SmiExtendedMetaData[] GetInternalSmiMetaData() if (null != metaData && 0 < metaData.Length) { - metaDataReturn = new SmiExtendedMetaData[metaData.visibleColumns]; - + metaDataReturn = new SmiExtendedMetaData[metaData.VisibleColumnCount]; + int returnIndex = 0; for (int index = 0; index < metaData.Length; index++) { _SqlMetaData colMetaData = metaData[index]; @@ -316,7 +316,7 @@ internal virtual SmiExtendedMetaData[] GetInternalSmiMetaData() length /= ADP.CharSize; } - metaDataReturn[index] = + metaDataReturn[returnIndex] = new SmiQueryMetaData( colMetaData.type, length, @@ -344,6 +344,8 @@ internal virtual SmiExtendedMetaData[] GetInternalSmiMetaData() colMetaData.IsExpression, colMetaData.IsDifferentName, colMetaData.IsHidden); + + returnIndex += 1; } } } @@ -406,7 +408,7 @@ override public int VisibleFieldCount { return 0; } - return (md.visibleColumns); + return md.VisibleColumnCount; } } @@ -1141,31 +1143,6 @@ private bool TryConsumeMetaData() Debug.Assert(!ignored, "Parser read a row token while trying to read metadata"); } - // we hide hidden columns from the user so build an internal map - // that compacts all hidden columns from the array - if (null != _metaData) - { - if (_snapshot != null && object.ReferenceEquals(_snapshot._metadata, _metaData)) - { - _metaData = (_SqlMetaDataSet)_metaData.Clone(); - } - - _metaData.visibleColumns = 0; - - Debug.Assert(null == _metaData.indexMap, "non-null metaData indexmap"); - int[] indexMap = new int[_metaData.Length]; - for (int i = 0; i < indexMap.Length; ++i) - { - indexMap[i] = _metaData.visibleColumns; - - if (!(_metaData[i].IsHidden)) - { - _metaData.visibleColumns++; - } - } - _metaData.indexMap = indexMap; - } - return true; } @@ -2621,11 +2598,11 @@ virtual public int GetSqlValues(object[] values) SetTimeout(_defaultTimeoutMilliseconds); - int copyLen = (values.Length < _metaData.visibleColumns) ? values.Length : _metaData.visibleColumns; + int copyLen = (values.Length < _metaData.VisibleColumnCount) ? values.Length : _metaData.VisibleColumnCount; for (int i = 0; i < copyLen; i++) { - values[_metaData.indexMap[i]] = GetSqlValueInternal(i); + values[i] = GetSqlValueInternal(_metaData.GetVisibleColumnIndex(i)); } return copyLen; } @@ -2964,7 +2941,7 @@ override public int GetValues(object[] values) CheckMetaDataIsReady(); - int copyLen = (values.Length < _metaData.visibleColumns) ? values.Length : _metaData.visibleColumns; + int copyLen = (values.Length < _metaData.VisibleColumnCount) ? values.Length : _metaData.VisibleColumnCount; int maximumColumn = copyLen - 1; SetTimeout(_defaultTimeoutMilliseconds); @@ -2982,12 +2959,19 @@ override public int GetValues(object[] values) for (int i = 0; i < copyLen; i++) { // Get the usable, TypeSystem-compatible value from the internal buffer - values[_metaData.indexMap[i]] = GetValueFromSqlBufferInternal(_data[i], _metaData[i]); + int fieldIndex = _metaData.GetVisibleColumnIndex(i); + values[i] = GetValueFromSqlBufferInternal(_data[fieldIndex], _metaData[fieldIndex]); // If this is sequential access, then we need to wipe the internal buffer if ((sequentialAccess) && (i < maximumColumn)) { - _data[i].Clear(); + _data[fieldIndex].Clear(); + if (fieldIndex > i && fieldIndex>0) + { + // if we jumped an index forward because of a hidden column see if the buffer before the + // current one was populated by the seek forward and clear it if it was + _data[fieldIndex - 1].Clear(); + } } } 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 7a0e4620b2..50f012d574 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 @@ -4447,7 +4447,6 @@ internal bool TryProcessAltMetaData(int cColumns, TdsParserStateObject stateObj, metaData = null; _SqlMetaDataSet altMetaDataSet = new _SqlMetaDataSet(cColumns, null); - int[] indexMap = new int[cColumns]; if (!stateObj.TryReadUInt16(out altMetaDataSet.id)) { @@ -4491,13 +4490,8 @@ internal bool TryProcessAltMetaData(int cColumns, TdsParserStateObject stateObj, { return false; } - - indexMap[i] = i; } - altMetaDataSet.indexMap = indexMap; - altMetaDataSet.visibleColumns = cColumns; - metaData = altMetaDataSet; return true; } 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 b2fa724102..da9123c7d8 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 @@ -542,14 +542,17 @@ public object Clone() internal sealed partial class _SqlMetaDataSet { internal ushort id; // for altrow-columns only - internal int[] indexMap; - internal int visibleColumns; + internal DataTable schemaTable; private readonly _SqlMetaData[] _metaDataArray; internal ReadOnlyCollection dbColumnSchema; + private int _hiddenColumnCount; + private int[] _visibleColumnMap; + internal _SqlMetaDataSet(int count) { + _hiddenColumnCount = -1; _metaDataArray = new _SqlMetaData[count]; for (int i = 0; i < _metaDataArray.Length; ++i) { @@ -559,11 +562,10 @@ internal _SqlMetaDataSet(int count) private _SqlMetaDataSet(_SqlMetaDataSet original) { - this.id = original.id; - // although indexMap is not immutable, in practice it is initialized once and then passed around - this.indexMap = original.indexMap; - this.visibleColumns = original.visibleColumns; - this.dbColumnSchema = original.dbColumnSchema; + id = original.id; + _hiddenColumnCount = original._hiddenColumnCount; + _visibleColumnMap = original._visibleColumnMap; + dbColumnSchema = original.dbColumnSchema; if (original._metaDataArray == null) { _metaDataArray = null; @@ -586,6 +588,18 @@ internal int Length } } + internal int VisibleColumnCount + { + get + { + if (_hiddenColumnCount == -1) + { + SetupHiddenColumns(); + } + return Length - _hiddenColumnCount; + } + } + internal _SqlMetaData this[int index] { get @@ -599,10 +613,54 @@ internal _SqlMetaData this[int index] } } - public object Clone() + public int GetVisibleColumnIndex(int index) + { + if (_hiddenColumnCount == -1) + { + SetupHiddenColumns(); + } + if (_visibleColumnMap is null) + { + return index; + } + else + { + return _visibleColumnMap[index]; + } + } + + public _SqlMetaDataSet Clone() { return new _SqlMetaDataSet(this); } + + private void SetupHiddenColumns() + { + int hiddenColumnCount = 0; + for (int index = 0; index < Length; index++) + { + if (_metaDataArray[index].IsHidden) + { + hiddenColumnCount += 1; + } + } + + if (hiddenColumnCount > 0) + { + int[] visibleColumnMap = new int[Length - hiddenColumnCount]; + int mapIndex = 0; + for (int metaDataIndex = 0; metaDataIndex < Length; metaDataIndex++) + { + if (!_metaDataArray[metaDataIndex].IsHidden) + { + visibleColumnMap[mapIndex] = metaDataIndex; + mapIndex += 1; + } + } + _visibleColumnMap = visibleColumnMap; + } + _hiddenColumnCount = hiddenColumnCount; + } } internal sealed class _SqlMetaDataSetCollection @@ -649,10 +707,10 @@ internal _SqlMetaDataSet GetAltMetaData(int id) public object Clone() { _SqlMetaDataSetCollection result = new _SqlMetaDataSetCollection(); - result.metaDataSet = metaDataSet == null ? null : (_SqlMetaDataSet)metaDataSet.Clone(); + result.metaDataSet = metaDataSet == null ? null : metaDataSet.Clone(); foreach (_SqlMetaDataSet set in _altMetaDataSetArray) { - result._altMetaDataSetArray.Add((_SqlMetaDataSet)set.Clone()); + result._altMetaDataSetArray.Add(set.Clone()); } return result; } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs index b7787b5855..30f88bd151 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; using System.Collections.Generic; using System.Data; using System.Text; @@ -225,5 +226,81 @@ private static bool IsColumnBitSet(SqlConnection con, string selectQuery, int in } return columnSetPresent; } + + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + public static void CheckHiddenColumns() + { + // hidden columns can be found by using CommandBehavior.KeyInfo or at the sql level + // by using the FOR BROWSE option. These features return the column information requested and + // also include any key information required to be able to find the row containing the data + // requested. The additional key information is provided as hidden columns and can be seen using + // the difference between VisibleFieldCount and FieldCount on the reader + + string tempTableName = DataTestUtility.GenerateObjectName(); + + string createQuery = $@" +create table [{tempTableName}] ( + user_id int not null identity(1,1), + first_name varchar(100) null, + last_name varchar(100) null); + +alter table [{tempTableName}] add constraint pk_{tempTableName}_user_id primary key (user_id); + +insert into [{tempTableName}] (first_name,last_name) values ('Joe','Smith') +"; + + string dataQuery = $@"select first_name, last_name from [{tempTableName}]"; + + + int fieldCount = 0; + int visibleFieldCount = 0; + Type[] types = null; + string[] names = null; + + using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) + { + connection.Open(); + + try + { + using (SqlCommand createCommand = new SqlCommand(createQuery, connection)) + { + createCommand.ExecuteNonQuery(); + } + + using (SqlCommand queryCommand = new SqlCommand(dataQuery, connection)) + { + using (SqlDataReader reader = queryCommand.ExecuteReader(CommandBehavior.KeyInfo)) + { + fieldCount = reader.FieldCount; + visibleFieldCount = reader.VisibleFieldCount; + types = new Type[fieldCount]; + names = new string[fieldCount]; + for (int index = 0; index < fieldCount; index++) + { + types[index] = reader.GetFieldType(index); + names[index] = reader.GetName(index); + } + } + } + } + finally + { + DataTestUtility.DropTable(connection, tempTableName); + } + } + + Assert.Equal(3, fieldCount); + Assert.Equal(2, visibleFieldCount); + Assert.NotNull(types); + Assert.NotNull(names); + + // requested fields + Assert.Contains("first_name", names, StringComparer.Ordinal); + Assert.Contains("last_name", names, StringComparer.Ordinal); + + // hidden field + Assert.Contains("user_id", names, StringComparer.Ordinal); + } } } From dbbcde899c646df362ac8369f2d1edd82437759f Mon Sep 17 00:00:00 2001 From: SilverFox Date: Sat, 8 Aug 2020 00:44:39 +0800 Subject: [PATCH 03/24] Only check inexact match when no exact match is found. (#668) Fix dotnet/runtime#39620 --- .../Common/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs | 2 +- .../netfx/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs index d8d9d21957..88ca0725c2 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs @@ -283,7 +283,7 @@ internal DataRow FindMetaDataCollectionRow(string collectionName) exactCollectionName = candidateCollectionName; haveExactMatch = true; } - else + else if (haveExactMatch == false) { // have an inexact match - ok only if it is the only one if (exactCollectionName != null) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs index 644d336232..bea2e6cae5 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbMetaDataFactory.cs @@ -322,7 +322,7 @@ internal DataRow FindMetaDataCollectionRow(string collectionName) exactCollectionName = candidateCollectionName; haveExactMatch = true; } - else + else if (haveExactMatch == false) { // have an inexact match - ok only if it is the only one if (exactCollectionName != null) From f0e90e25816f495710b145a7756657467c1b56ee Mon Sep 17 00:00:00 2001 From: Karina Zhou Date: Thu, 20 Aug 2020 14:17:35 -0700 Subject: [PATCH 04/24] Remove duplicate CacheConnectionStringProperties calls (#683) --- .../netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs | 2 -- .../netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs | 3 --- 2 files changed, 5 deletions(-) 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 a139327841..b82137f669 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 @@ -114,7 +114,6 @@ private static readonly ConcurrentDictionary> _ColumnEncry public SqlConnection(string connectionString) : this() { ConnectionString = connectionString; // setting connection string first so that ConnectionOption is available - CacheConnectionStringProperties(); } /// @@ -157,7 +156,6 @@ public SqlConnection(string connectionString, SqlCredential credential) : this() // else // credential == null: we should not set "Credential" as this will do additional validation check and // checking pool groups which is not necessary. All necessary operation is already done by calling "ConnectionString = connectionString" - CacheConnectionStringProperties(); } private SqlConnection(SqlConnection connection) 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 a0775464f4..8181a4e27d 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 @@ -336,7 +336,6 @@ public SqlConnection(string connectionString, SqlCredential credential) : this() // else // credential == null: we should not set "Credential" as this will do additional validation check and // checking pool groups which is not necessary. All necessary operation is already done by calling "ConnectionString = connectionString" - CacheConnectionStringProperties(); } private SqlConnection(SqlConnection connection) @@ -3231,5 +3230,3 @@ internal struct MEMMAP internal byte[] rgbData; } } // Microsoft.Data.SqlClient namespace - - From 8d1db304e1b85e1c44de8db4f6e584a0963b5f79 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Thu, 20 Aug 2020 15:11:11 -0700 Subject: [PATCH 05/24] Revert "Return empty DataTable from GetSchemaTable. (#419)" (#696) --- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 2 +- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 3 +-- .../SQL/DataReaderTest/DataReaderTest.cs | 19 +------------------ 3 files changed, 3 insertions(+), 21 deletions(-) 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 d926a0da62..dd7d898f85 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 @@ -1454,7 +1454,7 @@ public override DataTable GetSchemaTable() Debug.Assert(null != _metaData.schemaTable, "No schema information yet!"); } } - return _metaData?.schemaTable ?? new DataTable(); + return _metaData?.schemaTable; } finally { 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 d015ca434f..c29b521eef 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 @@ -1681,10 +1681,9 @@ override public DataTable GetSchemaTable() { _metaData.schemaTable = BuildSchemaTable(); Debug.Assert(null != _metaData.schemaTable, "No schema information yet!"); - // filter table? } } - return _metaData?.schemaTable ?? new DataTable(); + return _metaData?.schemaTable; } finally { diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs index 30f88bd151..2e1c32c716 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs @@ -38,6 +38,7 @@ public static void LoadReaderIntoDataTableToTestGetSchemaTable() [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static void MultiQuerySchema() { + SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString); using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) { connection.Open(); @@ -66,25 +67,7 @@ public static void MultiQuerySchema() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] - public static void GetSchemaTable_returns_null_when_no_resultset() - { - using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) - { - connection.Open(); - using (SqlCommand command = connection.CreateCommand()) - { - command.CommandText = "SELECT 1"; - using (SqlDataReader reader = command.ExecuteReader()) - { - reader.NextResult(); - Assert.NotNull(reader.GetSchemaTable()); - } - } - } - } - // Checks for the IsColumnSet bit in the GetSchemaTable for Sparse columns [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static void CheckSparseColumnBit() From 736f4a289a4685fac9b82f4744ffb421628e84db Mon Sep 17 00:00:00 2001 From: Karina Zhou Date: Thu, 20 Aug 2020 15:12:43 -0700 Subject: [PATCH 06/24] Port Fix for EnclaveSessionCache Issue (#686) --- .../SqlColumnEncryptionEnclaveProvider.xml | 9 +- ...estationBasedEnclaveProvider.NetCoreApp.cs | 18 +- .../SqlClient/EnclaveDelegate.NetCoreApp.cs | 36 ++-- .../SqlClient/EnclaveDelegate.NetStandard.cs | 11 +- .../EnclaveProviderBase.NetCoreApp.cs | 20 +- .../EnclaveSessionCache.NetCoreApp.cs | 18 +- .../SimulatorEnclaveProvider.NetCoreApp.cs | 22 +-- ...umnEncryptionEnclaveProvider.NetCoreApp.cs | 5 +- .../SqlColumnEncryptionEnclaveProvider.cs | 4 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 28 +-- .../Data/SqlClient/SqlEnclaveSession.cs | 14 ++ ...ecureModeEnclaveProviderBase.NetCoreApp.cs | 18 +- .../AzureAttestationBasedEnclaveProvider.cs | 22 +-- .../Data/SqlClient/EnclaveDelegate.cs | 36 ++-- .../Data/SqlClient/EnclaveProviderBase.cs | 18 +- .../Data/SqlClient/EnclaveSessionCache.cs | 20 +- .../SqlClient/SimulatorEnclaveProvider.cs | 20 +- .../SqlColumnEncryptionEnclaveProvider.cs | 6 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 28 +-- .../Data/SqlClient/SqlEnclaveSession.cs | 14 ++ .../VirtualSecureModeEnclaveProviderBase.cs | 19 +- .../EnclaveAzureDatabaseTests.cs | 185 ++++++++++++++++++ .../SQLSetupStrategyAzureKeyVault.cs | 4 +- .../TestFixtures/Setup/AkvColumnMasterKey.cs | 8 +- .../TestFixtures/Setup/CspColumnMasterKey.cs | 8 +- .../ManualTests/DataCommon/DataTestUtility.cs | 10 + ....Data.SqlClient.ManualTesting.Tests.csproj | 1 + 27 files changed, 412 insertions(+), 190 deletions(-) create mode 100644 src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/EnclaveAzureDatabaseTests.cs diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionEnclaveProvider.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionEnclaveProvider.xml index c85f90fc84..261f5e57ed 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionEnclaveProvider.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlColumnEncryptionEnclaveProvider.xml @@ -19,8 +19,7 @@ the enclave attestation protocol as well as the logic for creating and caching e The information the provider uses to attest the enclave and generate a symmetric key for the session. The format of this information is specific to the enclave attestation protocol. A Diffie-Hellman algorithm object that encapsulates a client-side key pair. - The endpoint of an attestation service for attesting the enclave. - The name of the SQL Server instance containing the enclave. + The set of parameters required for an enclave session. The set of extra data needed for attestating the enclave. The length of the extra data needed for attestating the enclave. The requested enclave session or if the provider doesn't implement session caching. @@ -37,8 +36,7 @@ the enclave attestation protocol as well as the logic for creating and caching e To be added. - The name of the SQL Server instance containing the enclave. - The endpoint of an attestation service, SqlClient contacts to attest the enclave. + The set of parameters required for enclave session. to indicate that a set of extra data needs to be generated for attestation; otherwise, . When this method returns, the requested enclave session or if the provider doesn't implement session caching. This parameter is treated as uninitialized. A counter that the enclave provider is expected to increment each time SqlClient retrieves the session from the cache. The purpose of this field is to prevent replay attacks. @@ -49,8 +47,7 @@ the enclave attestation protocol as well as the logic for creating and caching e To be added. - The name of the SQL Server instance containing the enclave. - The endpoint of an attestation service, SqlClient contacts to attest the enclave. + The set of parameters required for enclave session. The session to be invalidated. When overridden in a derived class, looks up and evicts an enclave session from the enclave session cache, if the provider implements session caching. To be added. diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.NetCoreApp.cs index b41ef407bf..a2a8270803 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.NetCoreApp.cs @@ -65,9 +65,9 @@ internal class AzureAttestationEnclaveProvider : EnclaveProviderBase #region Internal methods // When overridden in a derived class, looks up an existing enclave session information in the enclave session cache. // If the enclave provider doesn't implement enclave session caching, this method is expected to return null in the sqlEnclaveSession parameter. - internal override void GetEnclaveSession(string servername, string attestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) + internal override void GetEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) { - GetEnclaveSessionHelper(servername, attestationUrl, generateCustomData, out sqlEnclaveSession, out counter, out customData, out customDataLength); + GetEnclaveSessionHelper(enclaveSessionParameters, generateCustomData, out sqlEnclaveSession, out counter, out customData, out customDataLength); } // Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. @@ -81,17 +81,17 @@ internal override SqlEnclaveAttestationParameters GetAttestationParameters(strin } // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache. - internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, string attestationUrl, string servername, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) + internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) { sqlEnclaveSession = null; counter = 0; try { ThreadRetryCache.Remove(Thread.CurrentThread.ManagedThreadId.ToString()); - sqlEnclaveSession = GetEnclaveSessionFromCache(servername, attestationUrl, out counter); + sqlEnclaveSession = GetEnclaveSessionFromCache(enclaveSessionParameters, out counter); if (sqlEnclaveSession == null) { - if (!string.IsNullOrEmpty(attestationUrl) && customData != null && customDataLength > 0) + if (!string.IsNullOrEmpty(enclaveSessionParameters.AttestationUrl) && customData != null && customDataLength > 0) { byte[] nonce = customData; @@ -101,13 +101,13 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell AzureAttestationInfo attestInfo = new AzureAttestationInfo(attestationInfo); // Validate the attestation info - VerifyAzureAttestationInfo(attestationUrl, attestInfo.EnclaveType, attestInfo.AttestationToken.AttestationToken, attestInfo.Identity, nonce); + VerifyAzureAttestationInfo(enclaveSessionParameters.AttestationUrl, attestInfo.EnclaveType, attestInfo.AttestationToken.AttestationToken, attestInfo.Identity, nonce); // Set up shared secret and validate signature byte[] sharedSecret = GetSharedSecret(attestInfo.Identity, nonce, attestInfo.EnclaveType, attestInfo.EnclaveDHInfo, clientDHKey); // add session to cache - sqlEnclaveSession = AddEnclaveSessionToCache(attestationUrl, servername, sharedSecret, attestInfo.SessionId, out counter); + sqlEnclaveSession = AddEnclaveSessionToCache(enclaveSessionParameters, sharedSecret, attestInfo.SessionId, out counter); } else { @@ -126,9 +126,9 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell } // When overridden in a derived class, looks up and evicts an enclave session from the enclave session cache, if the provider implements session caching. - internal override void InvalidateEnclaveSession(string serverName, string enclaveAttestationUrl, SqlEnclaveSession enclaveSessionToInvalidate) + internal override void InvalidateEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSessionToInvalidate) { - InvalidateEnclaveSessionHelper(serverName, enclaveAttestationUrl, enclaveSessionToInvalidate); + InvalidateEnclaveSessionHelper(enclaveSessionParameters, enclaveSessionToInvalidate); } #endregion diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveDelegate.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveDelegate.NetCoreApp.cs index 4ab9421bd9..db9f7a68f2 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveDelegate.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveDelegate.NetCoreApp.cs @@ -62,13 +62,12 @@ internal byte[] GetSerializedAttestationParameters(SqlEnclaveAttestationParamete /// /// attestation protocol /// enclave type - /// servername - /// attestation url for attestation service endpoint + /// The set of parameters required for enclave session. /// attestation info from SQL Server /// attestation parameters /// A set of extra data needed for attestating the enclave. /// The length of the extra data needed for attestating the enclave. - internal void CreateEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, string serverName, string attestationUrl, + internal void CreateEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, EnclaveSessionParameters enclaveSessionParameters, byte[] attestationInfo, SqlEnclaveAttestationParameters attestationParameters, byte[] customData, int customDataLength) { @@ -80,18 +79,18 @@ internal void CreateEnclaveSession(SqlConnectionAttestationProtocol attestationP byte[] dummyCustomData = null; int dummyCustomDataLength; - sqlColumnEncryptionEnclaveProvider.GetEnclaveSession(serverName, attestationUrl, false, out sqlEnclaveSession, out counter, out dummyCustomData, out dummyCustomDataLength); + sqlColumnEncryptionEnclaveProvider.GetEnclaveSession(enclaveSessionParameters, false, out sqlEnclaveSession, out counter, out dummyCustomData, out dummyCustomDataLength); if (sqlEnclaveSession != null) { return; } - sqlColumnEncryptionEnclaveProvider.CreateEnclaveSession(attestationInfo, attestationParameters.ClientDiffieHellmanKey, attestationUrl, serverName, customData, customDataLength, out sqlEnclaveSession, out counter); + sqlColumnEncryptionEnclaveProvider.CreateEnclaveSession(attestationInfo, attestationParameters.ClientDiffieHellmanKey, enclaveSessionParameters, customData, customDataLength, out sqlEnclaveSession, out counter); if (sqlEnclaveSession == null) { - throw SQL.NullEnclaveSessionReturnedFromProvider(enclaveType, attestationUrl); + throw SQL.NullEnclaveSessionReturnedFromProvider(enclaveType, enclaveSessionParameters.AttestationUrl); } } } @@ -103,10 +102,9 @@ internal void CreateEnclaveSession(SqlConnectionAttestationProtocol attestationP /// Keys to be sent to enclave /// /// enclave type - /// server name - /// url for attestation endpoint + /// The set of parameters required for enclave session. /// - internal EnclavePackage GenerateEnclavePackage(SqlConnectionAttestationProtocol attestationProtocol, Dictionary keysToBeSentToEnclave, string queryText, string enclaveType, string serverName, string enclaveAttestationUrl) + internal EnclavePackage GenerateEnclavePackage(SqlConnectionAttestationProtocol attestationProtocol, Dictionary keysToBeSentToEnclave, string queryText, string enclaveType, EnclaveSessionParameters enclaveSessionParameters) { SqlEnclaveSession sqlEnclaveSession = null; @@ -116,27 +114,27 @@ internal EnclavePackage GenerateEnclavePackage(SqlConnectionAttestationProtocol try { - GetEnclaveSession(attestationProtocol, enclaveType, serverName, enclaveAttestationUrl, false, out sqlEnclaveSession, out counter, out dummyCustomData, out dummyCustomDataLength, throwIfNull: true); + GetEnclaveSession(attestationProtocol, enclaveType, enclaveSessionParameters, false, out sqlEnclaveSession, out counter, out dummyCustomData, out dummyCustomDataLength, throwIfNull: true); } catch (Exception e) { throw new RetryableEnclaveQueryExecutionException(e.Message, e); } - List decryptedKeysToBeSentToEnclave = GetDecryptedKeysToBeSentToEnclave(keysToBeSentToEnclave, serverName); + List decryptedKeysToBeSentToEnclave = GetDecryptedKeysToBeSentToEnclave(keysToBeSentToEnclave, enclaveSessionParameters.ServerName); byte[] queryStringHashBytes = ComputeQueryStringHash(queryText); byte[] keyBytePackage = GenerateBytePackageForKeys(counter, queryStringHashBytes, decryptedKeysToBeSentToEnclave); byte[] sessionKey = sqlEnclaveSession.GetSessionKey(); - byte[] encryptedBytePackage = EncryptBytePackage(keyBytePackage, sessionKey, serverName); + byte[] encryptedBytePackage = EncryptBytePackage(keyBytePackage, sessionKey, enclaveSessionParameters.ServerName); byte[] enclaveSessionHandle = BitConverter.GetBytes(sqlEnclaveSession.SessionId); byte[] byteArrayToBeSentToEnclave = CombineByteArrays(new[] { enclaveSessionHandle, encryptedBytePackage }); return new EnclavePackage(byteArrayToBeSentToEnclave, sqlEnclaveSession); } - internal void InvalidateEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, string serverName, string EnclaveAttestationUrl, SqlEnclaveSession enclaveSession) + internal void InvalidateEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSession) { SqlColumnEncryptionEnclaveProvider sqlColumnEncryptionEnclaveProvider = GetEnclaveProvider(attestationProtocol, enclaveType); - sqlColumnEncryptionEnclaveProvider.InvalidateEnclaveSession(serverName, EnclaveAttestationUrl, enclaveSession); + sqlColumnEncryptionEnclaveProvider.InvalidateEnclaveSession(enclaveSessionParameters, enclaveSession); } @@ -207,20 +205,20 @@ private string ConvertAttestationProtocolToString(SqlConnectionAttestationProtoc } } - internal void GetEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, string serverName, string enclaveAttestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out byte[] customData, out int customDataLength) + internal void GetEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out byte[] customData, out int customDataLength) { long counter; - GetEnclaveSession(attestationProtocol, enclaveType, serverName, enclaveAttestationUrl, generateCustomData, out sqlEnclaveSession, out counter, out customData, out customDataLength, throwIfNull: false); + GetEnclaveSession(attestationProtocol, enclaveType, enclaveSessionParameters, generateCustomData, out sqlEnclaveSession, out counter, out customData, out customDataLength, throwIfNull: false); } - private void GetEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, string serverName, string enclaveAttestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength, bool throwIfNull) + private void GetEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength, bool throwIfNull) { SqlColumnEncryptionEnclaveProvider sqlColumnEncryptionEnclaveProvider = GetEnclaveProvider(attestationProtocol, enclaveType); - sqlColumnEncryptionEnclaveProvider.GetEnclaveSession(serverName, enclaveAttestationUrl, generateCustomData, out sqlEnclaveSession, out counter, out customData, out customDataLength); + sqlColumnEncryptionEnclaveProvider.GetEnclaveSession(enclaveSessionParameters, generateCustomData, out sqlEnclaveSession, out counter, out customData, out customDataLength); if (throwIfNull && sqlEnclaveSession == null) { - throw SQL.NullEnclaveSessionDuringQueryExecution(enclaveType, enclaveAttestationUrl); + throw SQL.NullEnclaveSessionDuringQueryExecution(enclaveType, enclaveSessionParameters.AttestationUrl); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveDelegate.NetStandard.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveDelegate.NetStandard.cs index 63db20022a..3005105a14 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveDelegate.NetStandard.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveDelegate.NetStandard.cs @@ -23,29 +23,28 @@ internal byte[] GetSerializedAttestationParameters( /// /// attestation protocol /// enclave type - /// servername - /// attestation url for attestation service endpoint + /// The set of parameters required for enclave session. /// attestation info from SQL Server /// attestation parameters /// A set of extra data needed for attestating the enclave. /// The length of the extra data needed for attestating the enclave. - internal void CreateEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, string serverName, string attestationUrl, + internal void CreateEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, EnclaveSessionParameters enclaveSessionParameters, byte[] attestationInfo, SqlEnclaveAttestationParameters attestationParameters, byte[] customData, int customDataLength) { throw new PlatformNotSupportedException(); } - internal void GetEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, string serverName, string enclaveAttestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out byte[] customData, out int customDataLength) + internal void GetEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out byte[] customData, out int customDataLength) { throw new PlatformNotSupportedException(); } - internal EnclavePackage GenerateEnclavePackage(SqlConnectionAttestationProtocol attestationProtocol, Dictionary keysTobeSentToEnclave, string queryText, string enclaveType, string serverName, string enclaveAttestationUrl) + internal EnclavePackage GenerateEnclavePackage(SqlConnectionAttestationProtocol attestationProtocol, Dictionary keysTobeSentToEnclave, string queryText, string enclaveType, EnclaveSessionParameters enclaveSessionParameters) { throw new PlatformNotSupportedException(); } - internal void InvalidateEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, string serverName, string EnclaveAttestationUrl, SqlEnclaveSession enclaveSession) + internal void InvalidateEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSession) { throw new PlatformNotSupportedException(); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveProviderBase.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveProviderBase.NetCoreApp.cs index 213b6b162b..a32e46f581 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveProviderBase.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveProviderBase.NetCoreApp.cs @@ -87,13 +87,13 @@ internal abstract class EnclaveProviderBase : SqlColumnEncryptionEnclaveProvider protected static readonly MemoryCache ThreadRetryCache = new MemoryCache("ThreadRetryCache"); #endregion - #region Public methods + #region protected methods // Helper method to get the enclave session from the cache if present - protected void GetEnclaveSessionHelper(string servername, string attestationUrl, bool shouldGenerateNonce, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) + protected void GetEnclaveSessionHelper(EnclaveSessionParameters enclaveSessionParameters, bool shouldGenerateNonce, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) { customData = null; customDataLength = 0; - sqlEnclaveSession = SessionCache.GetEnclaveSession(servername, attestationUrl, out counter); + sqlEnclaveSession = SessionCache.GetEnclaveSession(enclaveSessionParameters, out counter); if (sqlEnclaveSession == null) { @@ -128,7 +128,7 @@ protected void GetEnclaveSessionHelper(string servername, string attestationUrl, { // While the current thread is waiting for event to be signaled and in the meanwhile we already completed the attestation on different thread // then we need to signal the event here - sqlEnclaveSession = SessionCache.GetEnclaveSession(servername, attestationUrl, out counter); + sqlEnclaveSession = SessionCache.GetEnclaveSession(enclaveSessionParameters, out counter); if (sqlEnclaveSession != null && !sameThreadRetry) { lock (lockUpdateSessionLock) @@ -194,21 +194,21 @@ protected void UpdateEnclaveSessionLockStatus(SqlEnclaveSession sqlEnclaveSessio } // Helper method to remove the enclave session from the cache - protected void InvalidateEnclaveSessionHelper(string servername, string attestationUrl, SqlEnclaveSession enclaveSessionToInvalidate) + protected void InvalidateEnclaveSessionHelper(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSessionToInvalidate) { - SessionCache.InvalidateSession(servername, attestationUrl, enclaveSessionToInvalidate); + SessionCache.InvalidateSession(enclaveSessionParameters, enclaveSessionToInvalidate); } // Helper method for getting the enclave session from the session cache - protected SqlEnclaveSession GetEnclaveSessionFromCache(string attestationUrl, string servername, out long counter) + protected SqlEnclaveSession GetEnclaveSessionFromCache(EnclaveSessionParameters enclaveSessionParameters, out long counter) { - return SessionCache.GetEnclaveSession(servername, attestationUrl, out counter); + return SessionCache.GetEnclaveSession(enclaveSessionParameters, out counter); } // Helper method for adding the enclave session to the session cache - protected SqlEnclaveSession AddEnclaveSessionToCache(string attestationUrl, string servername, byte[] sharedSecret, long sessionId, out long counter) + protected SqlEnclaveSession AddEnclaveSessionToCache(EnclaveSessionParameters enclaveSessionParameters, byte[] sharedSecret, long sessionId, out long counter) { - return SessionCache.CreateSession(attestationUrl, servername, sharedSecret, sessionId, out counter); + return SessionCache.CreateSession(enclaveSessionParameters, sharedSecret, sessionId, out counter); } } #endregion diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveSessionCache.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveSessionCache.NetCoreApp.cs index 5cf0590d06..f76191fec8 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveSessionCache.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveSessionCache.NetCoreApp.cs @@ -22,23 +22,23 @@ internal class EnclaveSessionCache private static int enclaveCacheTimeOutInHours = 8; // Retrieves a SqlEnclaveSession from the cache - internal SqlEnclaveSession GetEnclaveSession(string servername, string attestationUrl, out long counter) + internal SqlEnclaveSession GetEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, out long counter) { - string cacheKey = GenerateCacheKey(servername, attestationUrl); + string cacheKey = GenerateCacheKey(enclaveSessionParameters); SqlEnclaveSession enclaveSession = enclaveMemoryCache[cacheKey] as SqlEnclaveSession; counter = Interlocked.Increment(ref _counter); return enclaveSession; } // Invalidates a SqlEnclaveSession entry in the cache - internal void InvalidateSession(string serverName, string enclaveAttestationUrl, SqlEnclaveSession enclaveSessionToInvalidate) + internal void InvalidateSession(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSessionToInvalidate) { - string cacheKey = GenerateCacheKey(serverName, enclaveAttestationUrl); + string cacheKey = GenerateCacheKey(enclaveSessionParameters); lock (enclaveCacheLock) { long counter; - SqlEnclaveSession enclaveSession = GetEnclaveSession(serverName, enclaveAttestationUrl, out counter); + SqlEnclaveSession enclaveSession = GetEnclaveSession(enclaveSessionParameters, out counter); if (enclaveSession != null && enclaveSession.SessionId == enclaveSessionToInvalidate.SessionId) { @@ -52,9 +52,9 @@ internal void InvalidateSession(string serverName, string enclaveAttestationUrl, } // Creates a new SqlEnclaveSession and adds it to the cache - internal SqlEnclaveSession CreateSession(string attestationUrl, string serverName, byte[] sharedSecret, long sessionId, out long counter) + internal SqlEnclaveSession CreateSession(EnclaveSessionParameters enclaveSessionParameters, byte[] sharedSecret, long sessionId, out long counter) { - string cacheKey = GenerateCacheKey(serverName, attestationUrl); + string cacheKey = GenerateCacheKey(enclaveSessionParameters); SqlEnclaveSession enclaveSession = null; lock (enclaveCacheLock) { @@ -67,9 +67,9 @@ internal SqlEnclaveSession CreateSession(string attestationUrl, string serverNam } // Generates the cache key for the enclave session cache - private string GenerateCacheKey(string serverName, string attestationUrl) + private string GenerateCacheKey(EnclaveSessionParameters enclaveSessionParameters) { - return (serverName + attestationUrl).ToLowerInvariant(); + return (enclaveSessionParameters.ServerName + '+' + enclaveSessionParameters.Database + enclaveSessionParameters.AttestationUrl).ToLowerInvariant(); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs index 811816f1e6..064742be3c 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs @@ -22,14 +22,13 @@ internal class SimulatorEnclaveProvider : EnclaveProviderBase // When overridden in a derived class, looks up an existing enclave session information in the enclave session cache. // If the enclave provider doesn't implement enclave session caching, this method is expected to return null in the sqlEnclaveSession parameter. - public override void GetEnclaveSession(string servername, string attestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) + internal override void GetEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) { - GetEnclaveSessionHelper(servername, attestationUrl, false, out sqlEnclaveSession, out counter, out customData, out customDataLength); + GetEnclaveSessionHelper(enclaveSessionParameters, false, out sqlEnclaveSession, out counter, out customData, out customDataLength); } // Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. - // The information SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. - public override SqlEnclaveAttestationParameters GetAttestationParameters(string attestationUrl, byte[] customData, int customDataLength) + internal override SqlEnclaveAttestationParameters GetAttestationParameters(string attestationUrl, byte[] customData, int customDataLength) { ECDiffieHellmanCng clientDHKey = new ECDiffieHellmanCng(384); clientDHKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; @@ -39,7 +38,7 @@ public override SqlEnclaveAttestationParameters GetAttestationParameters(string } // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache. - public override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, string attestationUrl, string servername, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) + internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) { ////for simulator: enclave does not send public key, and sends an empty attestation info //// The only non-trivial content it sends is the session setup info (DH pubkey of enclave) @@ -49,11 +48,11 @@ public override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellma try { ThreadRetryCache.Remove(Thread.CurrentThread.ManagedThreadId.ToString()); - sqlEnclaveSession = GetEnclaveSessionFromCache(servername, attestationUrl, out counter); + sqlEnclaveSession = GetEnclaveSessionFromCache(enclaveSessionParameters, out counter); if (sqlEnclaveSession == null) { - if (!string.IsNullOrEmpty(attestationUrl)) + if (!string.IsNullOrEmpty(enclaveSessionParameters.AttestationUrl)) { ////Read AttestationInfo int attestationInfoOffset = 0; @@ -88,7 +87,7 @@ public override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellma CngKey k = CngKey.Import(trustedModuleDHPublicKey, CngKeyBlobFormat.EccPublicBlob); byte[] sharedSecret = clientDHKey.DeriveKeyMaterial(k); long sessionId = BitConverter.ToInt64(enclaveSessionHandle, 0); - sqlEnclaveSession = AddEnclaveSessionToCache(attestationUrl, servername, sharedSecret, sessionId, out counter); + sqlEnclaveSession = AddEnclaveSessionToCache(enclaveSessionParameters, sharedSecret, sessionId, out counter); } else { @@ -105,12 +104,11 @@ public override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellma /// /// When overridden in a derived class, looks up and evicts an enclave session from the enclave session cache, if the provider implements session caching. /// - /// The name of the SQL Server instance containing the enclave. - /// The endpoint of an attestation service, SqlClient contacts to attest the enclave. + /// The set of parameters required for enclave session. /// The session to be invalidated. - public override void InvalidateEnclaveSession(string serverName, string enclaveAttestationUrl, SqlEnclaveSession enclaveSessionToInvalidate) + internal override void InvalidateEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSessionToInvalidate) { - InvalidateEnclaveSessionHelper(serverName, enclaveAttestationUrl, enclaveSessionToInvalidate); + InvalidateEnclaveSessionHelper(enclaveSessionParameters, enclaveSessionToInvalidate); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.NetCoreApp.cs index ccf4fe889c..c608036c6e 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.NetCoreApp.cs @@ -14,13 +14,12 @@ internal abstract partial class SqlColumnEncryptionEnclaveProvider /// Performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache. /// The information the provider uses to attest the enclave and generate a symmetric key for the session. The format of this information is specific to the enclave attestation protocol. /// A Diffie-Hellman algorithm object encapsulating a client-side key pair. - /// The endpoint of an attestation service for attesting the enclave. - /// The name of the SQL Server instance containing the enclave. + /// The set of parameters required for enclave session. /// The set of extra data needed for attestating the enclave. /// The length of the extra data needed for attestating the enclave. /// The requested enclave session or null if the provider does not implement session caching. /// A counter that the enclave provider is expected to increment each time SqlClient retrieves the session from the cache. The purpose of this field is to prevent replay attacks. - internal abstract void CreateEnclaveSession(byte[] enclaveAttestationInfo, ECDiffieHellmanCng clientDiffieHellmanKey, string attestationUrl, string servername, byte[] customData, int customDataLength, + internal abstract void CreateEnclaveSession(byte[] enclaveAttestationInfo, ECDiffieHellmanCng clientDiffieHellmanKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.cs index 79ba91de7b..e374d43665 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.cs @@ -8,12 +8,12 @@ namespace Microsoft.Data.SqlClient internal abstract partial class SqlColumnEncryptionEnclaveProvider { /// - internal abstract void GetEnclaveSession(string serverName, string attestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength); + internal abstract void GetEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength); /// internal abstract SqlEnclaveAttestationParameters GetAttestationParameters(string attestationUrl, byte[] customData, int customDataLength); /// - internal abstract void InvalidateEnclaveSession(string serverName, string enclaveAttestationUrl, SqlEnclaveSession enclaveSession); + internal abstract void InvalidateEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSession); } } 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 3049feb963..aeedc3a346 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 @@ -2288,9 +2288,9 @@ long firstAttemptStart if (ShouldUseEnclaveBasedWorkflow && this.enclavePackage != null) { + EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, - this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, - this.enclavePackage.EnclaveSession); + enclaveSessionParameters, this.enclavePackage.EnclaveSession); } try @@ -3613,13 +3613,14 @@ private SqlDataReader TryFetchInputParameterEncryptionInfo(int timeout, { SqlConnectionAttestationProtocol attestationProtocol = this._activeConnection.AttestationProtocol; string enclaveType = this._activeConnection.Parser.EnclaveType; - string dataSource = this._activeConnection.DataSource; - string enclaveAttestationUrl = this._activeConnection.EnclaveAttestationUrl; + + EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + SqlEnclaveSession sqlEnclaveSession = null; - EnclaveDelegate.Instance.GetEnclaveSession(attestationProtocol, enclaveType, dataSource, enclaveAttestationUrl, true, out sqlEnclaveSession, out customData, out customDataLength); + EnclaveDelegate.Instance.GetEnclaveSession(attestationProtocol, enclaveType, enclaveSessionParameters, true, out sqlEnclaveSession, out customData, out customDataLength); if (sqlEnclaveSession == null) { - enclaveAttestationParameters = EnclaveDelegate.Instance.GetAttestationParameters(attestationProtocol, enclaveType, enclaveAttestationUrl, customData, customDataLength); + enclaveAttestationParameters = EnclaveDelegate.Instance.GetAttestationParameters(attestationProtocol, enclaveType, enclaveSessionParameters.AttestationUrl, customData, customDataLength); serializedAttestationParameters = EnclaveDelegate.Instance.GetSerializedAttestationParameters(enclaveAttestationParameters, enclaveType); } } @@ -4140,10 +4141,9 @@ private void ReadDescribeEncryptionParameterResults(SqlDataReader ds, ReadOnlyDi SqlConnectionAttestationProtocol attestationProtocol = this._activeConnection.AttestationProtocol; string enclaveType = this._activeConnection.Parser.EnclaveType; - string dataSource = this._activeConnection.DataSource; - string enclaveAttestationUrl = this._activeConnection.EnclaveAttestationUrl; + EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); - EnclaveDelegate.Instance.CreateEnclaveSession(attestationProtocol, enclaveType, dataSource, enclaveAttestationUrl, attestationInfo, enclaveAttestationParameters, customData, customDataLength); + EnclaveDelegate.Instance.CreateEnclaveSession(attestationProtocol, enclaveType, enclaveSessionParameters, attestationInfo, enclaveAttestationParameters, customData, customDataLength); enclaveAttestationParameters = null; attestationInfoRead = true; } @@ -4256,8 +4256,9 @@ internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior if (ShouldUseEnclaveBasedWorkflow && this.enclavePackage != null) { + EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, - this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this.enclavePackage.EnclaveSession); + enclaveSessionParameters, this.enclavePackage.EnclaveSession); } return RunExecuteReader(cmdBehavior, runBehavior, returnStream, null, TdsParserStaticMethods.GetRemainingTimeout(timeout, firstAttemptStart), out task, out usedCache, isAsync, inRetry: true, method: method); @@ -4299,8 +4300,9 @@ internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior if (ShouldUseEnclaveBasedWorkflow && this.enclavePackage != null) { + EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, - this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this.enclavePackage.EnclaveSession); + enclaveSessionParameters, this.enclavePackage.EnclaveSession); } return RunExecuteReader(cmdBehavior, runBehavior, returnStream, null, TdsParserStaticMethods.GetRemainingTimeout(timeout, firstAttemptStart), out task, out usedCache, isAsync, inRetry: true, method: method); @@ -4405,9 +4407,9 @@ private void GenerateEnclavePackage() try { + EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); this.enclavePackage = EnclaveDelegate.Instance.GenerateEnclavePackage(attestationProtocol, keysToBeSentToEnclave, - this.CommandText, enclaveType, this._activeConnection.DataSource, - this._activeConnection.EnclaveAttestationUrl); + this.CommandText, enclaveType, enclaveSessionParameters); } catch (EnclaveDelegate.RetryableEnclaveQueryExecutionException) { diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlEnclaveSession.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlEnclaveSession.cs index 4328123100..fbafb58efa 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlEnclaveSession.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlEnclaveSession.cs @@ -56,4 +56,18 @@ internal SqlEnclaveSession(byte[] sessionKey, long sessionId/*, long counter*/) SessionId = sessionId; } } + + internal class EnclaveSessionParameters + { + internal string ServerName { get; set; } // The name of the SQL Server instance containing the enclave. + internal string AttestationUrl { get; set; } // The endpoint of an attestation service for attesting the enclave. + internal string Database { get; set; } // The database that SqlClient contacts to request an enclave session. + + internal EnclaveSessionParameters(string serverName, string attestationUrl, string database) + { + ServerName = serverName; + AttestationUrl = attestationUrl; + Database = database; + } + } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.NetCoreApp.cs index 1be443edbe..66f3f71a65 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.NetCoreApp.cs @@ -86,9 +86,9 @@ internal abstract class VirtualizationBasedSecurityEnclaveProviderBase : Enclave // When overridden in a derived class, looks up an existing enclave session information in the enclave session cache. // If the enclave provider doesn't implement enclave session caching, this method is expected to return null in the sqlEnclaveSession parameter. - internal override void GetEnclaveSession(string servername, string attestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) + internal override void GetEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) { - GetEnclaveSessionHelper(servername, attestationUrl, false, out sqlEnclaveSession, out counter, out customData, out customDataLength); + GetEnclaveSessionHelper(enclaveSessionParameters, false, out sqlEnclaveSession, out counter, out customData, out customDataLength); } // Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. @@ -101,17 +101,17 @@ internal override SqlEnclaveAttestationParameters GetAttestationParameters(strin } // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache. - internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, string attestationUrl, string servername, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) + internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) { sqlEnclaveSession = null; counter = 0; try { ThreadRetryCache.Remove(Thread.CurrentThread.ManagedThreadId.ToString()); - sqlEnclaveSession = GetEnclaveSessionFromCache(servername, attestationUrl, out counter); + sqlEnclaveSession = GetEnclaveSessionFromCache(enclaveSessionParameters, out counter); if (sqlEnclaveSession == null) { - if (!string.IsNullOrEmpty(attestationUrl)) + if (!string.IsNullOrEmpty(enclaveSessionParameters.AttestationUrl)) { // Deserialize the payload AttestationInfo info = new AttestationInfo(attestationInfo); @@ -120,13 +120,13 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell VerifyEnclavePolicy(info.EnclaveReportPackage); // Perform Attestation per VSM protocol - VerifyAttestationInfo(attestationUrl, info.HealthReport, info.EnclaveReportPackage); + VerifyAttestationInfo(enclaveSessionParameters.AttestationUrl, info.HealthReport, info.EnclaveReportPackage); // Set up shared secret and validate signature byte[] sharedSecret = GetSharedSecret(info.Identity, info.EnclaveDHInfo, clientDHKey); // add session to cache - sqlEnclaveSession = AddEnclaveSessionToCache(attestationUrl, servername, sharedSecret, info.SessionId, out counter); + sqlEnclaveSession = AddEnclaveSessionToCache(enclaveSessionParameters, sharedSecret, info.SessionId, out counter); } else { @@ -141,9 +141,9 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell } // When overridden in a derived class, looks up and evicts an enclave session from the enclave session cache, if the provider implements session caching. - internal override void InvalidateEnclaveSession(string serverName, string enclaveAttestationUrl, SqlEnclaveSession enclaveSessionToInvalidate) + internal override void InvalidateEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSessionToInvalidate) { - InvalidateEnclaveSessionHelper(serverName, enclaveAttestationUrl, enclaveSessionToInvalidate); + InvalidateEnclaveSessionHelper(enclaveSessionParameters, enclaveSessionToInvalidate); } #endregion diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.cs index dea4db7680..a79c4900b8 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.cs @@ -65,9 +65,9 @@ internal class AzureAttestationEnclaveProvider : EnclaveProviderBase #region Internal methods // When overridden in a derived class, looks up an existing enclave session information in the enclave session cache. // If the enclave provider doesn't implement enclave session caching, this method is expected to return null in the sqlEnclaveSession parameter. - internal override void GetEnclaveSession(string servername, string attestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) + internal override void GetEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) { - GetEnclaveSessionHelper(servername, attestationUrl, generateCustomData, out sqlEnclaveSession, out counter, out customData, out customDataLength); + GetEnclaveSessionHelper(enclaveSessionParameters, generateCustomData, out sqlEnclaveSession, out counter, out customData, out customDataLength); } // Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. @@ -81,17 +81,17 @@ internal override SqlEnclaveAttestationParameters GetAttestationParameters(strin } // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache. - internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, string attestationUrl, string servername, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) + internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) { sqlEnclaveSession = null; counter = 0; try { ThreadRetryCache.Remove(Thread.CurrentThread.ManagedThreadId.ToString()); - sqlEnclaveSession = GetEnclaveSessionFromCache(servername, attestationUrl, out counter); + sqlEnclaveSession = GetEnclaveSessionFromCache(enclaveSessionParameters, out counter); if (sqlEnclaveSession == null) { - if (!string.IsNullOrEmpty(attestationUrl) && customData != null && customDataLength > 0) + if (!string.IsNullOrEmpty(enclaveSessionParameters.AttestationUrl) && customData != null && customDataLength > 0) { byte[] nonce = customData; @@ -101,13 +101,13 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell AzureAttestationInfo attestInfo = new AzureAttestationInfo(attestationInfo); // Validate the attestation info - VerifyAzureAttestationInfo(attestationUrl, attestInfo.EnclaveType, attestInfo.AttestationToken.AttestationToken, attestInfo.Identity, nonce); + VerifyAzureAttestationInfo(enclaveSessionParameters.AttestationUrl, attestInfo.EnclaveType, attestInfo.AttestationToken.AttestationToken, attestInfo.Identity, nonce); // Set up shared secret and validate signature byte[] sharedSecret = GetSharedSecret(attestInfo.Identity, nonce, attestInfo.EnclaveType, attestInfo.EnclaveDHInfo, clientDHKey); // add session to cache - sqlEnclaveSession = AddEnclaveSessionToCache(attestationUrl, servername, sharedSecret, attestInfo.SessionId, out counter); + sqlEnclaveSession = AddEnclaveSessionToCache(enclaveSessionParameters, sharedSecret, attestInfo.SessionId, out counter); } else { @@ -117,18 +117,18 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell } finally { - // As per current design, we want to minimize the number of create session calls. To acheive this we block all the GetEnclaveSession calls until the first call to + // As per current design, we want to minimize the number of create session calls. To achieve this we block all the GetEnclaveSession calls until the first call to // GetEnclaveSession -> GetAttestationParameters -> CreateEnclaveSession completes or the event timeout happen. // Case 1: When the first request successfully creates the session, then all outstanding GetEnclaveSession will use the current session. - // Case 2: When the first request unable to create the encalve session (may be due to some error or the first request doesn't require enclave computation) then in those case we set the event timeout to 0. + // Case 2: When the first request unable to create the enclave session (may be due to some error or the first request doesn't require enclave computation) then in those case we set the event timeout to 0. UpdateEnclaveSessionLockStatus(sqlEnclaveSession); } } // When overridden in a derived class, looks up and evicts an enclave session from the enclave session cache, if the provider implements session caching. - internal override void InvalidateEnclaveSession(string serverName, string enclaveAttestationUrl, SqlEnclaveSession enclaveSessionToInvalidate) + internal override void InvalidateEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSessionToInvalidate) { - InvalidateEnclaveSessionHelper(serverName, enclaveAttestationUrl, enclaveSessionToInvalidate); + InvalidateEnclaveSessionHelper(enclaveSessionParameters, enclaveSessionToInvalidate); } #endregion diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveDelegate.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveDelegate.cs index 4201b3545a..09ba954353 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveDelegate.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveDelegate.cs @@ -40,10 +40,9 @@ private EnclaveDelegate() { } /// Keys to be sent to enclave /// /// enclave type - /// server name - /// url for attestation endpoint + /// The set of parameters required for enclave session. /// - internal EnclavePackage GenerateEnclavePackage(SqlConnectionAttestationProtocol attestationProtocol, Dictionary keysTobeSentToEnclave, string queryText, string enclaveType, string serverName, string enclaveAttestationUrl) + internal EnclavePackage GenerateEnclavePackage(SqlConnectionAttestationProtocol attestationProtocol, Dictionary keysTobeSentToEnclave, string queryText, string enclaveType, EnclaveSessionParameters enclaveSessionParameters) { SqlEnclaveSession sqlEnclaveSession = null; @@ -52,43 +51,43 @@ internal EnclavePackage GenerateEnclavePackage(SqlConnectionAttestationProtocol int dummyCustomDataLength; try { - GetEnclaveSession(attestationProtocol, enclaveType, serverName, enclaveAttestationUrl, false, out sqlEnclaveSession, out counter, out dummyCustomData, out dummyCustomDataLength, throwIfNull: true); + GetEnclaveSession(attestationProtocol, enclaveType, enclaveSessionParameters, false, out sqlEnclaveSession, out counter, out dummyCustomData, out dummyCustomDataLength, throwIfNull: true); } catch (Exception e) { throw new RetryableEnclaveQueryExecutionException(e.Message, e); } - List decryptedKeysToBeSentToEnclave = GetDecryptedKeysToBeSentToEnclave(keysTobeSentToEnclave, serverName); + List decryptedKeysToBeSentToEnclave = GetDecryptedKeysToBeSentToEnclave(keysTobeSentToEnclave, enclaveSessionParameters.ServerName); byte[] queryStringHashBytes = ComputeQueryStringHash(queryText); byte[] keyBytePackage = GenerateBytePackageForKeys(counter, queryStringHashBytes, decryptedKeysToBeSentToEnclave); byte[] sessionKey = sqlEnclaveSession.GetSessionKey(); - byte[] encryptedBytePackage = EncryptBytePackage(keyBytePackage, sessionKey, serverName); + byte[] encryptedBytePackage = EncryptBytePackage(keyBytePackage, sessionKey, enclaveSessionParameters.ServerName); byte[] enclaveSessionHandle = BitConverter.GetBytes(sqlEnclaveSession.SessionId); byte[] byteArrayToBeSentToEnclave = CombineByteArrays(new[] { enclaveSessionHandle, encryptedBytePackage }); return new EnclavePackage(byteArrayToBeSentToEnclave, sqlEnclaveSession); } - internal void InvalidateEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, string serverName, string EnclaveAttestationUrl, SqlEnclaveSession enclaveSession) + internal void InvalidateEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSession) { SqlColumnEncryptionEnclaveProvider sqlColumnEncryptionEnclaveProvider = GetEnclaveProvider(attestationProtocol, enclaveType); - sqlColumnEncryptionEnclaveProvider.InvalidateEnclaveSession(serverName, EnclaveAttestationUrl, enclaveSession); + sqlColumnEncryptionEnclaveProvider.InvalidateEnclaveSession(enclaveSessionParameters, enclaveSession); } - internal void GetEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, string serverName, string enclaveAttestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out byte[] customData, out int customDataLength) + internal void GetEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out byte[] customData, out int customDataLength) { long counter; - GetEnclaveSession(attestationProtocol, enclaveType, serverName, enclaveAttestationUrl, generateCustomData, out sqlEnclaveSession, out counter, out customData, out customDataLength, throwIfNull: false); + GetEnclaveSession(attestationProtocol, enclaveType, enclaveSessionParameters, generateCustomData, out sqlEnclaveSession, out counter, out customData, out customDataLength, throwIfNull: false); } - private void GetEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, string serverName, string enclaveAttestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength, bool throwIfNull) + private void GetEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength, bool throwIfNull) { SqlColumnEncryptionEnclaveProvider sqlColumnEncryptionEnclaveProvider = GetEnclaveProvider(attestationProtocol, enclaveType); - sqlColumnEncryptionEnclaveProvider.GetEnclaveSession(serverName, enclaveAttestationUrl, generateCustomData, out sqlEnclaveSession, out counter, out customData, out customDataLength); + sqlColumnEncryptionEnclaveProvider.GetEnclaveSession(enclaveSessionParameters, generateCustomData, out sqlEnclaveSession, out counter, out customData, out customDataLength); if (throwIfNull && sqlEnclaveSession == null) { - throw SQL.NullEnclaveSessionDuringQueryExecution(enclaveType, enclaveAttestationUrl); + throw SQL.NullEnclaveSessionDuringQueryExecution(enclaveType, enclaveSessionParameters.AttestationUrl); } } @@ -157,13 +156,12 @@ private byte[] GetUintBytes(string enclaveType, int intValue, string variableNam /// /// attestation protocol /// enclave type - /// servername - /// attestation url for attestation service endpoint + /// The set of parameters required for enclave session. /// attestation info from SQL Server /// attestation parameters /// A set of extra data needed for attestating the enclave. /// The length of the extra data needed for attestating the enclave. - internal void CreateEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, string serverName, string attestationUrl, + internal void CreateEnclaveSession(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, EnclaveSessionParameters enclaveSessionParameters, byte[] attestationInfo, SqlEnclaveAttestationParameters attestationParameters, byte[] customData, int customDataLength) { @@ -174,18 +172,18 @@ internal void CreateEnclaveSession(SqlConnectionAttestationProtocol attestationP SqlEnclaveSession sqlEnclaveSession = null; byte[] dummyCustomData = null; int dummyCustomDataLength; - sqlColumnEncryptionEnclaveProvider.GetEnclaveSession(serverName, attestationUrl, false, out sqlEnclaveSession, out counter, out dummyCustomData, out dummyCustomDataLength); + sqlColumnEncryptionEnclaveProvider.GetEnclaveSession(enclaveSessionParameters, false, out sqlEnclaveSession, out counter, out dummyCustomData, out dummyCustomDataLength); if (sqlEnclaveSession != null) { return; } - sqlColumnEncryptionEnclaveProvider.CreateEnclaveSession(attestationInfo, attestationParameters.ClientDiffieHellmanKey, attestationUrl, serverName, customData, customDataLength, out sqlEnclaveSession, out counter); + sqlColumnEncryptionEnclaveProvider.CreateEnclaveSession(attestationInfo, attestationParameters.ClientDiffieHellmanKey, enclaveSessionParameters, customData, customDataLength, out sqlEnclaveSession, out counter); if (sqlEnclaveSession == null) { - throw SQL.NullEnclaveSessionReturnedFromProvider(enclaveType, attestationUrl); + throw SQL.NullEnclaveSessionReturnedFromProvider(enclaveType, enclaveSessionParameters.AttestationUrl); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveProviderBase.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveProviderBase.cs index 03a49f34f1..77937a470f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveProviderBase.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveProviderBase.cs @@ -89,11 +89,11 @@ internal abstract class EnclaveProviderBase : SqlColumnEncryptionEnclaveProvider #region Public methods // Helper method to get the enclave session from the cache if present - protected void GetEnclaveSessionHelper(string servername, string attestationUrl, bool shouldGenerateNonce, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) + protected void GetEnclaveSessionHelper(EnclaveSessionParameters enclaveSessionParameters, bool shouldGenerateNonce, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) { customData = null; customDataLength = 0; - sqlEnclaveSession = SessionCache.GetEnclaveSession(servername, attestationUrl, out counter); + sqlEnclaveSession = SessionCache.GetEnclaveSession(enclaveSessionParameters, out counter); if (sqlEnclaveSession == null) { @@ -128,7 +128,7 @@ protected void GetEnclaveSessionHelper(string servername, string attestationUrl, { // While the current thread is waiting for event to be signaled and in the meanwhile we already completed the attestation on different thread // then we need to signal the event here - sqlEnclaveSession = SessionCache.GetEnclaveSession(servername, attestationUrl, out counter); + sqlEnclaveSession = SessionCache.GetEnclaveSession(enclaveSessionParameters, out counter); if (sqlEnclaveSession != null && !sameThreadRetry) { lock (lockUpdateSessionLock) @@ -194,21 +194,21 @@ protected void UpdateEnclaveSessionLockStatus(SqlEnclaveSession sqlEnclaveSessio } // Helper method to remove the enclave session from the cache - protected void InvalidateEnclaveSessionHelper(string servername, string attestationUrl, SqlEnclaveSession enclaveSessionToInvalidate) + protected void InvalidateEnclaveSessionHelper(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSessionToInvalidate) { - SessionCache.InvalidateSession(servername, attestationUrl, enclaveSessionToInvalidate); + SessionCache.InvalidateSession(enclaveSessionParameters, enclaveSessionToInvalidate); } // Helper method for getting the enclave session from the session cache - protected SqlEnclaveSession GetEnclaveSessionFromCache(string attestationUrl, string servername, out long counter) + protected SqlEnclaveSession GetEnclaveSessionFromCache(EnclaveSessionParameters enclaveSessionParameters, out long counter) { - return SessionCache.GetEnclaveSession(servername, attestationUrl, out counter); + return SessionCache.GetEnclaveSession(enclaveSessionParameters, out counter); } // Helper method for adding the enclave session to the session cache - protected SqlEnclaveSession AddEnclaveSessionToCache(string attestationUrl, string servername, byte[] sharedSecret, long sessionId, out long counter) + protected SqlEnclaveSession AddEnclaveSessionToCache(EnclaveSessionParameters enclaveSessionParameters, byte[] sharedSecret, long sessionId, out long counter) { - return SessionCache.CreateSession(attestationUrl, servername, sharedSecret, sessionId, out counter); + return SessionCache.CreateSession(enclaveSessionParameters, sharedSecret, sessionId, out counter); } } #endregion diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveSessionCache.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveSessionCache.cs index 5cf0590d06..98aacdc635 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveSessionCache.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/EnclaveSessionCache.cs @@ -22,23 +22,23 @@ internal class EnclaveSessionCache private static int enclaveCacheTimeOutInHours = 8; // Retrieves a SqlEnclaveSession from the cache - internal SqlEnclaveSession GetEnclaveSession(string servername, string attestationUrl, out long counter) + internal SqlEnclaveSession GetEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, out long counter) { - string cacheKey = GenerateCacheKey(servername, attestationUrl); + string cacheKey = GenerateCacheKey(enclaveSessionParameters); SqlEnclaveSession enclaveSession = enclaveMemoryCache[cacheKey] as SqlEnclaveSession; counter = Interlocked.Increment(ref _counter); return enclaveSession; } // Invalidates a SqlEnclaveSession entry in the cache - internal void InvalidateSession(string serverName, string enclaveAttestationUrl, SqlEnclaveSession enclaveSessionToInvalidate) + internal void InvalidateSession(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSessionToInvalidate) { - string cacheKey = GenerateCacheKey(serverName, enclaveAttestationUrl); + string cacheKey = GenerateCacheKey(enclaveSessionParameters); lock (enclaveCacheLock) { long counter; - SqlEnclaveSession enclaveSession = GetEnclaveSession(serverName, enclaveAttestationUrl, out counter); + SqlEnclaveSession enclaveSession = GetEnclaveSession(enclaveSessionParameters, out counter); if (enclaveSession != null && enclaveSession.SessionId == enclaveSessionToInvalidate.SessionId) { @@ -52,9 +52,9 @@ internal void InvalidateSession(string serverName, string enclaveAttestationUrl, } // Creates a new SqlEnclaveSession and adds it to the cache - internal SqlEnclaveSession CreateSession(string attestationUrl, string serverName, byte[] sharedSecret, long sessionId, out long counter) + internal SqlEnclaveSession CreateSession(EnclaveSessionParameters enclaveSessionParameters, byte[] sharedSecret, long sessionId, out long counter) { - string cacheKey = GenerateCacheKey(serverName, attestationUrl); + string cacheKey = GenerateCacheKey(enclaveSessionParameters); SqlEnclaveSession enclaveSession = null; lock (enclaveCacheLock) { @@ -67,9 +67,9 @@ internal SqlEnclaveSession CreateSession(string attestationUrl, string serverNam } // Generates the cache key for the enclave session cache - private string GenerateCacheKey(string serverName, string attestationUrl) + private string GenerateCacheKey(EnclaveSessionParameters enclaveSessionParameters) { - return (serverName + attestationUrl).ToLowerInvariant(); + return (enclaveSessionParameters.ServerName + '+' + enclaveSessionParameters.Database + enclaveSessionParameters.AttestationUrl).ToLowerInvariant(); } - } + } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.cs index cf9af48632..064742be3c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.cs @@ -22,13 +22,12 @@ internal class SimulatorEnclaveProvider : EnclaveProviderBase // When overridden in a derived class, looks up an existing enclave session information in the enclave session cache. // If the enclave provider doesn't implement enclave session caching, this method is expected to return null in the sqlEnclaveSession parameter. - internal override void GetEnclaveSession(string servername, string attestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) + internal override void GetEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) { - GetEnclaveSessionHelper(servername, attestationUrl, false, out sqlEnclaveSession, out counter, out customData, out customDataLength); + GetEnclaveSessionHelper(enclaveSessionParameters, false, out sqlEnclaveSession, out counter, out customData, out customDataLength); } // Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. - // The information SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. internal override SqlEnclaveAttestationParameters GetAttestationParameters(string attestationUrl, byte[] customData, int customDataLength) { ECDiffieHellmanCng clientDHKey = new ECDiffieHellmanCng(384); @@ -39,7 +38,7 @@ internal override SqlEnclaveAttestationParameters GetAttestationParameters(strin } // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache. - internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, string attestationUrl, string servername, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) + internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) { ////for simulator: enclave does not send public key, and sends an empty attestation info //// The only non-trivial content it sends is the session setup info (DH pubkey of enclave) @@ -49,11 +48,11 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell try { ThreadRetryCache.Remove(Thread.CurrentThread.ManagedThreadId.ToString()); - sqlEnclaveSession = GetEnclaveSessionFromCache(servername, attestationUrl, out counter); + sqlEnclaveSession = GetEnclaveSessionFromCache(enclaveSessionParameters, out counter); if (sqlEnclaveSession == null) { - if (!string.IsNullOrEmpty(attestationUrl)) + if (!string.IsNullOrEmpty(enclaveSessionParameters.AttestationUrl)) { ////Read AttestationInfo int attestationInfoOffset = 0; @@ -88,7 +87,7 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell CngKey k = CngKey.Import(trustedModuleDHPublicKey, CngKeyBlobFormat.EccPublicBlob); byte[] sharedSecret = clientDHKey.DeriveKeyMaterial(k); long sessionId = BitConverter.ToInt64(enclaveSessionHandle, 0); - sqlEnclaveSession = AddEnclaveSessionToCache(attestationUrl, servername, sharedSecret, sessionId, out counter); + sqlEnclaveSession = AddEnclaveSessionToCache(enclaveSessionParameters, sharedSecret, sessionId, out counter); } else { @@ -105,12 +104,11 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell /// /// When overridden in a derived class, looks up and evicts an enclave session from the enclave session cache, if the provider implements session caching. /// - /// The name of the SQL Server instance containing the enclave. - /// The endpoint of an attestation service, SqlClient contacts to attest the enclave. + /// The set of parameters required for enclave session. /// The session to be invalidated. - internal override void InvalidateEnclaveSession(string serverName, string enclaveAttestationUrl, SqlEnclaveSession enclaveSessionToInvalidate) + internal override void InvalidateEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSessionToInvalidate) { - InvalidateEnclaveSessionHelper(serverName, enclaveAttestationUrl, enclaveSessionToInvalidate); + InvalidateEnclaveSessionHelper(enclaveSessionParameters, enclaveSessionToInvalidate); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.cs index d29e7d1643..00f05363bc 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.cs @@ -11,15 +11,15 @@ internal abstract class SqlColumnEncryptionEnclaveProvider { /// - internal abstract void GetEnclaveSession(string serverName, string attestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength); + internal abstract void GetEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength); /// internal abstract SqlEnclaveAttestationParameters GetAttestationParameters(string attestationUrl, byte[] customData, int customDataLength); /// - internal abstract void CreateEnclaveSession(byte[] enclaveAttestationInfo, ECDiffieHellmanCng clientDiffieHellmanKey, string attestationUrl, string servername, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter); + internal abstract void CreateEnclaveSession(byte[] enclaveAttestationInfo, ECDiffieHellmanCng clientDiffieHellmanKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter); /// - internal abstract void InvalidateEnclaveSession(string serverName, string enclaveAttestationUrl, SqlEnclaveSession enclaveSession); + internal abstract void InvalidateEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSession); } } 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 09d7ba3bbe..26db371812 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 @@ -2714,7 +2714,8 @@ private bool TriggerInternalEndAndRetryIfNecessary(CommandBehavior behavior, obj if (ShouldUseEnclaveBasedWorkflow && this.enclavePackage != null) { - EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this.enclavePackage.EnclaveSession); + EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, enclaveSessionParameters, this.enclavePackage.EnclaveSession); } try @@ -4255,13 +4256,14 @@ private SqlDataReader TryFetchInputParameterEncryptionInfo(int timeout, { SqlConnectionAttestationProtocol attestationProtocol = this._activeConnection.AttestationProtocol; string enclaveType = this._activeConnection.Parser.EnclaveType; - string dataSource = this._activeConnection.DataSource; - string enclaveAttestationUrl = this._activeConnection.EnclaveAttestationUrl; + + EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + SqlEnclaveSession sqlEnclaveSession = null; - EnclaveDelegate.Instance.GetEnclaveSession(attestationProtocol, enclaveType, dataSource, enclaveAttestationUrl, true, out sqlEnclaveSession, out customData, out customDataLength); + EnclaveDelegate.Instance.GetEnclaveSession(attestationProtocol, enclaveType, enclaveSessionParameters, true, out sqlEnclaveSession, out customData, out customDataLength); if (sqlEnclaveSession == null) { - this.enclaveAttestationParameters = EnclaveDelegate.Instance.GetAttestationParameters(attestationProtocol, enclaveType, enclaveAttestationUrl, customData, customDataLength); + this.enclaveAttestationParameters = EnclaveDelegate.Instance.GetAttestationParameters(attestationProtocol, enclaveType, enclaveSessionParameters.AttestationUrl, customData, customDataLength); serializedAttestatationParameters = EnclaveDelegate.Instance.GetSerializedAttestationParameters(this.enclaveAttestationParameters, enclaveType); } } @@ -4792,10 +4794,10 @@ private void ReadDescribeEncryptionParameterResults(SqlDataReader ds, ReadOnlyDi SqlConnectionAttestationProtocol attestationProtocol = this._activeConnection.AttestationProtocol; string enclaveType = this._activeConnection.Parser.EnclaveType; - string dataSource = this._activeConnection.DataSource; - string enclaveAttestationUrl = this._activeConnection.EnclaveAttestationUrl; + + EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); - EnclaveDelegate.Instance.CreateEnclaveSession(attestationProtocol, enclaveType, dataSource, enclaveAttestationUrl, attestationInfo, enclaveAttestationParameters, customData, customDataLength); + EnclaveDelegate.Instance.CreateEnclaveSession(attestationProtocol, enclaveType, enclaveSessionParameters, attestationInfo, enclaveAttestationParameters, customData, customDataLength); enclaveAttestationParameters = null; attestationInfoRead = true; } @@ -4929,8 +4931,9 @@ internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior if (ShouldUseEnclaveBasedWorkflow && this.enclavePackage != null) { + EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, - this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this.enclavePackage.EnclaveSession); + enclaveSessionParameters, this.enclavePackage.EnclaveSession); } return RunExecuteReader(cmdBehavior, runBehavior, returnStream, method, null, TdsParserStaticMethods.GetRemainingTimeout(timeout, firstAttemptStart), out task, out usedCache, async, inRetry: true); @@ -4972,8 +4975,9 @@ internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior if (ShouldUseEnclaveBasedWorkflow && this.enclavePackage != null) { + EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, - this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this.enclavePackage.EnclaveSession); + enclaveSessionParameters, this.enclavePackage.EnclaveSession); } return RunExecuteReader(cmdBehavior, runBehavior, returnStream, method, null, TdsParserStaticMethods.GetRemainingTimeout(timeout, firstAttemptStart), out task, out usedCache, async, inRetry: true); @@ -5116,9 +5120,9 @@ private void GenerateEnclavePackage() try { + EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); this.enclavePackage = EnclaveDelegate.Instance.GenerateEnclavePackage(attestationProtocol, keysToBeSentToEnclave, - this.CommandText, enclaveType, this._activeConnection.DataSource, - this._activeConnection.EnclaveAttestationUrl); + this.CommandText, enclaveType, enclaveSessionParameters); } catch (EnclaveDelegate.RetryableEnclaveQueryExecutionException) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlEnclaveSession.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlEnclaveSession.cs index 032f9d006d..a2d0cf56a4 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlEnclaveSession.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlEnclaveSession.cs @@ -53,4 +53,18 @@ internal SqlEnclaveSession(byte[] sessionKey, long sessionId/*, long counter*/) SessionId = sessionId; } } + + internal class EnclaveSessionParameters + { + internal string ServerName { get; set; } // The name of the SQL Server instance containing the enclave. + internal string AttestationUrl { get; set; } // The endpoint of an attestation service for attesting the enclave. + internal string Database { get; set; } // The database that SqlClient contacts to request an enclave session. + + internal EnclaveSessionParameters(string serverName, string attestationUrl, string database) + { + ServerName = serverName; + AttestationUrl = attestationUrl; + Database = database; + } + } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.cs index 73da211f7e..6f7c62ce66 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.cs @@ -86,13 +86,12 @@ internal abstract class VirtualizationBasedSecurityEnclaveProviderBase : Enclave // When overridden in a derived class, looks up an existing enclave session information in the enclave session cache. // If the enclave provider doesn't implement enclave session caching, this method is expected to return null in the sqlEnclaveSession parameter. - internal override void GetEnclaveSession(string servername, string attestationUrl, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) + internal override void GetEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, bool generateCustomData, out SqlEnclaveSession sqlEnclaveSession, out long counter, out byte[] customData, out int customDataLength) { - GetEnclaveSessionHelper(servername, attestationUrl, false, out sqlEnclaveSession, out counter, out customData, out customDataLength); + GetEnclaveSessionHelper(enclaveSessionParameters, false, out sqlEnclaveSession, out counter, out customData, out customDataLength); } // Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. - // The information SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. internal override SqlEnclaveAttestationParameters GetAttestationParameters(string attestationUrl, byte[] customData, int customDataLength) { ECDiffieHellmanCng clientDHKey = new ECDiffieHellmanCng(DiffieHellmanKeySize); @@ -102,17 +101,17 @@ internal override SqlEnclaveAttestationParameters GetAttestationParameters(strin } // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache. - internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, string attestationUrl, string servername, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) + internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) { sqlEnclaveSession = null; counter = 0; try { ThreadRetryCache.Remove(Thread.CurrentThread.ManagedThreadId.ToString()); - sqlEnclaveSession = GetEnclaveSessionFromCache(servername, attestationUrl, out counter); + sqlEnclaveSession = GetEnclaveSessionFromCache(enclaveSessionParameters, out counter); if (sqlEnclaveSession == null) { - if (!string.IsNullOrEmpty(attestationUrl)) + if (!string.IsNullOrEmpty(enclaveSessionParameters.AttestationUrl)) { // Deserialize the payload AttestationInfo info = new AttestationInfo(attestationInfo); @@ -121,13 +120,13 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell VerifyEnclavePolicy(info.EnclaveReportPackage); // Perform Attestation per VSM protocol - VerifyAttestationInfo(attestationUrl, info.HealthReport, info.EnclaveReportPackage); + VerifyAttestationInfo(enclaveSessionParameters.AttestationUrl, info.HealthReport, info.EnclaveReportPackage); // Set up shared secret and validate signature byte[] sharedSecret = GetSharedSecret(info.Identity, info.EnclaveDHInfo, clientDHKey); // add session to cache - sqlEnclaveSession = AddEnclaveSessionToCache(attestationUrl, servername, sharedSecret, info.SessionId, out counter); + sqlEnclaveSession = AddEnclaveSessionToCache(enclaveSessionParameters, sharedSecret, info.SessionId, out counter); } else { @@ -142,9 +141,9 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell } // When overridden in a derived class, looks up and evicts an enclave session from the enclave session cache, if the provider implements session caching. - internal override void InvalidateEnclaveSession(string serverName, string enclaveAttestationUrl, SqlEnclaveSession enclaveSessionToInvalidate) + internal override void InvalidateEnclaveSession(EnclaveSessionParameters enclaveSessionParameters, SqlEnclaveSession enclaveSessionToInvalidate) { - InvalidateEnclaveSessionHelper(serverName, enclaveAttestationUrl, enclaveSessionToInvalidate); + InvalidateEnclaveSessionHelper(enclaveSessionParameters, enclaveSessionToInvalidate); } #endregion diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/EnclaveAzureDatabaseTests.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/EnclaveAzureDatabaseTests.cs new file mode 100644 index 0000000000..d90529976d --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/EnclaveAzureDatabaseTests.cs @@ -0,0 +1,185 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information.using System; + +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using System.Threading.Tasks; +using Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider; +using Microsoft.Data.SqlClient.ManualTesting.Tests; +using Xunit; +using Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted.Setup; + +namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted +{ + // This test class is for internal use only + public class EnclaveAzureDatabaseTests : IDisposable + { + private ColumnMasterKey akvColumnMasterKey; + private ColumnEncryptionKey akvColumnEncryptionKey; + private SqlColumnEncryptionAzureKeyVaultProvider sqlColumnEncryptionAzureKeyVaultProvider; + private List databaseObjects = new List(); + private List connStrings = new List(); + + public EnclaveAzureDatabaseTests() + { + if (DataTestUtility.IsEnclaveAzureDatabaseSetup()) + { + // Initialize AKV provider + sqlColumnEncryptionAzureKeyVaultProvider = new SqlColumnEncryptionAzureKeyVaultProvider(AADUtility.AzureActiveDirectoryAuthenticationCallback); + + if (!SQLSetupStrategyAzureKeyVault.isAKVProviderRegistered) + { + // Register AKV provider + SqlConnection.RegisterColumnEncryptionKeyStoreProviders(customProviders: new Dictionary(capacity: 1, comparer: StringComparer.OrdinalIgnoreCase) + { + { SqlColumnEncryptionAzureKeyVaultProvider.ProviderName, sqlColumnEncryptionAzureKeyVaultProvider} + }); + + SQLSetupStrategyAzureKeyVault.isAKVProviderRegistered = true; + } + + akvColumnMasterKey = new AkvColumnMasterKey(DatabaseHelper.GenerateUniqueName("AKVCMK"), akvUrl: DataTestUtility.AKVUrl, sqlColumnEncryptionAzureKeyVaultProvider, DataTestUtility.EnclaveEnabled); + databaseObjects.Add(akvColumnMasterKey); + + akvColumnEncryptionKey= new ColumnEncryptionKey(DatabaseHelper.GenerateUniqueName("AKVCEK"), + akvColumnMasterKey, + sqlColumnEncryptionAzureKeyVaultProvider); + databaseObjects.Add(akvColumnEncryptionKey); + + SqlConnectionStringBuilder connString1 = new SqlConnectionStringBuilder(DataTestUtility.EnclaveAzureDatabaseConnString); + connString1.InitialCatalog = "testdb001"; + + SqlConnectionStringBuilder connString2 = new SqlConnectionStringBuilder(DataTestUtility.EnclaveAzureDatabaseConnString); + connString2.InitialCatalog = "testdb002"; + + connStrings.Add(connString1.ToString()); + connStrings.Add(connString2.ToString()); + + foreach (string connString in connStrings) + { + using (SqlConnection connection = new SqlConnection(connString)) + { + connection.Open(); + databaseObjects.ForEach(o => o.Create(connection)); + } + } + } + } + + [PlatformSpecific(TestPlatforms.Windows)] + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsEnclaveAzureDatabaseSetup))] + public void ConnectToAzureDatabaseWithEnclave() + { + string tableName = DatabaseHelper.GenerateUniqueName("AzureTable"); + + foreach (string connString in connStrings) + { + using (SqlConnection sqlConnection = new SqlConnection(connString)) + { + sqlConnection.Open(); + + Customer customer = new Customer(1, @"Microsoft", @"Corporation"); + + try + { + CreateTable(sqlConnection, akvColumnEncryptionKey.Name, tableName); + InsertData(sqlConnection, tableName, customer); + VerifyData(sqlConnection, tableName, customer); + } + finally + { + DropTableIfExists(sqlConnection, tableName); + } + } + } + } + + private void CreateTable(SqlConnection sqlConnection, string cekName, string tableName) + { + string ColumnEncryptionAlgorithmName = @"AEAD_AES_256_CBC_HMAC_SHA_256"; + string sql = + $@"CREATE TABLE [dbo].[{tableName}] + ( + [CustomerId] [int] ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [{cekName}], ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = '{ColumnEncryptionAlgorithmName}'), + [FirstName] [nvarchar](50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [{cekName}], ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = '{ColumnEncryptionAlgorithmName}'), + [LastName] [nvarchar](50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [{cekName}], ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = '{ColumnEncryptionAlgorithmName}') + )"; + using (SqlCommand command = sqlConnection.CreateCommand()) + { + command.CommandText = sql; + command.ExecuteNonQuery(); + } + } + + private void InsertData(SqlConnection sqlConnection, string tableName, Customer newCustomer) + { + string insertSql = $"INSERT INTO [{tableName}] (CustomerId, FirstName, LastName) VALUES (@CustomerId, @FirstName, @LastName);"; + using (SqlTransaction sqlTransaction = sqlConnection.BeginTransaction()) + using (SqlCommand sqlCommand = new SqlCommand(insertSql, + connection: sqlConnection, transaction: sqlTransaction, + columnEncryptionSetting: SqlCommandColumnEncryptionSetting.Enabled)) + { + sqlCommand.Parameters.AddWithValue(@"CustomerId", newCustomer.Id); + sqlCommand.Parameters.AddWithValue(@"FirstName", newCustomer.FirstName); + sqlCommand.Parameters.AddWithValue(@"LastName", newCustomer.LastName); + sqlCommand.ExecuteNonQuery(); + sqlTransaction.Commit(); + } + } + + private void VerifyData(SqlConnection sqlConnection, string tableName, Customer customer) + { + // Test INPUT parameter on an encrypted parameter + using (SqlCommand sqlCommand = new SqlCommand($"SELECT CustomerId, FirstName, LastName FROM [{tableName}] WHERE FirstName = @firstName", + sqlConnection)) + { + SqlParameter customerFirstParam = sqlCommand.Parameters.AddWithValue(@"firstName", @"Microsoft"); + customerFirstParam.Direction = System.Data.ParameterDirection.Input; + customerFirstParam.ForceColumnEncryption = true; + using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader()) + { + ValidateResultSet(sqlDataReader); + } + } + } + + private void ValidateResultSet(SqlDataReader sqlDataReader) + { + Assert.True(sqlDataReader.HasRows, "We didn't find any rows."); + while (sqlDataReader.Read()) + { + Assert.True(sqlDataReader.GetInt32(0) == 1, "Employee Id didn't match"); + Assert.True(sqlDataReader.GetString(1) == @"Microsoft", "Employee FirstName didn't match."); + Assert.True(sqlDataReader.GetString(2) == @"Corporation", "Employee LastName didn't match."); + } + } + + private void DropTableIfExists(SqlConnection sqlConnection, string tableName) + { + string cmdText = $@"IF EXISTS (select * from sys.objects where name = '{tableName}') BEGIN DROP TABLE [{tableName}] END"; + using (SqlCommand command = sqlConnection.CreateCommand()) + { + command.CommandText = cmdText; + command.ExecuteNonQuery(); + } + } + + public void Dispose() + { + if (DataTestUtility.IsEnclaveAzureDatabaseSetup()) + { + databaseObjects.Reverse(); + foreach (string connStr in connStrings) + { + using (SqlConnection sqlConnection = new SqlConnection(connStr)) + { + sqlConnection.Open(); + databaseObjects.ForEach(o => o.Drop(sqlConnection)); + } + } + } + } + } +} diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/SQLSetupStrategyAzureKeyVault.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/SQLSetupStrategyAzureKeyVault.cs index 288e6f069a..3086235852 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/SQLSetupStrategyAzureKeyVault.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/SQLSetupStrategyAzureKeyVault.cs @@ -11,7 +11,7 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted { public class SQLSetupStrategyAzureKeyVault : SQLSetupStrategy { - private static bool isAKVProviderRegistered = false; + internal static bool isAKVProviderRegistered = false; public Table AKVTestTable { get; private set; } public SqlColumnEncryptionAzureKeyVaultProvider AkvStoreProvider; @@ -36,7 +36,7 @@ public SQLSetupStrategyAzureKeyVault() : base() internal override void SetupDatabase() { - ColumnMasterKey akvColumnMasterKey = new AkvColumnMasterKey(GenerateUniqueName("AKVCMK"), akvUrl: DataTestUtility.AKVUrl); + ColumnMasterKey akvColumnMasterKey = new AkvColumnMasterKey(GenerateUniqueName("AKVCMK"), akvUrl: DataTestUtility.AKVUrl, AkvStoreProvider, DataTestUtility.EnclaveEnabled); databaseObjects.Add(akvColumnMasterKey); List akvColumnEncryptionKeys = CreateColumnEncryptionKeys(akvColumnMasterKey, 2, AkvStoreProvider); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/AkvColumnMasterKey.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/AkvColumnMasterKey.cs index 5f3f51f72e..a9469d79b6 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/AkvColumnMasterKey.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/AkvColumnMasterKey.cs @@ -2,16 +2,22 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; + namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted.Setup { public class AkvColumnMasterKey : ColumnMasterKey { public override string KeyPath { get; } - public AkvColumnMasterKey(string name, string akvUrl) : base(name) + public AkvColumnMasterKey(string name, string akvUrl, SqlColumnEncryptionKeyStoreProvider akvProvider, bool allowEnclaveComputations) : base(name) { KeyStoreProviderName = @"AZURE_KEY_VAULT"; KeyPath = akvUrl; + + // For keys which allow enclave computation + byte[] cmkSign = akvProvider.SignColumnMasterKeyMetadata(akvUrl, allowEnclaveComputations); + cmkSignStr = string.Concat("0x", BitConverter.ToString(cmkSign).Replace("-", string.Empty)); } } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/CspColumnMasterKey.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/CspColumnMasterKey.cs index 22b31ab888..9e26b1105e 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/CspColumnMasterKey.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/CspColumnMasterKey.cs @@ -14,21 +14,21 @@ public class CspColumnMasterKey : ColumnMasterKey public string Thumbprint { get; } public override string KeyPath { get; } - public CspColumnMasterKey(string name, string certificateThumbprint, SqlColumnEncryptionKeyStoreProvider certStoreProvider, bool allEnclaveComputations) : base(name) + public CspColumnMasterKey(string name, string certificateThumbprint, SqlColumnEncryptionKeyStoreProvider certStoreProvider, bool allowEnclaveComputations) : base(name) { KeyStoreProviderName = @"MSSQL_CERTIFICATE_STORE"; Thumbprint = certificateThumbprint; KeyPath = string.Concat(CertificateStoreLocation.ToString(), "/", CertificateStoreName.ToString(), "/", Thumbprint); - byte[] cmkSign = certStoreProvider.SignColumnMasterKeyMetadata(KeyPath, allEnclaveComputations); + byte[] cmkSign = certStoreProvider.SignColumnMasterKeyMetadata(KeyPath, allowEnclaveComputations); cmkSignStr = string.Concat("0x", BitConverter.ToString(cmkSign).Replace("-", string.Empty)); } - public CspColumnMasterKey(string name, string providerName, string cspKeyPath, SqlColumnEncryptionKeyStoreProvider certStoreProvider, bool allEnclaveComputations) : base(name) + public CspColumnMasterKey(string name, string providerName, string cspKeyPath, SqlColumnEncryptionKeyStoreProvider certStoreProvider, bool allowEnclaveComputations) : base(name) { KeyStoreProviderName = providerName; KeyPath = cspKeyPath; - byte[] cmkSign = certStoreProvider.SignColumnMasterKeyMetadata(KeyPath, allEnclaveComputations); + byte[] cmkSign = certStoreProvider.SignColumnMasterKeyMetadata(KeyPath, allowEnclaveComputations); cmkSignStr = string.Concat("0x", BitConverter.ToString(cmkSign).Replace("-", string.Empty)); } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs index 1e8fa398c6..60b506533e 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs @@ -49,6 +49,8 @@ public static class DataTestUtility public static readonly bool IsDNSCachingSupportedCR = false; // this is for the control ring public static readonly bool IsDNSCachingSupportedTR = false; // this is for the tenant ring + public static readonly string EnclaveAzureDatabaseConnString = null; + public const string UdtTestDbName = "UdtTestDb"; public const string AKVKeyName = "TestSqlClientAzureKeyVaultProvider"; private const string ManagedNetworkingAppContextSwitch = "Switch.Microsoft.Data.SqlClient.UseManagedNetworkingOnWindows"; @@ -86,6 +88,7 @@ private class Config public string DNSCachingServerTR = null; // this is for the tenant ring public bool IsDNSCachingSupportedCR = false; // this is for the control ring public bool IsDNSCachingSupportedTR = false; // this is for the tenant ring + public string EnclaveAzureDatabaseConnString = null; } static DataTestUtility() @@ -117,6 +120,8 @@ static DataTestUtility() IsDNSCachingSupportedCR = c.IsDNSCachingSupportedCR; IsDNSCachingSupportedTR = c.IsDNSCachingSupportedTR; + EnclaveAzureDatabaseConnString = c.EnclaveAzureDatabaseConnString; + if (TracingEnabled) { TraceListener = new DataTestUtility.TraceEventListener(); @@ -284,6 +289,11 @@ public static bool IsSupportedDataClassification() public static bool IsDNSCachingSetup() => !string.IsNullOrEmpty(DNSCachingConnString); + public static bool IsEnclaveAzureDatabaseSetup() + { + return EnclaveEnabled && !string.IsNullOrEmpty(EnclaveAzureDatabaseConnString); + } + public static bool IsUdtTestDatabasePresent() => IsDatabasePresent(UdtTestDbName); public static bool AreConnStringsSetup() diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj index 34bd1e6ead..afbd056adb 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj @@ -26,6 +26,7 @@ + From ec6a2635685b462028c6a3f6a3feb61d9a7d750c Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Fri, 21 Aug 2020 11:45:32 -0700 Subject: [PATCH 07/24] Update config Section name for Microsoft.Data.SqlClient (#702) --- ...uthenticationProviderManager.NetCoreApp.cs | 38 +++++++++++++++++-- .../SqlAuthenticationProviderManager.cs | 38 +++++++++++++++++-- 2 files changed, 69 insertions(+), 7 deletions(-) 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 eb3e03b1e2..52be62e901 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 @@ -20,12 +20,18 @@ static SqlAuthenticationProviderManager() try { - configurationSection = (SqlAuthenticationProviderConfigurationSection)ConfigurationManager.GetSection(SqlAuthenticationProviderConfigurationSection.Name); + // New configuration section "SqlClientAuthenticationProviders" for Microsoft.Data.SqlClient accepted to avoid conflicts with older one. + configurationSection = FetchConfigurationSection(SqlClientAuthenticationProviderConfigurationSection.Name); + if (null == configurationSection) + { + // If configuration section is not yet found, try with old Configuration Section name for backwards compatibility + configurationSection = FetchConfigurationSection(SqlAuthenticationProviderConfigurationSection.Name); + } } catch (ConfigurationErrorsException e) { // Don't throw an error for invalid config files - SqlClientEventSource.Log.TraceEvent("Unable to load custom SqlAuthenticationProviders. ConfigurationManager failed to load due to configuration errors: {0}", e); + SqlClientEventSource.Log.TraceEvent("Unable to load custom SqlAuthenticationProviders or SqlClientAuthenticationProviders. ConfigurationManager failed to load due to configuration errors: {0}", e); } Instance = new SqlAuthenticationProviderManager(configurationSection); @@ -49,7 +55,7 @@ public SqlAuthenticationProviderManager(SqlAuthenticationProviderConfigurationSe if (configSection == null) { - _sqlAuthLogger.LogInfo(_typeName, methodName, "No SqlAuthProviders configuration section found."); + _sqlAuthLogger.LogInfo(_typeName, methodName, "Neither SqlClientAuthenticationProviders nor SqlAuthenticationProviders configuration section found."); return; } @@ -105,6 +111,24 @@ public SqlAuthenticationProviderManager(SqlAuthenticationProviderConfigurationSe } } + private static T FetchConfigurationSection(string name) + { + Type t = typeof(T); + object section = ConfigurationManager.GetSection(name); + if (null != section) + { + if (section is ConfigurationSection configSection && configSection.GetType() == t) + { + return (T)section; + } + else + { + SqlClientEventSource.Log.TraceEvent("Found a custom {0} configuration but it is not of type {1}.", name, t.FullName); + } + } + return default; + } + private static SqlAuthenticationMethod AuthenticationEnumFromString(string authentication) { switch (authentication.ToLowerInvariant()) @@ -143,5 +167,13 @@ internal class SqlAuthenticationProviderConfigurationSection : ConfigurationSect [ConfigurationProperty("initializerType")] public string InitializerType => base["initializerType"] as string; } + + /// + /// The configuration section definition for reading app.config. + /// + internal class SqlClientAuthenticationProviderConfigurationSection : SqlAuthenticationProviderConfigurationSection + { + public new const string Name = "SqlClientAuthenticationProviders"; + } } } 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 144a782acb..af9a603898 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 @@ -27,12 +27,18 @@ static SqlAuthenticationProviderManager() SqlAuthenticationProviderConfigurationSection configurationSection = null; try { - configurationSection = (SqlAuthenticationProviderConfigurationSection)ConfigurationManager.GetSection(SqlAuthenticationProviderConfigurationSection.Name); + // New configuration section "SqlClientAuthenticationProviders" for Microsoft.Data.SqlClient accepted to avoid conflicts with older one. + configurationSection = FetchConfigurationSection(SqlClientAuthenticationProviderConfigurationSection.Name); + if (null == configurationSection) + { + // If configuration section is not yet found, try with old Configuration Section name for backwards compatibility + configurationSection = FetchConfigurationSection(SqlAuthenticationProviderConfigurationSection.Name); + } } catch (ConfigurationErrorsException e) { // Don't throw an error for invalid config files - SqlClientEventSource.Log.TraceEvent("Unable to load custom SqlAuthenticationProviders. ConfigurationManager failed to load due to configuration errors: {0}", e); + SqlClientEventSource.Log.TraceEvent("Unable to load custom SqlAuthenticationProviders or SqlClientAuthenticationProviders. ConfigurationManager failed to load due to configuration errors: {0}", e); } Instance = new SqlAuthenticationProviderManager(configurationSection); Instance.SetProvider(SqlAuthenticationMethod.ActiveDirectoryIntegrated, activeDirectoryAuthProvider); @@ -62,7 +68,7 @@ public SqlAuthenticationProviderManager(SqlAuthenticationProviderConfigurationSe if (configSection == null) { - _sqlAuthLogger.LogInfo(_typeName, methodName, "No SqlAuthProviders configuration section found."); + _sqlAuthLogger.LogInfo(_typeName, methodName, "Neither SqlClientAuthenticationProviders nor SqlAuthenticationProviders configuration section found."); return; } @@ -164,6 +170,24 @@ public bool SetProvider(SqlAuthenticationMethod authenticationMethod, SqlAuthent return true; } + private static T FetchConfigurationSection(string name) + { + Type t = typeof(T); + object section = ConfigurationManager.GetSection(name); + if (null != section) + { + if (section is ConfigurationSection configSection && configSection.GetType() == t) + { + return (T)section; + } + else + { + SqlClientEventSource.Log.TraceEvent("Found a custom {0} configuration but it is not of type {1}.", name, t.FullName); + } + } + return default; + } + private static SqlAuthenticationMethod AuthenticationEnumFromString(string authentication) { switch (authentication.ToLowerInvariant()) @@ -211,11 +235,17 @@ internal class SqlAuthenticationProviderConfigurationSection : ConfigurationSect public string InitializerType => base["initializerType"] as string; } + /// + /// The configuration section definition for reading app.config. + /// + internal class SqlClientAuthenticationProviderConfigurationSection : SqlAuthenticationProviderConfigurationSection + { + public new const string Name = "SqlClientAuthenticationProviders"; + } /// public abstract class SqlAuthenticationInitializer { - /// public abstract void Initialize(); } From e10b230d24eea034d5fe27fb799a2d6629b1d765 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Fri, 21 Aug 2020 14:19:26 -0700 Subject: [PATCH 08/24] Fix | Perform Null check for SqlErrors in SqlException (#698) --- .../Microsoft.Data.SqlClient/SqlException.xml | 26 ++++-- .../src/Microsoft/Data/SqlClient/SqlError.cs | 83 +++++-------------- .../Microsoft/Data/SqlClient/SqlException.cs | 4 +- .../src/Microsoft/Data/SqlClient/SqlError.cs | 83 +++++++++---------- .../Microsoft/Data/SqlClient/SqlException.cs | 25 +++--- 5 files changed, 94 insertions(+), 127 deletions(-) diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlException.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlException.xml index 85604fde46..c5eafa53b1 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlException.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlException.xml @@ -85,7 +85,9 @@ catch (Exception ex) { For information about the warning and informational messages sent by SQL Server, see the Troubleshooting section of the SQL Server documentation. This is a wrapper for the property of the first in the property. - + + If is `null`, the [`default`](https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/default-values) value for `byte` is returned. + ## Examples @@ -161,7 +163,9 @@ catch (Exception ex) { The line numbering starts at 1; if 0 is returned, the line number is not applicable. This is a wrapper for the property of the first in the property. - + + If is `null`, the [`default`](https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/default-values) value for `int` is returned. + ## Examples @@ -190,7 +194,11 @@ catch (Exception ex) { property of the first in the property. For more information on SQL Server engine errors, see [Database Engine Events and Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors). + This is a wrapper for the property of the first in the property. + + If is `null`, the [`default`](https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/default-values) value for `int` is returned. + + For more information on SQL Server engine errors, see [Database Engine Events and Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors). @@ -215,8 +223,9 @@ catch (Exception ex) { property of the first in the property. - + This is a wrapper for the property of the first in the property. + + If is `null`, the [`default`](https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/default-values) value for `string` is returned. ## Examples @@ -241,7 +250,8 @@ catch (Exception ex) { ## Remarks This is a wrapper for the property of the first in the property. - + + If is `null`, the [`default`](https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/default-values) value for `string` is returned. ## Examples @@ -266,7 +276,6 @@ catch (Exception ex) { ## Remarks This is a wrapper for the property of the first in the property. - ## Examples @@ -291,7 +300,8 @@ catch (Exception ex) { ## Remarks This is a wrapper for the property of the first in the property. - + + If is `null`, the [`default`](https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/default-values) value for `byte` is returned. ## Examples diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs index 844f36312f..05c1dd75b5 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs @@ -9,34 +9,23 @@ namespace Microsoft.Data.SqlClient /// public sealed class SqlError { - private string _source = TdsEnums.SQL_PROVIDER_NAME; - private int _number; - private byte _state; - private byte _errorClass; - private string _server; - private string _message; - private string _procedure; - private int _lineNumber; - private int _win32ErrorCode; - private Exception _exception; - internal SqlError(int infoNumber, byte errorState, byte errorClass, string server, string errorMessage, string procedure, int lineNumber, uint win32ErrorCode, Exception exception = null) : this(infoNumber, errorState, errorClass, server, errorMessage, procedure, lineNumber, exception) { - _win32ErrorCode = (int)win32ErrorCode; + Win32ErrorCode = (int)win32ErrorCode; } internal SqlError(int infoNumber, byte errorState, byte errorClass, string server, string errorMessage, string procedure, int lineNumber, Exception exception = null) { - _number = infoNumber; - _state = errorState; - _errorClass = errorClass; - _server = server; - _message = errorMessage; - _procedure = procedure; - _lineNumber = lineNumber; - _win32ErrorCode = 0; - _exception = exception; + Number = infoNumber; + State = errorState; + Class = errorClass; + Server = server; + Message = errorMessage; + Procedure = procedure; + LineNumber = lineNumber; + Win32ErrorCode = 0; + Exception = exception; if (errorClass != 0) { SqlClientEventSource.Log.TraceEvent(" infoNumber={0}, errorState={1}, errorClass={2}, errorMessage='{3}', procedure='{4}', lineNumber={5}", infoNumber, (int)errorState, (int)errorClass, errorMessage, procedure ?? "None", (int)lineNumber); @@ -49,65 +38,35 @@ internal SqlError(int infoNumber, byte errorState, byte errorClass, string serve // way back to SqlException. If the user needs a call stack, they can obtain it on SqlException. public override string ToString() { - return typeof(SqlError).ToString() + ": " + _message; // since this is sealed so we can change GetType to typeof + return typeof(SqlError).ToString() + ": " + Message; // since this is sealed so we can change GetType to typeof } /// - public string Source - { - get { return _source; } - } + public string Source { get; private set; } = TdsEnums.SQL_PROVIDER_NAME; /// - public int Number - { - get { return _number; } - } + public int Number { get; private set; } /// - public byte State - { - get { return _state; } - } + public byte State { get; private set; } /// - public byte Class - { - get { return _errorClass; } - } + public byte Class { get; private set; } /// - public string Server - { - get { return _server; } - } + public string Server { get; private set; } /// - public string Message - { - get { return _message; } - } + public string Message { get; private set; } /// - public string Procedure - { - get { return _procedure; } - } + public string Procedure { get; private set; } /// - public int LineNumber - { - get { return _lineNumber; } - } + public int LineNumber { get; private set; } - internal int Win32ErrorCode - { - get { return _win32ErrorCode; } - } + internal int Win32ErrorCode { get; private set; } - internal Exception Exception - { - get { return _exception; } - } + internal Exception Exception { get; private set; } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlException.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlException.cs index b19798c52f..5f4e952ec8 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlException.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlException.cs @@ -89,7 +89,7 @@ public Guid ClientConnectionId /// public byte Class { - get { return Errors.Count > 0 ? this.Errors[0].Class : default; } + get { return Errors.Count > 0 ? Errors[0].Class : default; } } /// @@ -125,7 +125,7 @@ public byte State /// override public string Source { - get { return Errors.Count > 0 ? Errors[0].Source : default; } + get { return TdsEnums.SQL_PROVIDER_NAME; } } /// diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs index 10ac16d708..feec3a7438 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs @@ -6,109 +6,108 @@ namespace Microsoft.Data.SqlClient { - /// + /// [Serializable] public sealed class SqlError { - // bug fix - MDAC 48965 - missing source of exception - private string source = TdsEnums.SQL_PROVIDER_NAME; - private int number; - private byte state; - private byte errorClass; - [System.Runtime.Serialization.OptionalFieldAttribute(VersionAdded = 2)] - private string server; - private string message; - private string procedure; - private int lineNumber; - [System.Runtime.Serialization.OptionalFieldAttribute(VersionAdded = 4)] - private int win32ErrorCode; + private readonly string _source = TdsEnums.SQL_PROVIDER_NAME; + private readonly int _number; + private readonly byte _state; + private readonly byte _errorClass; + [System.Runtime.Serialization.OptionalField(VersionAdded = 2)] + private readonly string _server; + private readonly string _message; + private readonly string _procedure; + private readonly int _lineNumber; + [System.Runtime.Serialization.OptionalField(VersionAdded = 4)] + private readonly int _win32ErrorCode; internal SqlError(int infoNumber, byte errorState, byte errorClass, string server, string errorMessage, string procedure, int lineNumber, uint win32ErrorCode) : this(infoNumber, errorState, errorClass, server, errorMessage, procedure, lineNumber) { - this.win32ErrorCode = (int)win32ErrorCode; + _win32ErrorCode = (int)win32ErrorCode; } internal SqlError(int infoNumber, byte errorState, byte errorClass, string server, string errorMessage, string procedure, int lineNumber) { - this.number = infoNumber; - this.state = errorState; - this.errorClass = errorClass; - this.server = server; - this.message = errorMessage; - this.procedure = procedure; - this.lineNumber = lineNumber; + _number = infoNumber; + _state = errorState; + _errorClass = errorClass; + _server = server; + _message = errorMessage; + _procedure = procedure; + _lineNumber = lineNumber; if (errorClass != 0) { SqlClientEventSource.Log.TraceEvent(" infoNumber={0}, errorState={1}, errorClass={2}, errorMessage='{3}', procedure='{4}', lineNumber={5}", infoNumber, (int)errorState, (int)errorClass, errorMessage, procedure ?? "None", (int)lineNumber); } - this.win32ErrorCode = 0; + _win32ErrorCode = 0; } - /// + /// // bug fix - MDAC #49280 - SqlError does not implement ToString(); // I did not include an exception stack because the correct exception stack is only available // on SqlException, and to obtain that the SqlError would have to have backpointers all the // way back to SqlException. If the user needs a call stack, they can obtain it on SqlException. public override string ToString() { - //return this.GetType().ToString() + ": " + this.message; - return typeof(SqlError).ToString() + ": " + this.message; // since this is sealed so we can change GetType to typeof + //return GetType().ToString() + ": " + message; + return typeof(SqlError).ToString() + ": " + _message; // since this is sealed so we can change GetType to typeof } - /// + /// // bug fix - MDAC #48965 - missing source of exception public string Source { - get { return this.source; } + get { return _source; } } - /// + /// public int Number { - get { return this.number; } + get { return _number; } } - /// + /// public byte State { - get { return this.state; } + get { return _state; } } - /// + /// public byte Class { - get { return this.errorClass; } + get { return _errorClass; } } - /// + /// public string Server { - get { return this.server; } + get { return _server; } } - /// + /// public string Message { - get { return this.message; } + get { return _message; } } - /// + /// public string Procedure { - get { return this.procedure; } + get { return _procedure; } } - /// + /// public int LineNumber { - get { return this.lineNumber; } + get { return _lineNumber; } } internal int Win32ErrorCode { - get { return this.win32ErrorCode; } + get { return _win32ErrorCode; } } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlException.cs index 627861e6e5..7e4fe9f411 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlException.cs @@ -99,43 +99,43 @@ private bool ShouldSerializeErrors() /// public byte Class { - get { return this.Errors[0].Class; } + get { return Errors.Count > 0 ? Errors[0].Class : default; } } /// public int LineNumber { - get { return this.Errors[0].LineNumber; } + get { return Errors.Count > 0 ? Errors[0].LineNumber : default; } } /// public int Number { - get { return this.Errors[0].Number; } + get { return Errors.Count > 0 ? Errors[0].Number : default; } } /// public string Procedure { - get { return this.Errors[0].Procedure; } + get { return Errors.Count > 0 ? Errors[0].Procedure : default; } } /// public string Server { - get { return this.Errors[0].Server; } + get { return Errors.Count > 0 ? Errors[0].Server : default; } } /// public byte State { - get { return this.Errors[0].State; } + get { return Errors.Count > 0 ? Errors[0].State : default; } } /// override public string Source { - get { return this.Errors[0].Source; } + get { return TdsEnums.SQL_PROVIDER_NAME; } } /// @@ -146,7 +146,7 @@ public override string ToString() sb.AppendFormat(SQLMessage.ExClientConnectionId(), _clientConnectionId); // Append the error number, state and class if the server provided it - if (Number != 0) + if (Errors.Count > 0 && Number != 0) { sb.AppendLine(); sb.AppendFormat(SQLMessage.ExErrorNumberStateClass(), Number, State, Class); @@ -169,12 +169,12 @@ public override string ToString() return sb.ToString(); } - static internal SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion) + internal static SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion) { return CreateException(errorCollection, serverVersion, Guid.Empty); } - static internal SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion, SqlInternalConnectionTds internalConnection, Exception innerException = null) + internal static SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion, SqlInternalConnectionTds internalConnection, Exception innerException = null) { Guid connectionId = (internalConnection == null) ? Guid.Empty : internalConnection._clientConnectionId; var exception = CreateException(errorCollection, serverVersion, connectionId, innerException); @@ -195,11 +195,10 @@ static internal SqlException CreateException(SqlErrorCollection errorCollection, return exception; } - static internal SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion, Guid conId, Exception innerException = null) + internal static SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion, Guid conId, Exception innerException = null) { Debug.Assert(null != errorCollection && errorCollection.Count > 0, "no errorCollection?"); - // concat all messages together MDAC 65533 StringBuilder message = new StringBuilder(); for (int i = 0; i < errorCollection.Count; i++) { @@ -219,7 +218,7 @@ static internal SqlException CreateException(SqlErrorCollection errorCollection, exception.Data.Add("HelpLink.ProdName", "Microsoft SQL Server"); - if (!ADP.IsEmpty(serverVersion)) + if (!string.IsNullOrEmpty(serverVersion)) { exception.Data.Add("HelpLink.ProdVer", serverVersion); } From 146ecd9eab3f802a111bef271de9f838efc1333f Mon Sep 17 00:00:00 2001 From: Johnny Pham <23270162+johnnypham@users.noreply.github.com> Date: Fri, 21 Aug 2020 14:54:48 -0700 Subject: [PATCH 09/24] Feature | AE with enclaves - multi-platform and .NET Standard 2.1 support (#676) --- build.proj | 8 +- ...waysEncrypted.AzureKeyVaultProvider.csproj | 2 +- .../add-ons/Directory.Build.props | 1 + .../ref/Microsoft.Data.SqlClient.csproj | 3 +- .../src/Microsoft.Data.SqlClient.csproj | 39 ++--- ...=> AlwaysEncryptedAttestationException.cs} | 0 ...ncryptedEnclaveProviderUtils.NetCoreApp.cs | 55 ------- .../AlwaysEncryptedEnclaveProviderUtils.cs | 153 ++++++++++++++++++ ...> AzureAttestationBasedEnclaveProvider.cs} | 21 +-- .../SqlClient/EnclaveDelegate.NetCoreApp.cs | 10 +- ...e.NetCoreApp.cs => EnclaveProviderBase.cs} | 0 ...e.NetCoreApp.cs => EnclaveSessionCache.cs} | 0 .../SimulatorEnclaveProvider.NetCoreApp.cs | 13 +- ...ryptionCertificateStoreProvider.Windows.cs | 3 +- ...umnEncryptionEnclaveProvider.NetCoreApp.cs | 2 +- ...EnclaveAttestationParameters.NetCoreApp.cs | 4 +- ...cs => VirtualSecureModeEnclaveProvider.cs} | 0 ...> VirtualSecureModeEnclaveProviderBase.cs} | 39 ++--- .../tests/Directory.Build.props | 9 +- .../Microsoft.Data.SqlClient.Tests.csproj | 10 +- .../SqlConnectionStringBuilderTest.cs | 2 + .../ManualTests/AlwaysEncrypted/ApiShould.cs | 10 +- .../ManualTests/AlwaysEncrypted/BulkCopyAE.cs | 12 +- .../AlwaysEncrypted/BulkCopyAEErrorMessage.cs | 22 ++- .../EnclaveAzureDatabaseTests.cs | 1 - .../AlwaysEncrypted/End2EndSmokeTests.cs | 9 +- .../AlwaysEncrypted/ExceptionTestAKVStore.cs | 2 +- .../AlwaysEncrypted/SqlBulkCopyTruncation.cs | 11 +- .../AlwaysEncrypted/SqlNullValues.cs | 13 +- .../TestFixtures/SQLSetupStrategy.cs | 27 ++++ .../TestFixtures/Setup/AkvColumnMasterKey.cs | 2 +- .../TestFixtures/Setup/ColumnMasterKey.cs | 13 +- .../TestFixtures/Setup/CspColumnMasterKey.cs | 4 +- ....Data.SqlClient.ManualTesting.Tests.csproj | 60 +++---- .../Microsoft.Data.SqlClient.NSLibrary.csproj | 3 +- tools/specs/Microsoft.Data.SqlClient.nuspec | 29 ++++ 36 files changed, 371 insertions(+), 221 deletions(-) rename src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/{AlwaysEncryptedAttestationException.NetCoreApp.cs => AlwaysEncryptedAttestationException.cs} (100%) delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedEnclaveProviderUtils.NetCoreApp.cs create mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedEnclaveProviderUtils.cs rename src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/{AzureAttestationBasedEnclaveProvider.NetCoreApp.cs => AzureAttestationBasedEnclaveProvider.cs} (96%) rename src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/{EnclaveProviderBase.NetCoreApp.cs => EnclaveProviderBase.cs} (100%) rename src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/{EnclaveSessionCache.NetCoreApp.cs => EnclaveSessionCache.cs} (100%) rename src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/{VirtualSecureModeEnclaveProvider.NetCoreApp.cs => VirtualSecureModeEnclaveProvider.cs} (100%) rename src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/{VirtualSecureModeEnclaveProviderBase.NetCoreApp.cs => VirtualSecureModeEnclaveProviderBase.cs} (91%) diff --git a/build.proj b/build.proj index edebcec39e..32f1734db9 100644 --- a/build.proj +++ b/build.proj @@ -25,7 +25,7 @@ - + @@ -34,7 +34,7 @@ - + @@ -116,14 +116,14 @@ - + - + diff --git a/src/Microsoft.Data.SqlClient/add-ons/AzureKeyVaultProvider/Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider.csproj b/src/Microsoft.Data.SqlClient/add-ons/AzureKeyVaultProvider/Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider.csproj index 9a32df9809..77b6e7e1be 100644 --- a/src/Microsoft.Data.SqlClient/add-ons/AzureKeyVaultProvider/Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider.csproj +++ b/src/Microsoft.Data.SqlClient/add-ons/AzureKeyVaultProvider/Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider.csproj @@ -6,7 +6,7 @@ {9073ABEF-92E0-4702-BB23-2C99CEF9BDD7} netcoreapp netfx - Debug;Release;net46-Release;net46-Debug;netcoreapp2.1-Debug;netcoreapp2.1-Release; + Debug;Release;net46-Release;net46-Debug;netcoreapp2.1-Debug;netcoreapp2.1-Release;netcoreapp3.1-Debug;netcoreapp3.1-Release AnyCPU;x86;x64 $(ObjFolder)$(Configuration).$(Platform)\$(AddOnName) $(BinFolder)$(Configuration).$(Platform)\$(AddOnName) diff --git a/src/Microsoft.Data.SqlClient/add-ons/Directory.Build.props b/src/Microsoft.Data.SqlClient/add-ons/Directory.Build.props index 4fc891665f..e2303ef132 100644 --- a/src/Microsoft.Data.SqlClient/add-ons/Directory.Build.props +++ b/src/Microsoft.Data.SqlClient/add-ons/Directory.Build.props @@ -19,6 +19,7 @@ netcoreapp2.1 + netcoreapp3.1 net46 diff --git a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.csproj index dad15bc623..0902edd7c1 100644 --- a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.csproj @@ -1,7 +1,8 @@  false - netcoreapp2.1;netcoreapp3.1;netstandard2.0 + netcoreapp2.1;netcoreapp3.1;netstandard2.0;netstandard2.1 + netstandard2.1 $(ObjFolder)$(Configuration)\$(AssemblyName)\ref\ $(BinFolder)$(Configuration)\$(AssemblyName)\ref\ $(OutputPath)\$(TargetFramework)\Microsoft.Data.SqlClient.xml diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj index 9232078830..8074efc2e8 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj @@ -1,7 +1,8 @@  Microsoft.Data.SqlClient - netcoreapp2.1;netcoreapp3.1;netstandard2.0 + netcoreapp2.1;netcoreapp3.1;netstandard2.0;netstandard2.1 + netstandard2.1 Strings.PlatformNotSupported_DataSqlClient $(OS) true @@ -226,11 +227,27 @@ - - - + + + + + + + + + + + + + + + + + + + @@ -238,26 +255,12 @@ - - - - - - - - - - - - - - diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedAttestationException.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedAttestationException.cs similarity index 100% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedAttestationException.NetCoreApp.cs rename to src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedAttestationException.cs diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedEnclaveProviderUtils.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedEnclaveProviderUtils.NetCoreApp.cs deleted file mode 100644 index 066d33be25..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedEnclaveProviderUtils.NetCoreApp.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Linq; - -namespace Microsoft.Data.SqlClient -{ - internal class EnclavePublicKey - { - public byte[] PublicKey { get; set; } - - public EnclavePublicKey(byte[] payload) - { - PublicKey = payload; - } - } - - internal class EnclaveDiffieHellmanInfo - { - public int Size { get; private set; } - - public byte[] PublicKey { get; private set; } - - public byte[] PublicKeySignature { get; private set; } - - public EnclaveDiffieHellmanInfo(byte[] payload) - { - Size = payload.Length; - - int offset = 0; - int publicKeySize = BitConverter.ToInt32(payload, offset); - offset += sizeof(int); - - int publicKeySignatureSize = BitConverter.ToInt32(payload, offset); - offset += sizeof(int); - - PublicKey = payload.Skip(offset).Take(publicKeySize).ToArray(); - offset += publicKeySize; - - PublicKeySignature = payload.Skip(offset).Take(publicKeySignatureSize).ToArray(); - offset += publicKeySignatureSize; - } - } - - internal enum EnclaveType - { - None = 0, - - Vbs = 1, - - Sgx = 2 - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedEnclaveProviderUtils.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedEnclaveProviderUtils.cs new file mode 100644 index 0000000000..23abf6b247 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AlwaysEncryptedEnclaveProviderUtils.cs @@ -0,0 +1,153 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics; +using System.Linq; +using System.Security.Cryptography; + +namespace Microsoft.Data.SqlClient +{ + internal class EnclavePublicKey + { + public byte[] PublicKey { get; set; } + + public EnclavePublicKey(byte[] payload) + { + PublicKey = payload; + } + } + + internal class EnclaveDiffieHellmanInfo + { + public int Size { get; private set; } + + public byte[] PublicKey { get; private set; } + + public byte[] PublicKeySignature { get; private set; } + + public EnclaveDiffieHellmanInfo(byte[] payload) + { + Size = payload.Length; + + int offset = 0; + int publicKeySize = BitConverter.ToInt32(payload, offset); + offset += sizeof(int); + + int publicKeySignatureSize = BitConverter.ToInt32(payload, offset); + offset += sizeof(int); + + PublicKey = payload.Skip(offset).Take(publicKeySize).ToArray(); + offset += publicKeySize; + + PublicKeySignature = payload.Skip(offset).Take(publicKeySignatureSize).ToArray(); + offset += publicKeySignatureSize; + } + } + + internal enum EnclaveType + { + None = 0, + + Vbs = 1, + + Sgx = 2 + } + + // Contains methods to convert cryptography keys between different formats. + internal sealed class KeyConverter + { + // The RSA public key blob is structured as follows: + // BCRYPT_RSAKEY_BLOB header + // byte[ExponentSize] publicExponent + // byte[ModulusSize] modulus + private readonly struct RSAPublicKeyBlob + { + // Size of an RSA public key blob + internal static readonly int Size = 539; + // Size of the BCRYPT_RSAKEY_BLOB header + internal static readonly int HeaderSize = 27; + // Size of the exponent (final 3 bytes of the header) + internal static readonly int ExponentSize = 3; + // Size of the modulus (remaining bytes after the header) + internal static readonly int ModulusSize = Size - HeaderSize; + internal static readonly int ExponentOffset = HeaderSize - ExponentSize; + internal static readonly int ModulusOffset = HeaderSize; + } + + // Extracts the public key's modulus and exponent from an RSA public key blob + // and returns an RSAParameters object + internal static RSAParameters RSAPublicKeyBlobToParams(byte[] keyBlob) + { + Debug.Assert(keyBlob.Length == RSAPublicKeyBlob.Size, + $"RSA public key blob was not the expected length. Actual: {keyBlob.Length}. Expected: {RSAPublicKeyBlob.Size}"); + return new RSAParameters() + { + Exponent = keyBlob.Skip(RSAPublicKeyBlob.ExponentOffset).Take(RSAPublicKeyBlob.ExponentSize).ToArray(), + Modulus = keyBlob.Skip(RSAPublicKeyBlob.ModulusOffset).Take(RSAPublicKeyBlob.ModulusSize).ToArray() + }; + } + + // The ECC public key blob is structured as follows: + // BCRYPT_ECCKEY_BLOB header + // byte[KeySize] X + // byte[KeySize] Y + private readonly struct ECCPublicKeyBlob + { + // Size of an ECC public key blob + internal static readonly int Size = 104; + // Size of the BCRYPT_ECCKEY_BLOB header + internal static readonly int HeaderSize = 8; + // Size of each coordinate + internal static readonly int KeySize = (Size - HeaderSize) / 2; + } + + // Magic numbers identifying blob types + // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-wcce/cba27df5-4880-4f95-a879-783f8657e53b + private readonly struct KeyBlobMagicNumber + { + internal static readonly byte[] ECDHPublicP384 = new byte[] { 0x45, 0x43, 0x4b, 0x33 }; + } + + // Extracts the public key's X and Y coordinates from an ECC public key blob + // and returns an ECParameters object + internal static ECParameters ECCPublicKeyBlobToParams(byte[] keyBlob) + { + Debug.Assert(keyBlob.Length == ECCPublicKeyBlob.Size, + $"ECC public key blob was not the expected length. Actual: {keyBlob.Length}. Expected: {ECCPublicKeyBlob.Size}"); + return new ECParameters + { + Curve = ECCurve.NamedCurves.nistP384, + Q = new ECPoint + { + X = keyBlob.Skip(ECCPublicKeyBlob.HeaderSize).Take(ECCPublicKeyBlob.KeySize).ToArray(), + Y = keyBlob.Skip(ECCPublicKeyBlob.HeaderSize + ECCPublicKeyBlob.KeySize).Take(ECCPublicKeyBlob.KeySize).ToArray() + }, + }; + } + + // Serializes an ECDiffieHellmanPublicKey to an ECC public key blob + // "ECDiffieHellmanPublicKey.ToByteArray() doesn't have a (standards-)defined export + // format. The version used by ECDiffieHellmanPublicKeyCng is Windows-specific" + // from https://github.com/dotnet/runtime/issues/27276 + // => ECDiffieHellmanPublicKey.ToByteArray() is not supported in Unix + internal static byte[] ECDHPublicKeyToECCKeyBlob(ECDiffieHellmanPublicKey publicKey) + { + byte[] keyBlob = new byte[ECCPublicKeyBlob.Size]; + + // Set magic number + Array.Copy(KeyBlobMagicNumber.ECDHPublicP384, 0, keyBlob, 0, 4); + // Set key size + keyBlob[4] = (byte)ECCPublicKeyBlob.KeySize; + + ECPoint ecPoint = publicKey.ExportParameters().Q; + Debug.Assert(ecPoint.X.Length == ECCPublicKeyBlob.KeySize && ecPoint.Y.Length == ECCPublicKeyBlob.KeySize, + $"ECDH public key was not the expected length. Actual (X): {ecPoint.X.Length}. Actual (Y): {ecPoint.Y.Length} Expected: {ECCPublicKeyBlob.Size}"); + // Copy x and y coordinates to key blob + Array.Copy(ecPoint.X, 0, keyBlob, ECCPublicKeyBlob.HeaderSize, ECCPublicKeyBlob.KeySize); + Array.Copy(ecPoint.Y, 0, keyBlob, ECCPublicKeyBlob.HeaderSize + ECCPublicKeyBlob.KeySize, ECCPublicKeyBlob.KeySize); + return keyBlob; + } + } +} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.cs similarity index 96% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.NetCoreApp.cs rename to src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.cs index a2a8270803..a4bff1a65d 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/AzureAttestationBasedEnclaveProvider.cs @@ -73,15 +73,15 @@ internal override void GetEnclaveSession(EnclaveSessionParameters enclaveSession // Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. internal override SqlEnclaveAttestationParameters GetAttestationParameters(string attestationUrl, byte[] customData, int customDataLength) { - ECDiffieHellmanCng clientDHKey = new ECDiffieHellmanCng(DiffieHellmanKeySize); - clientDHKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; - clientDHKey.HashAlgorithm = CngAlgorithm.Sha256; + // The key derivation function and hash algorithm name are specified when key derivation is performed + ECDiffieHellman clientDHKey = ECDiffieHellman.Create(); + clientDHKey.KeySize = DiffieHellmanKeySize; byte[] attestationParam = PrepareAttestationParameters(attestationUrl, customData, customDataLength); return new SqlEnclaveAttestationParameters(AzureBasedAttestationProtocolId, attestationParam, clientDHKey); } // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache. - internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) + internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellman clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) { sqlEnclaveSession = null; counter = 0; @@ -514,7 +514,7 @@ private void ValidateClaim(Dictionary claims, string claimName, } // Derives the shared secret between the client and enclave. - private byte[] GetSharedSecret(EnclavePublicKey enclavePublicKey, byte[] nonce, EnclaveType enclaveType, EnclaveDiffieHellmanInfo enclaveDHInfo, ECDiffieHellmanCng clientDHKey) + private byte[] GetSharedSecret(EnclavePublicKey enclavePublicKey, byte[] nonce, EnclaveType enclaveType, EnclaveDiffieHellmanInfo enclaveDHInfo, ECDiffieHellman clientDHKey) { byte[] enclaveRsaPublicKey = enclavePublicKey.PublicKey; @@ -529,17 +529,18 @@ private byte[] GetSharedSecret(EnclavePublicKey enclavePublicKey, byte[] nonce, } // Perform signature verification. The enclave's DiffieHellman public key was signed by the enclave's RSA public key. - CngKey cngkey = CngKey.Import(enclaveRsaPublicKey, CngKeyBlobFormat.GenericPublicBlob); - using (RSACng rsacng = new RSACng(cngkey)) + RSAParameters rsaParams = KeyConverter.RSAPublicKeyBlobToParams(enclaveRsaPublicKey); + using (RSA rsa = RSA.Create(rsaParams)) { - if (!rsacng.VerifyData(enclaveDHInfo.PublicKey, enclaveDHInfo.PublicKeySignature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) + if (!rsa.VerifyData(enclaveDHInfo.PublicKey, enclaveDHInfo.PublicKeySignature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) { throw new ArgumentException(Strings.GetSharedSecretFailed); } } - CngKey key = CngKey.Import(enclaveDHInfo.PublicKey, CngKeyBlobFormat.GenericPublicBlob); - return clientDHKey.DeriveKeyMaterial(key); + ECParameters ecParams = KeyConverter.ECCPublicKeyBlobToParams(enclaveDHInfo.PublicKey); + ECDiffieHellman enclaveDHKey = ECDiffieHellman.Create(ecParams); + return clientDHKey.DeriveKeyFromHash(enclaveDHKey.PublicKey, HashAlgorithmName.SHA256); } #endregion } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveDelegate.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveDelegate.NetCoreApp.cs index db9f7a68f2..e1cff2d0e0 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveDelegate.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveDelegate.NetCoreApp.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; -using System.Security.Cryptography; namespace Microsoft.Data.SqlClient { @@ -44,7 +43,7 @@ internal byte[] GetSerializedAttestationParameters(SqlEnclaveAttestationParamete } // clientDHPublicKey - byte[] clientDHPublicKey = sqlEnclaveAttestationParameters.ClientDiffieHellmanKey.Key.Export(CngKeyBlobFormat.EccPublicBlob); + byte[] clientDHPublicKey = KeyConverter.ECDHPublicKeyToECCKeyBlob(sqlEnclaveAttestationParameters.ClientDiffieHellmanKey.PublicKey); // clientDHPublicKey length clientDHPublicKeyLengthBytes = GetUintBytes(enclaveType, clientDHPublicKey.Length, "clientDHPublicKeyLength"); @@ -54,7 +53,8 @@ internal byte[] GetSerializedAttestationParameters(SqlEnclaveAttestationParamete throw SQL.NullArgumentInternal("clientDHPublicKeyLengthBytes", ClassName, GetSerializedAttestationParametersName); } - return CombineByteArrays(new[] { attestationProtocolBytes, attestationProtocolInputLengthBytes, attestationProtocolInputBytes, clientDHPublicKeyLengthBytes, clientDHPublicKey }); + return CombineByteArrays(new[] { attestationProtocolBytes, attestationProtocolInputLengthBytes, + attestationProtocolInputBytes, clientDHPublicKeyLengthBytes, clientDHPublicKey }); } /// @@ -88,7 +88,7 @@ internal void CreateEnclaveSession(SqlConnectionAttestationProtocol attestationP sqlColumnEncryptionEnclaveProvider.CreateEnclaveSession(attestationInfo, attestationParameters.ClientDiffieHellmanKey, enclaveSessionParameters, customData, customDataLength, out sqlEnclaveSession, out counter); - if (sqlEnclaveSession == null) + if (sqlEnclaveSession == null) { throw SQL.NullEnclaveSessionReturnedFromProvider(enclaveType, enclaveSessionParameters.AttestationUrl); } @@ -137,7 +137,7 @@ internal void InvalidateEnclaveSession(SqlConnectionAttestationProtocol attestat sqlColumnEncryptionEnclaveProvider.InvalidateEnclaveSession(enclaveSessionParameters, enclaveSession); } - + internal SqlEnclaveAttestationParameters GetAttestationParameters(SqlConnectionAttestationProtocol attestationProtocol, string enclaveType, string attestationUrl, byte[] customData, int customDataLength) { SqlColumnEncryptionEnclaveProvider sqlColumnEncryptionEnclaveProvider = GetEnclaveProvider(attestationProtocol, enclaveType); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveProviderBase.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveProviderBase.cs similarity index 100% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveProviderBase.NetCoreApp.cs rename to src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveProviderBase.cs diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveSessionCache.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveSessionCache.cs similarity index 100% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveSessionCache.NetCoreApp.cs rename to src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/EnclaveSessionCache.cs diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs index 064742be3c..bed6ada9e3 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SimulatorEnclaveProvider.NetCoreApp.cs @@ -30,15 +30,15 @@ internal override void GetEnclaveSession(EnclaveSessionParameters enclaveSession // Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. internal override SqlEnclaveAttestationParameters GetAttestationParameters(string attestationUrl, byte[] customData, int customDataLength) { - ECDiffieHellmanCng clientDHKey = new ECDiffieHellmanCng(384); - clientDHKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; - clientDHKey.HashAlgorithm = CngAlgorithm.Sha256; + // The key derivation function and hash algorithm name are specified when key derivation is performed + ECDiffieHellman clientDHKey = ECDiffieHellman.Create(); + clientDHKey.KeySize = 384; return new SqlEnclaveAttestationParameters(2, new byte[] { }, clientDHKey); } // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache. - internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) + internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellman clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) { ////for simulator: enclave does not send public key, and sends an empty attestation info //// The only non-trivial content it sends is the session setup info (DH pubkey of enclave) @@ -84,8 +84,9 @@ internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHell Buffer.BlockCopy(attestationInfo, attestationInfoOffset, trustedModuleDHPublicKeySignature, 0, checked((int)sizeOfTrustedModuleDHPublicKeySignatureBuffer)); - CngKey k = CngKey.Import(trustedModuleDHPublicKey, CngKeyBlobFormat.EccPublicBlob); - byte[] sharedSecret = clientDHKey.DeriveKeyMaterial(k); + ECParameters ecParams = KeyConverter.ECCPublicKeyBlobToParams(trustedModuleDHPublicKey); + ECDiffieHellman enclaveDHKey = ECDiffieHellman.Create(ecParams); + byte[] sharedSecret = clientDHKey.DeriveKeyFromHash(enclaveDHKey.PublicKey, HashAlgorithmName.SHA256); long sessionId = BitConverter.ToInt64(enclaveSessionHandle, 0); sqlEnclaveSession = AddEnclaveSessionToCache(enclaveSessionParameters, sharedSecret, sessionId, out counter); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCertificateStoreProvider.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCertificateStoreProvider.Windows.cs index e05025d2f8..c6f2786583 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCertificateStoreProvider.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionCertificateStoreProvider.Windows.cs @@ -482,10 +482,11 @@ private byte[] RSAEncrypt(byte[] plainText, X509Certificate2 certificate) } /// - /// Encrypt the text using specified certificate. + /// Decrypt the data using specified certificate. /// /// Text to decrypt. /// Certificate object. + /// Returns a decrypted blob or throws an exception if there are any errors. private byte[] RSADecrypt(byte[] cipherText, X509Certificate2 certificate) { Debug.Assert((cipherText != null) && (cipherText.Length != 0)); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.NetCoreApp.cs index c608036c6e..cca04fc323 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlColumnEncryptionEnclaveProvider.NetCoreApp.cs @@ -19,7 +19,7 @@ internal abstract partial class SqlColumnEncryptionEnclaveProvider /// The length of the extra data needed for attestating the enclave. /// The requested enclave session or null if the provider does not implement session caching. /// A counter that the enclave provider is expected to increment each time SqlClient retrieves the session from the cache. The purpose of this field is to prevent replay attacks. - internal abstract void CreateEnclaveSession(byte[] enclaveAttestationInfo, ECDiffieHellmanCng clientDiffieHellmanKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, + internal abstract void CreateEnclaveSession(byte[] enclaveAttestationInfo, ECDiffieHellman clientDiffieHellmanKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlEnclaveAttestationParameters.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlEnclaveAttestationParameters.NetCoreApp.cs index 1f59daf511..739187a7e9 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlEnclaveAttestationParameters.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlEnclaveAttestationParameters.NetCoreApp.cs @@ -14,10 +14,10 @@ internal partial class SqlEnclaveAttestationParameters private static readonly string _className = "EnclaveAttestationParameters"; /// - internal ECDiffieHellmanCng ClientDiffieHellmanKey { get; } + internal ECDiffieHellman ClientDiffieHellmanKey { get; } /// - internal SqlEnclaveAttestationParameters(int protocol, byte[] input, ECDiffieHellmanCng clientDiffieHellmanKey) + internal SqlEnclaveAttestationParameters(int protocol, byte[] input, ECDiffieHellman clientDiffieHellmanKey) { _input = input ?? throw SQL.NullArgumentInConstructorInternal(_inputName, _className); Protocol = protocol; diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProvider.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProvider.cs similarity index 100% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProvider.NetCoreApp.cs rename to src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProvider.cs diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.cs similarity index 91% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.NetCoreApp.cs rename to src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.cs index 66f3f71a65..663b4a4e19 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/VirtualSecureModeEnclaveProviderBase.cs @@ -94,14 +94,15 @@ internal override void GetEnclaveSession(EnclaveSessionParameters enclaveSession // Gets the information that SqlClient subsequently uses to initiate the process of attesting the enclave and to establish a secure session with the enclave. internal override SqlEnclaveAttestationParameters GetAttestationParameters(string attestationUrl, byte[] customData, int customDataLength) { - ECDiffieHellmanCng clientDHKey = new ECDiffieHellmanCng(DiffieHellmanKeySize); - clientDHKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; - clientDHKey.HashAlgorithm = CngAlgorithm.Sha256; + // The key derivation function and hash algorithm name are specified when key derivation is performed + ECDiffieHellman clientDHKey = ECDiffieHellman.Create(); + clientDHKey.KeySize = DiffieHellmanKeySize; + return new SqlEnclaveAttestationParameters(VsmHGSProtocolId, new byte[] { }, clientDHKey); } // When overridden in a derived class, performs enclave attestation, generates a symmetric key for the session, creates a an enclave session and stores the session information in the cache. - internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellmanCng clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) + internal override void CreateEnclaveSession(byte[] attestationInfo, ECDiffieHellman clientDHKey, EnclaveSessionParameters enclaveSessionParameters, byte[] customData, int customDataLength, out SqlEnclaveSession sqlEnclaveSession, out long counter) { sqlEnclaveSession = null; counter = 0; @@ -295,14 +296,12 @@ private void VerifyEnclaveReportSignature(EnclaveReportPackage enclaveReportPack } // IDK_S is contained in healthReport cert public key - RSA rsacsp = healthReportCert.GetRSAPublicKey(); - RSAParameters rsaparams = rsacsp.ExportParameters(includePrivateParameters: false); - RSACng rsacng = new RSACng(); - rsacng.ImportParameters(rsaparams); - - if (!rsacng.VerifyData(enclaveReportPackage.ReportAsBytes, enclaveReportPackage.SignatureBlob, HashAlgorithmName.SHA256, RSASignaturePadding.Pss)) + using (RSA rsa = healthReportCert.GetRSAPublicKey()) { - throw new ArgumentException(Strings.VerifyEnclaveReportFailed); + if (!rsa.VerifyData(enclaveReportPackage.ReportAsBytes, enclaveReportPackage.SignatureBlob, HashAlgorithmName.SHA256, RSASignaturePadding.Pss)) + { + throw new ArgumentException(Strings.VerifyEnclaveReportFailed); + } } } @@ -349,20 +348,22 @@ private void VerifyEnclavePolicyProperty(string property, uint actual, uint expe } // Derives the shared secret between the client and enclave. - private byte[] GetSharedSecret(EnclavePublicKey enclavePublicKey, EnclaveDiffieHellmanInfo enclaveDHInfo, ECDiffieHellmanCng clientDHKey) + private byte[] GetSharedSecret(EnclavePublicKey enclavePublicKey, EnclaveDiffieHellmanInfo enclaveDHInfo, ECDiffieHellman clientDHKey) { // Perform signature verification. The enclave's DiffieHellman public key was signed by the enclave's RSA public key. - CngKey cngkey = CngKey.Import(enclavePublicKey.PublicKey, CngKeyBlobFormat.GenericPublicBlob); - RSACng rsacng = new RSACng(cngkey); - if (!rsacng.VerifyData(enclaveDHInfo.PublicKey, enclaveDHInfo.PublicKeySignature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) + RSAParameters rsaParams = KeyConverter.RSAPublicKeyBlobToParams(enclavePublicKey.PublicKey); + using (RSA rsa = RSA.Create(rsaParams)) { - throw new ArgumentException(Strings.GetSharedSecretFailed); + if (!rsa.VerifyData(enclaveDHInfo.PublicKey, enclaveDHInfo.PublicKeySignature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) + { + throw new ArgumentException(Strings.GetSharedSecretFailed); + } } - CngKey key = CngKey.Import(enclaveDHInfo.PublicKey, CngKeyBlobFormat.GenericPublicBlob); - return clientDHKey.DeriveKeyMaterial(key); + ECParameters ecParams = KeyConverter.ECCPublicKeyBlobToParams(enclaveDHInfo.PublicKey); + ECDiffieHellman enclaveDHKey = ECDiffieHellman.Create(ecParams); + return clientDHKey.DeriveKeyFromHash(enclaveDHKey.PublicKey, HashAlgorithmName.SHA256); } - #endregion } } diff --git a/src/Microsoft.Data.SqlClient/tests/Directory.Build.props b/src/Microsoft.Data.SqlClient/tests/Directory.Build.props index 5d26340cf8..3225e9461a 100644 --- a/src/Microsoft.Data.SqlClient/tests/Directory.Build.props +++ b/src/Microsoft.Data.SqlClient/tests/Directory.Build.props @@ -7,6 +7,7 @@ net46 + netcoreapp3.1 netcoreapp2.1 Project @@ -15,20 +16,20 @@ - $(TargetNetCoreVersion) + $(TargetNetCoreVersion) - $(TargetNetCoreVersion) - $(TargetNetFxVersion) + $(TargetNetCoreVersion) + $(TargetNetFxVersion) - $(Configuration.Split('-')[0]) + $(Configuration.Split('-')[0]) diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj index ed7e701212..cbaa4a9520 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj @@ -10,20 +10,20 @@ $(BinFolder)$(Configuration).$(Platform).$(AssemblyName) - - - + + + + + - - diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionStringBuilderTest.cs b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionStringBuilderTest.cs index f0b08da092..e1eae7b608 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionStringBuilderTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionStringBuilderTest.cs @@ -52,8 +52,10 @@ public class SqlConnectionStringBuilderTest [InlineData("PersistSecurityInfo = true")] [InlineData("Pooling = no")] [InlineData("Pooling = false")] +#if netcoreapp // PoolBlockingPeriod is not supported in .NET Standard [InlineData("PoolBlockingPeriod = Auto")] [InlineData("PoolBlockingperiod = NeverBlock")] +#endif [InlineData("Replication = true")] [InlineData("Transaction Binding = Explicit Unbind")] [InlineData("Trust Server Certificate = true")] diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/ApiShould.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/ApiShould.cs index bb74323fe0..5096d15af4 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/ApiShould.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/ApiShould.cs @@ -18,18 +18,16 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted { /// /// Always Encrypted public API Manual tests. - /// TODO: These tests are marked as Windows only for now but should be run for all platforms once the Master Key is accessible to this app from Azure Key Vault. /// - [PlatformSpecific(TestPlatforms.Windows)] - public class ApiShould : IClassFixture, IDisposable + public class ApiShould : IClassFixture, IDisposable { - private SQLSetupStrategyCertStoreProvider fixture; + private SQLSetupStrategy fixture; private readonly string tableName; - public ApiShould(SQLSetupStrategyCertStoreProvider fixture) + public ApiShould(PlatformSpecificTestContext context) { - this.fixture = fixture; + fixture = context.Fixture; tableName = fixture.ApiTestTable.Name; } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/BulkCopyAE.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/BulkCopyAE.cs index dccd65736a..dd2b2b2561 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/BulkCopyAE.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/BulkCopyAE.cs @@ -11,18 +11,16 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted { /// /// Always Encrypted public API Manual tests. - /// TODO: These tests are marked as Windows only for now but should be run for all platforms once the Master Key is accessible to this app from Azure Key Vault. /// - [PlatformSpecific(TestPlatforms.Windows)] - public class BulkCopyAE : IClassFixture, IDisposable + public class BulkCopyAE : IClassFixture, IDisposable { - private SQLSetupStrategyCertStoreProvider fixture; + private SQLSetupStrategy fixture; private readonly string tableName; - public BulkCopyAE(SQLSetupStrategyCertStoreProvider fixture) + public BulkCopyAE(PlatformSpecificTestContext context) { - this.fixture = fixture; + fixture = context.Fixture; tableName = fixture.BulkCopyAETestTable.Name; } @@ -34,7 +32,7 @@ public void TestBulkCopyString(string connectionString) dataTable.Columns.Add("c1", typeof(string)); var dataRow = dataTable.NewRow(); - String result = "stringValue"; + string result = "stringValue"; dataRow["c1"] = result; dataTable.Rows.Add(dataRow); dataTable.AcceptChanges(); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/BulkCopyAEErrorMessage.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/BulkCopyAEErrorMessage.cs index 111c64fd43..cf2da1c4b6 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/BulkCopyAEErrorMessage.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/BulkCopyAEErrorMessage.cs @@ -10,20 +10,18 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted { /// /// Always Encrypted public API Manual tests. - /// TODO: These tests are marked as Windows only for now but should be run for all platforms once the Master Key is accessible to this app from Azure Key Vault. /// - [PlatformSpecific(TestPlatforms.Windows)] - public class BulkCopyAEErrorMessage : IClassFixture + public class BulkCopyAEErrorMessage : IClassFixture { - private SQLSetupStrategyCertStoreProvider _fixture; - + private SQLSetupStrategy _fixture; + private readonly string _tableName; private readonly string _columnName; - public BulkCopyAEErrorMessage(SQLSetupStrategyCertStoreProvider fixture) + public BulkCopyAEErrorMessage(PlatformSpecificTestContext context) { - _fixture = fixture; - _tableName = fixture.BulkCopyAEErrorMessageTestTable.Name; + _fixture = context.Fixture; + _tableName = _fixture.BulkCopyAEErrorMessageTestTable.Name; _columnName = "c1"; } @@ -35,8 +33,8 @@ public void TextToIntErrorMessageTest(string connectionString) DataTable dataTable = CreateDataTable(value); Assert.True(StringToIntTest(connectionString, _tableName, dataTable, value, dataTable.Rows.Count), "Did not get any exceptions for DataTable when converting data from 'string' to 'int' datatype!"); - Assert.True(StringToIntTest(connectionString, _tableName, dataTable.Select(), value, dataTable.Rows.Count),"Did not get any exceptions for DataRow[] when converting data from 'string' to 'int' datatype!"); - Assert.True(StringToIntTest(connectionString, _tableName, dataTable.CreateDataReader(), value, -1),"Did not get any exceptions for DataReader when converting data from 'string' to 'int' datatype!"); + Assert.True(StringToIntTest(connectionString, _tableName, dataTable.Select(), value, dataTable.Rows.Count), "Did not get any exceptions for DataRow[] when converting data from 'string' to 'int' datatype!"); + Assert.True(StringToIntTest(connectionString, _tableName, dataTable.CreateDataReader(), value, -1), "Did not get any exceptions for DataReader when converting data from 'string' to 'int' datatype!"); } private DataTable CreateDataTable(string value) @@ -44,7 +42,7 @@ private DataTable CreateDataTable(string value) var dataTable = new DataTable(); dataTable.Columns.Add(_columnName, typeof(string)); - var dataRow = dataTable.NewRow(); + var dataRow = dataTable.NewRow(); dataRow[_columnName] = value; dataTable.Rows.Add(dataRow); dataTable.AcceptChanges(); @@ -90,7 +88,7 @@ private bool StringToIntTest(string connectionString, string targetTable, object catch (Exception ex) { string pattern; - object[] args = + object[] args = new object[] { string.Empty, value.GetType().Name, targetType, 0, _columnName, rowNo }; if (rowNo == -1) { diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/EnclaveAzureDatabaseTests.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/EnclaveAzureDatabaseTests.cs index d90529976d..289ad6bc63 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/EnclaveAzureDatabaseTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/EnclaveAzureDatabaseTests.cs @@ -68,7 +68,6 @@ public EnclaveAzureDatabaseTests() } } - [PlatformSpecific(TestPlatforms.Windows)] [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.IsEnclaveAzureDatabaseSetup))] public void ConnectToAzureDatabaseWithEnclave() { diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/End2EndSmokeTests.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/End2EndSmokeTests.cs index a8cbde4f1b..88fc0f6f66 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/End2EndSmokeTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/End2EndSmokeTests.cs @@ -11,16 +11,15 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted { - [PlatformSpecific(TestPlatforms.Windows)] - public class End2EndSmokeTests : IClassFixture, IDisposable + public class End2EndSmokeTests : IClassFixture, IDisposable { - private SQLSetupStrategyCertStoreProvider fixture; + private SQLSetupStrategy fixture; private readonly string tableName; - public End2EndSmokeTests(SQLSetupStrategyCertStoreProvider fixture) + public End2EndSmokeTests(PlatformSpecificTestContext context) { - this.fixture = fixture; + fixture = context.Fixture; tableName = fixture.End2EndSmokeTable.Name; } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/ExceptionTestAKVStore.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/ExceptionTestAKVStore.cs index 50eccd0b9e..a9503d69de 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/ExceptionTestAKVStore.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/ExceptionTestAKVStore.cs @@ -163,7 +163,7 @@ public void InvalidCertificatePath() Assert.Matches(errorMessage, ex2.Message); } - // [InlineData(true)] -> Enable with AE v2 + [InlineData(true)] [InlineData(false)] [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.IsAKVSetupAvailable))] public void AkvStoreProviderVerifyFunctionWithInvalidSignature(bool fEnclaveEnabled) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/SqlBulkCopyTruncation.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/SqlBulkCopyTruncation.cs index cd2c2dadc9..32dd86cd94 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/SqlBulkCopyTruncation.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/SqlBulkCopyTruncation.cs @@ -11,17 +11,16 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted { - [PlatformSpecific(TestPlatforms.Windows)] - public class SqlBulkCopyTruncation : IClassFixture + public class SqlBulkCopyTruncation : IClassFixture { - private SQLSetupStrategyCertStoreProvider _fixture; + private SQLSetupStrategy _fixture; private readonly Dictionary tableNames = new Dictionary(); - public SqlBulkCopyTruncation(SQLSetupStrategyCertStoreProvider fixture) + public SqlBulkCopyTruncation(PlatformSpecificTestContext context) { - _fixture = fixture; - tableNames = fixture.sqlBulkTruncationTableNames; + _fixture = context.Fixture; + tableNames = _fixture.sqlBulkTruncationTableNames; } [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))] diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/SqlNullValues.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/SqlNullValues.cs index 91d29836d0..caa174b3ce 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/SqlNullValues.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/SqlNullValues.cs @@ -11,17 +11,16 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted { - [PlatformSpecific(TestPlatforms.Windows)] - public class SqlNullValuesTests : IClassFixture, IDisposable + public class SqlNullValuesTests : IClassFixture, IDisposable { - private SQLSetupStrategyCertStoreProvider fixture; + private SQLSetupStrategy fixture; private readonly string tableName; private string UdfName = DatabaseHelper.GenerateUniqueName("SqlNullValuesRetVal"); private string UdfNameNotNull = DatabaseHelper.GenerateUniqueName("SqlNullValuesRetValNotNull"); - public SqlNullValuesTests(SQLSetupStrategyCertStoreProvider fixture) + public SqlNullValuesTests(PlatformSpecificTestContext context) { - this.fixture = fixture; + fixture = context.Fixture; tableName = fixture.SqlNullValuesTable.Name; // Disable the cache to avoid false failures. SqlConnection.ColumnEncryptionQueryMetadataCacheEnabled = false; @@ -33,7 +32,7 @@ public SqlNullValuesTests(SQLSetupStrategyCertStoreProvider fixture) { sqlConnection.Open(); - using (SqlCommand cmd = new SqlCommand(String.Format("INSERT INTO [{0}] (c1) VALUES (@c1)", tableName), sqlConnection, null, SqlCommandColumnEncryptionSetting.Enabled)) + using (SqlCommand cmd = new SqlCommand(string.Format("INSERT INTO [{0}] (c1) VALUES (@c1)", tableName), sqlConnection, null, SqlCommandColumnEncryptionSetting.Enabled)) { SqlParameter param = cmd.Parameters.Add("@c1", SqlDbType.Int); param.Value = DBNull.Value; @@ -79,7 +78,7 @@ public void NullValueTests(string connString, ConnStringColumnEncryptionSetting SqlParameter param; // Create a command similarly - using (SqlCommand cmd = new SqlCommand(String.Format("SELECT c1 FROM [{0}] ORDER BY c2 ASC", tableName), + using (SqlCommand cmd = new SqlCommand(string.Format("SELECT c1 FROM [{0}] ORDER BY c2 ASC", tableName), sqlConn, null, commandSetting)) { using (SqlDataReader reader = cmd.ExecuteReader()) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/SQLSetupStrategy.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/SQLSetupStrategy.cs index dc165a2747..7183655c41 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/SQLSetupStrategy.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/SQLSetupStrategy.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; +using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted.Setup; using Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted.TestFixtures.Setup; @@ -253,4 +254,30 @@ public void Dispose() } } } + + // Use this class as the fixture for AE tests to ensure only one platform-specific fixture + // is created for each test class + public class PlatformSpecificTestContext : IDisposable + { + private SQLSetupStrategy certStoreFixture = null; + private SQLSetupStrategy akvFixture = null; + public SQLSetupStrategy Fixture => certStoreFixture ?? akvFixture; + + public PlatformSpecificTestContext() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + certStoreFixture = new SQLSetupStrategyCertStoreProvider(); + } + else + { + akvFixture = new SQLSetupStrategyAzureKeyVault(); + } + } + + public void Dispose() + { + Fixture.Dispose(); + } + } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/AkvColumnMasterKey.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/AkvColumnMasterKey.cs index a9469d79b6..353f7ac97a 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/AkvColumnMasterKey.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/AkvColumnMasterKey.cs @@ -17,7 +17,7 @@ public AkvColumnMasterKey(string name, string akvUrl, SqlColumnEncryptionKeyStor // For keys which allow enclave computation byte[] cmkSign = akvProvider.SignColumnMasterKeyMetadata(akvUrl, allowEnclaveComputations); - cmkSignStr = string.Concat("0x", BitConverter.ToString(cmkSign).Replace("-", string.Empty)); + CmkSignStr = string.Concat("0x", BitConverter.ToString(cmkSign).Replace("-", string.Empty)); } } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/ColumnMasterKey.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/ColumnMasterKey.cs index 5eb02ffcd9..4e4cf8acf8 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/ColumnMasterKey.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/ColumnMasterKey.cs @@ -2,36 +2,29 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Data; -using System.Data.SqlTypes; -using Xunit; - namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted.Setup { public abstract class ColumnMasterKey : DbObject { - protected ColumnMasterKey(string name) : base(name) { } protected string KeyStoreProviderName { get; set; } - protected string cmkSignStr { get; set; } + protected string CmkSignStr { get; set; } public abstract string KeyPath { get; } public override void Create(SqlConnection sqlConnection) { string sql; - var connStrings = sqlConnection.ConnectionString; - if (DataTestUtility.EnclaveEnabled && !String.IsNullOrEmpty(cmkSignStr)) + if (DataTestUtility.EnclaveEnabled && !string.IsNullOrEmpty(CmkSignStr)) { sql = $@"CREATE COLUMN MASTER KEY [{Name}] WITH ( KEY_STORE_PROVIDER_NAME = N'{KeyStoreProviderName}', KEY_PATH = N'{KeyPath}', - ENCLAVE_COMPUTATIONS (SIGNATURE = {cmkSignStr}) + ENCLAVE_COMPUTATIONS (SIGNATURE = {CmkSignStr}) );"; } else diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/CspColumnMasterKey.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/CspColumnMasterKey.cs index 9e26b1105e..8a27b2b860 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/CspColumnMasterKey.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/TestFixtures/Setup/CspColumnMasterKey.cs @@ -21,7 +21,7 @@ public CspColumnMasterKey(string name, string certificateThumbprint, SqlColumnEn KeyPath = string.Concat(CertificateStoreLocation.ToString(), "/", CertificateStoreName.ToString(), "/", Thumbprint); byte[] cmkSign = certStoreProvider.SignColumnMasterKeyMetadata(KeyPath, allowEnclaveComputations); - cmkSignStr = string.Concat("0x", BitConverter.ToString(cmkSign).Replace("-", string.Empty)); + CmkSignStr = string.Concat("0x", BitConverter.ToString(cmkSign).Replace("-", string.Empty)); } public CspColumnMasterKey(string name, string providerName, string cspKeyPath, SqlColumnEncryptionKeyStoreProvider certStoreProvider, bool allowEnclaveComputations) : base(name) @@ -29,7 +29,7 @@ public CspColumnMasterKey(string name, string providerName, string cspKeyPath, S KeyStoreProviderName = providerName; KeyPath = cspKeyPath; byte[] cmkSign = certStoreProvider.SignColumnMasterKeyMetadata(KeyPath, allowEnclaveComputations); - cmkSignStr = string.Concat("0x", BitConverter.ToString(cmkSign).Replace("-", string.Empty)); + CmkSignStr = string.Concat("0x", BitConverter.ToString(cmkSign).Replace("-", string.Empty)); } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj index afbd056adb..810775db77 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj @@ -17,47 +17,47 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Common\System\Collections\DictionaryExtensions.cs @@ -278,7 +278,7 @@ - + diff --git a/src/Microsoft.Data.SqlClient/tests/NSLibrary/Microsoft.Data.SqlClient.NSLibrary.csproj b/src/Microsoft.Data.SqlClient/tests/NSLibrary/Microsoft.Data.SqlClient.NSLibrary.csproj index 5c1d2ce4c5..d526f2497c 100644 --- a/src/Microsoft.Data.SqlClient/tests/NSLibrary/Microsoft.Data.SqlClient.NSLibrary.csproj +++ b/src/Microsoft.Data.SqlClient/tests/NSLibrary/Microsoft.Data.SqlClient.NSLibrary.csproj @@ -1,7 +1,8 @@ - netstandard2.0 + netstandard2.0;netstandard2.1 + netstandard2.1 AnyCPU;x86;x64 $(ObjFolder)$(Configuration).$(Platform)\$(AssemblyName) $(BinFolder)$(Configuration).$(Platform)\$(AssemblyName) diff --git a/tools/specs/Microsoft.Data.SqlClient.nuspec b/tools/specs/Microsoft.Data.SqlClient.nuspec index 3e09d83333..362ffdd7c8 100644 --- a/tools/specs/Microsoft.Data.SqlClient.nuspec +++ b/tools/specs/Microsoft.Data.SqlClient.nuspec @@ -67,6 +67,17 @@ When using NuGet 3.x this package requires at least version 3.4. + + + + + + + + + + + @@ -93,6 +104,11 @@ When using NuGet 3.x this package requires at least version 3.4. + + + + + @@ -117,6 +133,10 @@ When using NuGet 3.x this package requires at least version 3.4. + + + + @@ -148,6 +168,10 @@ When using NuGet 3.x this package requires at least version 3.4. + + + + @@ -169,5 +193,10 @@ When using NuGet 3.x this package requires at least version 3.4. + + + + + From cff40d07c8a0895ca747d525c38a196149c77f1b Mon Sep 17 00:00:00 2001 From: Johnny Pham <23270162+johnnypham@users.noreply.github.com> Date: Fri, 21 Aug 2020 15:24:30 -0700 Subject: [PATCH 10/24] Enable event tracing in SNI.dll (#650) --- BUILDGUIDE.md | 4 +- .../Interop/SNINativeMethodWrapper.Windows.cs | 20 ++++++- .../src/Microsoft.Data.SqlClient.csproj | 5 ++ .../netfx/src/Microsoft.Data.SqlClient.csproj | 3 + .../Interop/SNINativeManagedWrapperX64.cs | 6 ++ .../Interop/SNINativeManagedWrapperX86.cs | 6 ++ .../Data/Interop/SNINativeMethodWrapper.cs | 34 +++++++++-- .../SqlClient/SqlClientEventSource.Windows.cs | 60 +++++++++++++++++++ .../Data/SqlClient/SqlClientEventSource.cs | 2 +- 9 files changed, 132 insertions(+), 8 deletions(-) create mode 100644 src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.Windows.cs diff --git a/BUILDGUIDE.md b/BUILDGUIDE.md index 71f068be23..6f56080aa0 100644 --- a/BUILDGUIDE.md +++ b/BUILDGUIDE.md @@ -56,8 +56,8 @@ Once the environment is setup properly, execute the desired set of commands belo ``` ```bash -> msbuild /t:BuildAllOSes -# Builds the driver for all Operating Systems. +> msbuild /t:BuildNetCoreAllOS +# Builds the .NET Core driver for all Operating Systems. ``` ## Building Tests 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 2566f441f0..e3b91c6ee5 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Interop/SNINativeMethodWrapper.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Interop/SNINativeMethodWrapper.Windows.cs @@ -304,7 +304,13 @@ private static extern unsafe uint SNISecGenClientContextWrapper( [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] private static extern uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket); - #endregion + + [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] + internal static extern bool RegisterTraceProviderWrapper(int eventKeyword); + + [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] + internal static extern void UnregisterTraceProviderWrapper(); + #endregion internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId) { @@ -461,6 +467,18 @@ private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref Sni_Consu : IntPtr.Zero; native_consumerInfo.ConsumerKey = consumerInfo.key; } + + internal static bool RegisterTraceProvider(int eventKeyword) + { + // Registers the TraceLogging provider, enabling it to generate events. + // Return true if enabled, otherwise false. + return RegisterTraceProviderWrapper(eventKeyword); + } + + internal static void UnregisterTraceProvider() + { + UnregisterTraceProviderWrapper(); + } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj index 8074efc2e8..ca0ae11448 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj @@ -33,6 +33,11 @@ true + + + Microsoft\Data\SqlClient\SqlClientEventSource.Windows.cs + + Microsoft\Data\SqlClient\SqlClientEventSource.cs diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj index 042ba6de5e..6d60225a6d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj @@ -91,6 +91,9 @@ Microsoft\Data\SqlClient\SqlClientEventSource.cs + + Microsoft\Data\SqlClient\SqlClientEventSource.Windows.cs + Microsoft\Data\SqlClient\SqlClientLogger.cs diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeManagedWrapperX64.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeManagedWrapperX64.cs index 0cddc32dc1..3b2549e5de 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeManagedWrapperX64.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeManagedWrapperX64.cs @@ -133,5 +133,11 @@ internal static extern unsafe uint SNISecGenClientContextWrapper( [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr SNIClientCertificateFallbackWrapper(IntPtr pCallbackContext); + + [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] + internal static extern bool RegisterTraceProviderWrapper(int eventKeyword); + + [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] + internal static extern void UnregisterTraceProviderWrapper(); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeManagedWrapperX86.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeManagedWrapperX86.cs index 398ecc4872..fc1e90750c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeManagedWrapperX86.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Interop/SNINativeManagedWrapperX86.cs @@ -133,5 +133,11 @@ internal static extern unsafe uint SNISecGenClientContextWrapper( [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr SNIClientCertificateFallbackWrapper(IntPtr pCallbackContext); + + [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] + internal static extern bool RegisterTraceProviderWrapper(int eventKeyword); + + [DllImport(SNI, CallingConvention = CallingConvention.Cdecl)] + internal static extern void UnregisterTraceProviderWrapper(); } } 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 66efa587b6..a79e0e71e5 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 @@ -51,7 +51,7 @@ internal static class SNINativeMethodWrapper internal const int LocalDBInvalidSqlUserInstanceDllPath = 55; internal const int LocalDBFailedToLoadDll = 56; internal const int LocalDBBadRuntime = 57; - internal const int SniIP6AddrStringBufferLength = 48; // from SNI layer + internal const int SniIP6AddrStringBufferLength = 48; // from SNI layer internal static int SniMaxComposedSpnLength { @@ -725,12 +725,12 @@ internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId) { return SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_CONNID, out connId); } - + internal static uint SniGetProviderNumber(SNIHandle pConn, ref ProviderEnum provNum) { return SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_PROVIDERNUM, out provNum); } - + internal static uint SniGetConnectionPort(SNIHandle pConn, ref ushort portNum) { return SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_PEERPORT, out portNum); @@ -812,7 +812,7 @@ internal static unsafe uint SNIOpenSyncEx(ConsumerInfo consumerInfo, string cons clientConsumerInfo.DNSCacheInfo.wszCachedTcpIPv4 = cachedDNSInfo?.AddrIPv4; clientConsumerInfo.DNSCacheInfo.wszCachedTcpIPv6 = cachedDNSInfo?.AddrIPv6; clientConsumerInfo.DNSCacheInfo.wszCachedTcpPort = cachedDNSInfo?.Port; - + if (spnBuffer != null) { fixed (byte* pin_spnBuffer = &spnBuffer[0]) @@ -1075,6 +1075,32 @@ private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref Sni_Consu : IntPtr.Zero; native_consumerInfo.ConsumerKey = consumerInfo.key; } + + internal static bool RegisterTraceProvider(int eventKeyword) + { + // Registers the TraceLogging provider, enabling it to generate events. + // Return true if enabled, otherwise false. + if (s_is64bitProcess) + { + return SNINativeManagedWrapperX64.RegisterTraceProviderWrapper(eventKeyword); + } + else + { + return SNINativeManagedWrapperX86.RegisterTraceProviderWrapper(eventKeyword); + } + } + + internal static void UnregisterTraceProvider() + { + if (s_is64bitProcess) + { + SNINativeManagedWrapperX64.UnregisterTraceProviderWrapper(); + } + else + { + SNINativeManagedWrapperX86.UnregisterTraceProviderWrapper(); + } + } } } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.Windows.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.Windows.cs new file mode 100644 index 0000000000..f9af6024e4 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.Windows.cs @@ -0,0 +1,60 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics; +using System.Diagnostics.Tracing; + +namespace Microsoft.Data.SqlClient +{ + internal partial class SqlClientEventSource : EventSource + { + private bool _traceLoggingProviderEnabled = false; + + /// + /// Captures application flow traces from native networking implementation + /// + private const EventCommand SNINativeTrace = (EventCommand)8192; + + /// + /// Captures scope trace events from native networking implementation + /// + private const EventCommand SNINativeScope = (EventCommand)16384; + + /// + /// Disables all event tracing in native networking implementation + /// + private const EventCommand SNINativeDisable = (EventCommand)32768; + + protected override void OnEventCommand(EventCommandEventArgs e) + { + // Internally, EventListener.EnableEvents sends an event command, with a reserved value of 0, -2, or -3. + // When a command is sent via EnableEvents or SendCommand, check if it is a user-defined value + // to enable or disable event tracing in sni.dll. + // If registration fails, all write and unregister commands will be a no-op. + + // If managed networking is enabled, don't call native wrapper methods +#if netcoreapp + if (AppContext.TryGetSwitch("Switch.Microsoft.Data.SqlClient.UseManagedNetworkingOnWindows", out bool isEnabled) && isEnabled) + { + return; + } +#endif + // Only register the provider if it's not already registered. Registering a provider that is already + // registered can lead to unpredictable behaviour. + if (!_traceLoggingProviderEnabled && e.Command > 0 && (e.Command & (SNINativeTrace | SNINativeScope)) != 0) + { + int eventKeyword = (int)(e.Command & (SNINativeTrace | SNINativeScope)); + _traceLoggingProviderEnabled = SNINativeMethodWrapper.RegisterTraceProvider(eventKeyword); + Debug.Assert(_traceLoggingProviderEnabled, "Failed to enable TraceLogging provider."); + } + else if (_traceLoggingProviderEnabled && (e.Command == SNINativeDisable)) + { + // Only unregister the provider if it's currently registered. + SNINativeMethodWrapper.UnregisterTraceProvider(); + _traceLoggingProviderEnabled = false; + } + } + } +} diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index 93e544a713..f9000f5d9f 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -8,7 +8,7 @@ namespace Microsoft.Data.SqlClient { [EventSource(Name = "Microsoft.Data.SqlClient.EventSource")] - internal class SqlClientEventSource : EventSource + internal partial class SqlClientEventSource : EventSource { // Defines the singleton instance for the Resources ETW provider internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); From 9e236792c3b54b51f1dde864f9b6444b56fa1233 Mon Sep 17 00:00:00 2001 From: Javad Date: Fri, 21 Aug 2020 15:24:46 -0700 Subject: [PATCH 11/24] Optimizing Eventsource memory allocations and removing an extra comment. (#684) --- .../src/Microsoft/Data/Common/AdapterUtil.cs | 2 +- .../Data/ProviderBase/DbConnectionFactory.cs | 26 +- .../Data/ProviderBase/DbConnectionInternal.cs | 10 +- .../ProviderBase/DbConnectionPoolGroup.cs | 6 +- .../src/Microsoft/Data/DataException.cs | 4 +- .../Data/ProviderBase/DbConnectionFactory.cs | 4 +- .../Data/ProviderBase/DbConnectionInternal.cs | 18 +- .../Data/ProviderBase/DbConnectionPool.cs | 94 +- .../Data/SqlClient/LocalDBAPI.Common.cs | 2 +- .../Data/SqlClient/LocalDBAPI.Windows.cs | 2 +- .../Data/SqlClient/SNI/LocalDB.Windows.cs | 38 +- .../Microsoft/Data/SqlClient/SNI/SNICommon.cs | 12 +- .../Data/SqlClient/SNI/SNILoadHandle.cs | 2 +- .../Data/SqlClient/SNI/SNIMarsConnection.cs | 46 +- .../Data/SqlClient/SNI/SNIMarsHandle.cs | 54 +- .../Data/SqlClient/SNI/SNINpHandle.cs | 60 +- .../src/Microsoft/Data/SqlClient/SNI/SSRP.cs | 10 +- ...uthenticationProviderManager.NetCoreApp.cs | 2 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 8 +- .../Data/SqlClient/SqlClientEventSource.cs | 949 ------------------ .../Microsoft/Data/SqlClient/SqlCommand.cs | 129 ++- .../Microsoft/Data/SqlClient/SqlCommandSet.cs | 10 +- .../Microsoft/Data/SqlClient/SqlConnection.cs | 64 +- .../Data/SqlClient/SqlConnectionFactory.cs | 2 +- .../Data/SqlClient/SqlConnectionHelper.cs | 18 +- .../SqlConnectionPoolGroupProviderInfo.cs | 4 +- .../Data/SqlClient/SqlDataAdapter.cs | 6 +- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 28 +- .../Data/SqlClient/SqlDelegatedTransaction.cs | 20 +- .../Microsoft/Data/SqlClient/SqlDependency.cs | 114 +-- .../Data/SqlClient/SqlDependencyListener.cs | 164 +-- .../SqlClient/SqlDependencyUtils.AppDomain.cs | 4 +- .../Data/SqlClient/SqlDependencyUtils.cs | 78 +- .../src/Microsoft/Data/SqlClient/SqlError.cs | 2 +- .../Data/SqlClient/SqlInternalConnection.cs | 16 +- .../SqlClient/SqlInternalConnectionTds.cs | 113 ++- .../Data/SqlClient/SqlInternalTransaction.cs | 22 +- .../Data/SqlClient/SqlTransaction.cs | 24 +- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 140 +-- .../Data/SqlClient/TdsParserSessionPool.cs | 18 +- .../Data/SqlClient/TdsParserStateObject.cs | 68 +- .../TdsParserStateObjectFactory.Windows.cs | 4 +- .../Data/SqlTypes/SqlFileStream.Windows.cs | 6 +- .../src/Microsoft/Data/Common/AdapterUtil.cs | 2 +- .../Data/Common/DBConnectionString.cs | 4 +- .../Data/Common/DbConnectionOptions.cs | 2 +- .../netfx/src/Microsoft/Data/DataException.cs | 4 +- .../Data/ProviderBase/DbConnectionFactory.cs | 30 +- .../Data/ProviderBase/DbConnectionInternal.cs | 28 +- .../Data/ProviderBase/DbConnectionPool.cs | 100 +- .../ProviderBase/DbConnectionPoolGroup.cs | 6 +- .../Data/ProviderBase/SqlConnectionHelper.cs | 20 +- .../Microsoft/Data/SqlClient/LocalDBAPI.cs | 12 +- .../SqlClient/Server/SmiEventSink_Default.cs | 2 +- .../Data/SqlClient/Server/SmiMetaData.cs | 2 +- .../SqlAuthenticationProviderManager.cs | 2 +- .../Microsoft/Data/SqlClient/SqlBulkCopy.cs | 30 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 117 +-- .../Microsoft/Data/SqlClient/SqlCommandSet.cs | 10 +- .../Microsoft/Data/SqlClient/SqlConnection.cs | 60 +- .../Data/SqlClient/SqlConnectionFactory.cs | 2 +- .../SqlConnectionPoolGroupProviderInfo.cs | 4 +- .../Data/SqlClient/SqlDataAdapter.cs | 6 +- .../Microsoft/Data/SqlClient/SqlDataReader.cs | 32 +- .../Data/SqlClient/SqlDataReaderSmi.cs | 26 +- .../Data/SqlClient/SqlDelegatedTransaction.cs | 20 +- .../Microsoft/Data/SqlClient/SqlDependency.cs | 138 +-- .../Data/SqlClient/SqlDependencyListener.cs | 164 +-- .../Data/SqlClient/SqlDependencyUtils.cs | 82 +- .../src/Microsoft/Data/SqlClient/SqlError.cs | 2 +- .../Data/SqlClient/SqlInternalConnection.cs | 16 +- .../SqlClient/SqlInternalConnectionSmi.cs | 44 +- .../SqlClient/SqlInternalConnectionTds.cs | 119 +-- .../Data/SqlClient/SqlTransaction.cs | 24 +- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 120 +-- .../Data/SqlClient/TdsParserSessionPool.cs | 18 +- .../Data/SqlClient/TdsParserStateObject.cs | 30 +- .../Data/SqlClient/sqlinternaltransaction.cs | 22 +- .../Microsoft/Data/SqlTypes/SqlFileStream.cs | 6 +- .../Data/SqlClient/SqlClientEventSource.cs | 269 +++-- .../Data/SqlClient/SqlClientLogger.cs | 8 +- 81 files changed, 1569 insertions(+), 2417 deletions(-) delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs index 74d812cf5d..396d43caa6 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/Common/AdapterUtil.cs @@ -39,7 +39,7 @@ static private void TraceException(string trace, Exception e) Debug.Assert(null != e, "TraceException: null Exception"); if (null != e) { - SqlClientEventSource.Log.TraceEvent(trace, e); + SqlClientEventSource.Log.TryTraceEvent(trace, e); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index cfbdd659eb..1ee4cba196 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -49,7 +49,7 @@ abstract public DbProviderFactory ProviderFactory public void ClearAllPools() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" connectionPoolGroups = _connectionPoolGroups; @@ -64,14 +64,14 @@ public void ClearAllPools() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } public void ClearPool(DbConnection connection) { ADP.CheckArgumentNull(connection, nameof(connection)); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", GetObjectId(connection)); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", GetObjectId(connection)); try { DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); @@ -82,7 +82,7 @@ public void ClearPool(DbConnection connection) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -90,7 +90,7 @@ public void ClearPool(DbConnectionPoolKey key) { Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, nameof(key) + "." + nameof(key.ConnectionString)); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" connectionString"); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" connectionString"); try { DbConnectionPoolGroup poolGroup; @@ -102,7 +102,7 @@ public void ClearPool(DbConnectionPoolKey key) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -126,7 +126,7 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne { newConnection.MakeNonPooledObject(owningConnection); } - SqlClientEventSource.Log.TraceEvent(" {0}, Non-pooled database connection created.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Non-pooled database connection created.", ObjectID); return newConnection; } @@ -140,7 +140,7 @@ internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbCo { newConnection.MakePooledConnection(pool); } - SqlClientEventSource.Log.TraceEvent(" {0}, Pooled database connection created.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Pooled database connection created.", ObjectID); return newConnection; } @@ -195,7 +195,7 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti // however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) { - SqlClientEventSource.Log.TraceEvent(" {0}, DisabledPoolGroup={1}", ObjectID, connectionPoolGroup.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, DisabledPoolGroup={1}", ObjectID, connectionPoolGroup?.ObjectID); // reusing existing pool option in case user originally used SetConnectionPoolOptions DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions; @@ -303,7 +303,7 @@ internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, D private void PruneConnectionPoolGroups(object state) { // when debugging this method, expect multiple threads at the same time - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}", ObjectID); // First, walk the pool release list and attempt to clear each // pool, when the pool is finally empty, we dispose of it. If the @@ -323,7 +323,7 @@ private void PruneConnectionPoolGroups(object state) if (0 == pool.Count) { _poolsToRelease.Remove(pool); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, ReleasePool={1}", ObjectID, pool.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, ReleasePool={1}", ObjectID, pool.ObjectID); } } } @@ -347,7 +347,7 @@ private void PruneConnectionPoolGroups(object state) if (0 == poolsLeft) { _poolGroupsToRelease.Remove(poolGroup); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, ReleasePoolGroup={1}", ObjectID, poolGroup.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, ReleasePoolGroup={1}", ObjectID, poolGroup.ObjectID); } } } @@ -410,7 +410,7 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { Debug.Assert(null != poolGroup, "null poolGroup?"); - SqlClientEventSource.Log.TraceEvent(" {0}, poolGroup={1}", ObjectID, poolGroup.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, poolGroup={1}", ObjectID, poolGroup.ObjectID); lock (_poolGroupsToRelease) { diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index fdb2042b54..0e92ed4f00 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -225,7 +225,7 @@ internal void DeactivateConnection() { // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Deactivating", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Deactivating", ObjectID); #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); @@ -249,14 +249,14 @@ internal void DeactivateConnection() protected internal void DoNotPoolThisConnection() { _cannotBePooled = true; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Marking pooled object as non-poolable so it will be disposed", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Marking pooled object as non-poolable so it will be disposed", ObjectID); } /// Ensure that this connection cannot be put back into the pool. protected internal void DoomThisConnection() { _connectionIsDoomed = true; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Dooming", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Dooming", ObjectID); } // Reset connection doomed status so it can be re-connected and pooled. @@ -383,7 +383,7 @@ internal void PrePush(object expectedOwner) throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time } - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Preparing to push into pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Preparing to push into pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount); _pooledCount++; _owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2% } @@ -412,7 +412,7 @@ internal void PostPop(object newOwner) } _owningObject.Target = newOwner; _pooledCount--; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Preparing to pop from pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Preparing to pop from pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount); //3 // The following tests are retail assertions of things we can't allow to happen. if (null != Pool) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs index 4c8e9adec6..5801057092 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -229,7 +229,7 @@ private bool MarkPoolGroupAsActive() if (PoolGroupStateIdle == _state) { _state = PoolGroupStateActive; - SqlClientEventSource.Log.TraceEvent(" {0}, Active", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Active", ObjectID); } return (PoolGroupStateActive == _state); } @@ -281,12 +281,12 @@ internal bool Prune() if (PoolGroupStateActive == _state) { _state = PoolGroupStateIdle; - SqlClientEventSource.Log.TraceEvent(" {0}, Idle", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Idle", ObjectID); } else if (PoolGroupStateIdle == _state) { _state = PoolGroupStateDisabled; - SqlClientEventSource.Log.TraceEvent(" {0}, Disabled", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Disabled", ObjectID); } } return (PoolGroupStateDisabled == _state); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs index e7613a4616..4d929e4031 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/DataException.cs @@ -31,8 +31,8 @@ static private void TraceException( Debug.Assert(null != e, "TraceException: null Exception"); if (null != e) { - SqlClientEventSource.Log.AdvancedTraceEvent(trace, e.Message); - SqlClientEventSource.Log.AdvancedTraceEvent(" Environment StackTrace = '{0}'", Environment.StackTrace); + SqlClientEventSource.Log.TryAdvancedTraceEvent(trace, e.Message); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Environment StackTrace = '{0}'", Environment.StackTrace); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index eed3ff6970..d620caa34a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -129,7 +129,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour // connection creation failed on semaphore waiting or if max pool reached if (connectionPool.IsRunning) { - SqlClientEventSource.Log.TraceEvent(" {0}, GetConnection failed because a pool timeout occurred.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, GetConnection failed because a pool timeout occurred.", ObjectID); // If GetConnection failed while the pool is running, the pool timeout occurred. throw ADP.PooledOpenTimeout(); } @@ -147,7 +147,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour if (connection == null) { - SqlClientEventSource.Log.TraceEvent(" {0}, GetConnection failed because a pool timeout occurred and all retries were exhausted.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, GetConnection failed because a pool timeout occurred and all retries were exhausted.", ObjectID); // exhausted all retries or timed out - give up throw ADP.PooledOpenTimeout(); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index 7f959eb1c9..232aef3c77 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -105,7 +105,7 @@ protected internal Transaction EnlistedTransaction if (null != value) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Enlisting.", ObjectID, value.GetHashCode()); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Enlisting.", ObjectID, value.GetHashCode()); TransactionOutcomeEnlist(value); } } @@ -211,7 +211,7 @@ internal void ActivateConnection(Transaction transaction) { // Internal method called from the connection pooler so we don't expose // the Activate method publicly. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Activating", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Activating", ObjectID); #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); @@ -261,7 +261,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac //////////////////////////////////////////////////////////////// Debug.Assert(null != owningObject, "null owningObject"); Debug.Assert(null != connectionFactory, "null connectionFactory"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0} Closing.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0} Closing.", ObjectID); // if an exception occurs after the state change but before the try block // the connection will be stuck in OpenBusy state. The commented out try-catch @@ -336,7 +336,7 @@ virtual internal void DelegatedTransactionEnded() // IMPORTANT NOTE: You must have taken a lock on the object before // you call this method to prevent race conditions with Clear and // ReclaimEmancipatedObjects. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Delegated Transaction Completed.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Delegated Transaction Completed.", ObjectID); if (1 == _pooledCount) { @@ -428,7 +428,7 @@ internal void DetachCurrentTransactionIfEnded() // Detach transaction from connection. internal void DetachTransaction(Transaction transaction, bool isExplicitlyReleasing) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction Completed. (pooledCount={1})", ObjectID, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction Completed. (pooledCount={1})", ObjectID, _pooledCount); // potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new // transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should @@ -468,7 +468,7 @@ internal void CleanupConnectionOnTransactionCompletion(Transaction transaction) void TransactionCompletedEvent(object sender, TransactionEventArgs e) { Transaction transaction = e.Transaction; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); CleanupTransactionOnCompletion(transaction); CleanupConnectionOnTransactionCompletion(transaction); } @@ -481,18 +481,18 @@ private void TransactionOutcomeEnlist(Transaction transaction) internal void SetInStasis() { _isInStasis = true; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID); } private void TerminateStasis(bool returningToPool) { if (returningToPool) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed. Returning to general pool.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed. Returning to general pool.", ObjectID); } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed/leaked. Disposing.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed/leaked. Disposing.", ObjectID); } _isInStasis = false; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index 90ada93ff3..d0921da04c 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -74,7 +74,7 @@ internal TransactedConnectionPool(DbConnectionPool pool) _pool = pool; _transactedCxns = new Dictionary(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Constructed for connection pool {1}", ObjectID, _pool.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Constructed for connection pool {1}", ObjectID, _pool.ObjectID); } internal int ObjectID @@ -133,7 +133,7 @@ internal DbConnectionInternal GetTransactedObject(Transaction transaction) if (null != transactedObject) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } return transactedObject; } @@ -160,7 +160,7 @@ internal void PutTransactedObject(Transaction transaction, DbConnectionInternal lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); connections.Add(transactedObject); } } @@ -195,13 +195,13 @@ internal void PutTransactedObject(Transaction transaction, DbConnectionInternal lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); connections.Add(transactedObject); } } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Adding List to transacted pool.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Adding List to transacted pool.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); // add the connection/transacted object to the list newConnections.Add(transactedObject); @@ -229,13 +229,13 @@ internal void PutTransactedObject(Transaction transaction, DbConnectionInternal } } } - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Added.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Added.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } } internal void TransactionEnded(Transaction transaction, DbConnectionInternal transactedObject) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); TransactedConnectionList connections; int entry = -1; @@ -269,7 +269,7 @@ internal void TransactionEnded(Transaction transaction, DbConnectionInternal tra // safely remove the list from the transacted pool. if (0 >= connections.Count) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Removing List from transacted pool.", ObjectID, transaction.GetHashCode()); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Removing List from transacted pool.", ObjectID, transaction.GetHashCode()); _transactedCxns.Remove(transaction); // we really need to dispose our connection list; it may have @@ -285,7 +285,7 @@ internal void TransactionEnded(Transaction transaction, DbConnectionInternal tra } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transacted pool not yet created prior to transaction completing. Connection may be leaked.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transacted pool not yet created prior to transaction completing. Connection may be leaked.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } } @@ -443,7 +443,7 @@ internal DbConnectionPool( _poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback _state = State.Running; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Constructed.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Constructed.", ObjectID); //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls // StartBackgroundCallbacks after pool is actually in the collection @@ -586,7 +586,7 @@ private void CleanupCallback(object state) // // With this logic, objects are pruned from the pool if unused for // at least one period but not more than two periods. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}", ObjectID); // Destroy free objects that put us above MinPoolSize from old stack. while (Count > MinPoolSize) @@ -658,7 +658,7 @@ private void CleanupCallback(object state) break; Debug.Assert(obj != null, "null connection is not expected"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, ChangeStacks={1}", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, ChangeStacks={1}", ObjectID, obj.ObjectID); Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); Debug.Assert(obj.CanBePooled, "pooled object is not poolable"); @@ -673,7 +673,7 @@ private void CleanupCallback(object state) internal void Clear() { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Clearing.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Clearing.", ObjectID); DbConnectionInternal obj; // First, quickly doom everything. @@ -707,7 +707,7 @@ internal void Clear() // Finally, reclaim everything that's emancipated (which, because // it's been doomed, will cause it to be disposed of as well) ReclaimEmancipatedObjects(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Cleared.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Cleared.", ObjectID); } private Timer CreateCleanupTimer() => @@ -758,7 +758,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio } } } - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Added to pool.", ObjectID, newObj != null ? newObj?.ObjectID.ToString() ?? "null" : "null"); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Added to pool.", ObjectID, newObj?.ObjectID); // Reset the error wait: _errorWait = ERROR_WAIT_DEFAULT; @@ -816,7 +816,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio private void DeactivateObject(DbConnectionInternal obj) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Deactivating.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Deactivating.", ObjectID, obj.ObjectID); obj.DeactivateConnection(); bool returnToGeneralPool = false; @@ -951,11 +951,11 @@ internal void DestroyObject(DbConnectionInternal obj) // again. if (obj.IsTxRootWaitingForTxEnd) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Has Delegated Transaction, waiting to Dispose.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Has Delegated Transaction, waiting to Dispose.", ObjectID, obj.ObjectID); } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Removing from pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Removing from pool.", ObjectID, obj.ObjectID); bool removed = false; lock (_objectList) { @@ -966,16 +966,16 @@ internal void DestroyObject(DbConnectionInternal obj) if (removed) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Removed from pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Removed from pool.", ObjectID, obj.ObjectID); } obj.Dispose(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Disposed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Disposed.", ObjectID, obj.ObjectID); } } private void ErrorCallback(object state) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Resetting Error handling.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Resetting Error handling.", ObjectID); _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); @@ -1106,7 +1106,7 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource {0}, DbConnectionInternal State != Running.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, DbConnectionInternal State != Running.", ObjectID); connection = null; return true; } @@ -1146,7 +1146,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj { DbConnectionInternal obj = null; Transaction transaction = null; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Getting connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Getting connection.", ObjectID); // If automatic transaction enlistment is required, then we try to // get the connection from the transacted connection pool first. @@ -1181,19 +1181,19 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj switch (waitResult) { case WaitHandle.WaitTimeout: - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Wait timed out.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Wait timed out.", ObjectID); Interlocked.Decrement(ref _waitCount); connection = null; return false; case ERROR_HANDLE: // Throw the error that PoolCreateRequest stashed. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Errors are set.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Errors are set.", ObjectID); Interlocked.Decrement(ref _waitCount); throw TryCloneCachedException(); case CREATION_HANDLE: - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Creating new connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Creating new connection.", ObjectID); try { obj = UserCreateRequest(owningObject, userOptions); @@ -1243,7 +1243,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj if ((obj != null) && (!obj.IsConnectionAlive())) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); obj = null; // Setting to null in case creating a new object fails @@ -1253,7 +1253,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj { try { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Creating new connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Creating new connection.", ObjectID); obj = UserCreateRequest(owningObject, userOptions); } finally @@ -1264,7 +1264,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj else { // Timeout waiting for creation semaphore - return null - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Wait timed out.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Wait timed out.", ObjectID); connection = null; return false; } @@ -1273,7 +1273,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj break; default: - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, WaitForMultipleObjects={1}", ObjectID, waitResult); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, WaitForMultipleObjects={1}", ObjectID, waitResult); Interlocked.Decrement(ref _waitCount); throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult); } @@ -1287,7 +1287,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj } // Do not use this pooled connection if access token is about to expire soon before we can connect. - if(null != obj && obj.IsAccessTokenExpired) + if (null != obj && obj.IsAccessTokenExpired) { DestroyObject(obj); obj = null; @@ -1332,7 +1332,7 @@ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal o /// A new inner connection that is attached to the internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, replacing connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, replacing connection.", ObjectID); DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); if (newConnection != null) @@ -1373,7 +1373,7 @@ private DbConnectionInternal GetFromGeneralPool() if (null != obj) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Popped from general pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Popped from general pool.", ObjectID, obj.ObjectID); } return (obj); } @@ -1389,7 +1389,7 @@ private DbConnectionInternal GetFromTransactedPool(out Transaction transaction) if (null != obj) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Popped from transacted pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Popped from transacted pool.", ObjectID, obj.ObjectID); if (obj.IsTransactionRoot) { @@ -1399,14 +1399,14 @@ private DbConnectionInternal GetFromTransactedPool(out Transaction transaction) } catch { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); throw; } } else if (!obj.IsConnectionAlive()) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); obj = null; } @@ -1419,7 +1419,7 @@ private void PoolCreateRequest(object state) { // called by pooler to ensure pool requests are currently being satisfied - // creation mutex has not been obtained - long scopeID = SqlClientEventSource.Log.PoolerScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryPoolerScopeEnterEvent(" {0}", ObjectID); try { if (State.Running == _state) @@ -1503,7 +1503,7 @@ private void PoolCreateRequest(object state) } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, PoolCreateRequest called WaitForSingleObject failed {1}", ObjectID, waitResult); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, PoolCreateRequest called WaitForSingleObject failed {1}", ObjectID, waitResult); } } catch (Exception e) @@ -1516,7 +1516,7 @@ private void PoolCreateRequest(object state) // Now that CreateObject can throw, we need to catch the exception and discard it. // There is no further action we can take beyond tracing. The error will be // thrown to the user the next time they request a connection. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, PoolCreateRequest called CreateConnection which threw an exception: {1}", ObjectID, e); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, PoolCreateRequest called CreateConnection which threw an exception: {1}", ObjectID, e); } finally { @@ -1532,7 +1532,7 @@ private void PoolCreateRequest(object state) } finally { - SqlClientEventSource.Log.PoolerScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryPoolerScopeLeaveEvent(scopeID); } } @@ -1540,7 +1540,7 @@ internal void PutNewObject(DbConnectionInternal obj) { Debug.Assert(null != obj, "why are we adding a null object to the pool?"); // Debug.Assert(obj.CanBePooled, "non-poolable object in pool"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Pushing to general pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Pushing to general pool.", ObjectID, obj.ObjectID); _stackNew.Push(obj); _waitHandles.PoolSemaphore.Release(1); @@ -1584,7 +1584,7 @@ internal void PutObjectFromTransactedPool(DbConnectionInternal obj) // method, we can safely presume that the caller is the only person // that is using the connection, and that all pre-push logic has been // done and all transactions are ended. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Transaction has ended.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Transaction has ended.", ObjectID, obj.ObjectID); if (_state == State.Running && obj.CanBePooled) { @@ -1609,7 +1609,7 @@ private void QueuePoolCreateRequest() private bool ReclaimEmancipatedObjects() { bool emancipatedObjectFound = false; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}", ObjectID); List reclaimedObjects = new List(); int count; @@ -1661,7 +1661,7 @@ private bool ReclaimEmancipatedObjects() for (int i = 0; i < count; ++i) { DbConnectionInternal obj = reclaimedObjects[i]; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Reclaiming.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Reclaiming.", ObjectID, obj.ObjectID); emancipatedObjectFound = true; obj.DetachCurrentTransactionIfEnded(); @@ -1672,7 +1672,7 @@ private bool ReclaimEmancipatedObjects() internal void Startup() { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, CleanupWait={1}", ObjectID, _cleanupWait); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, CleanupWait={1}", ObjectID, _cleanupWait); _cleanupTimer = CreateCleanupTimer(); if (NeedToReplenish) { @@ -1682,7 +1682,7 @@ internal void Startup() internal void Shutdown() { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}", ObjectID); _state = State.ShuttingDown; // deactivate timer callbacks @@ -1704,7 +1704,7 @@ internal void TransactionEnded(Transaction transaction, DbConnectionInternal tra Debug.Assert(null != transactedObject, "null transactedObject?"); // Note: connection may still be associated with transaction due to Explicit Unbinding requirement. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); // called by the internal connection when it get's told that the // transaction is completed. We tell the transacted pool to remove diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Common.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Common.cs index 834fa09628..f072900b6e 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Common.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Common.cs @@ -38,7 +38,7 @@ private static LocalDBFormatMessageDelegate LocalDBFormatMessage { // SNI checks for LocalDBFormatMessage during DLL loading, so it is practically impossible to get this error. int hResult = Marshal.GetLastWin32Error(); - SqlClientEventSource.Log.TraceEvent(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); + SqlClientEventSource.Log.TryTraceEvent(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); throw CreateLocalDBException(errorMessage: Strings.LocalDB_MethodNotFound); } s_localDBFormatMessage = Marshal.GetDelegateForFunctionPointer(functionAddr); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs index d4b3a73133..6334e5873d 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs @@ -24,7 +24,7 @@ private static IntPtr UserInstanceDLLHandle SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle); if(s_userInstanceDLLHandle != IntPtr.Zero) { - SqlClientEventSource.Log.TraceEvent(" LocalDB - handle obtained"); + SqlClientEventSource.Log.TryTraceEvent(" LocalDB - handle obtained"); } else { diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Windows.cs index bd3ce43eb2..e77b93f5f0 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Windows.cs @@ -64,26 +64,26 @@ internal static uint MapLocalDBErrorStateToCode(LocalDBErrorState errorState) switch (errorState) { case LocalDBErrorState.NO_INSTALLATION: - SqlClientEventSource.Log.SNITraceEvent(" LocalDB is not installed. Error State ={0}", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" LocalDB is not installed. Error State ={0}", errorState); return SNICommon.LocalDBNoInstallation; case LocalDBErrorState.INVALID_CONFIG: - SqlClientEventSource.Log.SNITraceEvent(" Invalid configuration. Error State ={0}", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" Invalid configuration. Error State ={0}", errorState); return SNICommon.LocalDBInvalidConfig; case LocalDBErrorState.NO_SQLUSERINSTANCEDLL_PATH: - SqlClientEventSource.Log.SNITraceEvent(" No SQL user instance path. Error State ={0}", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" No SQL user instance path. Error State ={0}", errorState); return SNICommon.LocalDBNoSqlUserInstanceDllPath; case LocalDBErrorState.INVALID_SQLUSERINSTANCEDLL_PATH: - SqlClientEventSource.Log.SNITraceEvent(" Invalid SQL user instance path. Error State ={0}", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" Invalid SQL user instance path. Error State ={0}", errorState); return SNICommon.LocalDBInvalidSqlUserInstanceDllPath; case LocalDBErrorState.NONE: return 0; default: - SqlClientEventSource.Log.SNITraceEvent(" Invalid configuration. Error State ={0}", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" Invalid configuration. Error State ={0}", errorState); return SNICommon.LocalDBInvalidConfig; } } @@ -93,7 +93,7 @@ internal static uint MapLocalDBErrorStateToCode(LocalDBErrorState errorState) /// private bool LoadUserInstanceDll() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { // Check in a non thread-safe way if the handle is already set for performance. @@ -118,7 +118,7 @@ private bool LoadUserInstanceDll() if (dllPath == null) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, MapLocalDBErrorStateToCode(registryQueryErrorState), string.Empty); - SqlClientEventSource.Log.SNITraceEvent("User instance DLL path is null."); + SqlClientEventSource.Log.TrySNITraceEvent("User instance DLL path is null."); return false; } @@ -126,7 +126,7 @@ private bool LoadUserInstanceDll() if (string.IsNullOrWhiteSpace(dllPath)) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBInvalidSqlUserInstanceDllPath, string.Empty); - SqlClientEventSource.Log.SNITraceEvent(" User instance DLL path is invalid. DLL path ={0}", dllPath); + SqlClientEventSource.Log.TrySNITraceEvent(" User instance DLL path is invalid. DLL path ={0}", dllPath); return false; } @@ -136,7 +136,7 @@ private bool LoadUserInstanceDll() if (libraryHandle.IsInvalid) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBFailedToLoadDll, string.Empty); - SqlClientEventSource.Log.SNITraceEvent(" Library Handle is invalid. Could not load the dll."); + SqlClientEventSource.Log.TrySNITraceEvent(" Library Handle is invalid. Could not load the dll."); libraryHandle.Dispose(); return false; } @@ -147,7 +147,7 @@ private bool LoadUserInstanceDll() if (_startInstanceHandle == IntPtr.Zero) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBBadRuntime, string.Empty); - SqlClientEventSource.Log.SNITraceEvent(" Was not able to load the PROC from DLL. Bad Runtime."); + SqlClientEventSource.Log.TrySNITraceEvent(" Was not able to load the PROC from DLL. Bad Runtime."); libraryHandle.Dispose(); return false; } @@ -164,13 +164,13 @@ private bool LoadUserInstanceDll() } _sqlUserInstanceLibraryHandle = libraryHandle; - SqlClientEventSource.Log.SNITraceEvent(" User Instance DLL was loaded successfully."); + SqlClientEventSource.Log.TrySNITraceEvent(" User Instance DLL was loaded successfully."); return true; } } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -181,7 +181,7 @@ private bool LoadUserInstanceDll() /// private string GetUserInstanceDllPath(out LocalDBErrorState errorState) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(" GetUserInstanceDllPath"); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(" GetUserInstanceDllPath"); try { string dllPath = null; @@ -190,7 +190,7 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) if (key == null) { errorState = LocalDBErrorState.NO_INSTALLATION; - SqlClientEventSource.Log.SNITraceEvent(" not installed. Error state ={0}.", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" not installed. Error state ={0}.", errorState); return null; } @@ -205,7 +205,7 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) if (!Version.TryParse(subKey, out currentKeyVersion)) { errorState = LocalDBErrorState.INVALID_CONFIG; - SqlClientEventSource.Log.SNITraceEvent(" Invalid Configuration. state ={0}.", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" Invalid Configuration. state ={0}.", errorState); return null; } @@ -219,7 +219,7 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) if (latestVersion.Equals(zeroVersion)) { errorState = LocalDBErrorState.INVALID_CONFIG; - SqlClientEventSource.Log.SNITraceEvent(" Invalid Configuration. state ={0}.", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" Invalid Configuration. state ={0}.", errorState); return null; } @@ -232,7 +232,7 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) if (instanceAPIPathRegistryObject == null) { errorState = LocalDBErrorState.NO_SQLUSERINSTANCEDLL_PATH; - SqlClientEventSource.Log.SNITraceEvent(" No SQL user instance DLL. Instance API Path Registry Object Error. state ={0}.", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" No SQL user instance DLL. Instance API Path Registry Object Error. state ={0}.", errorState); return null; } @@ -241,7 +241,7 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) if (valueKind != RegistryValueKind.String) { errorState = LocalDBErrorState.INVALID_SQLUSERINSTANCEDLL_PATH; - SqlClientEventSource.Log.SNITraceEvent(" No SQL user instance DLL. state ={0}. Registry value kind error.", errorState); + SqlClientEventSource.Log.TrySNITraceEvent(" No SQL user instance DLL. state ={0}. Registry value kind error.", errorState); return null; } @@ -254,7 +254,7 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs index 94ed2bece1..475660aa2b 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs @@ -136,18 +136,18 @@ internal class SNICommon /// True if certificate is valid internal static bool ValidateSslServerCertificate(string targetServerName, object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { if (policyErrors == SslPolicyErrors.None) { - SqlClientEventSource.Log.SNITraceEvent(" SSL Server certificate validated."); + SqlClientEventSource.Log.TrySNITraceEvent(" SSL Server certificate validated."); return true; } if ((policyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) { - SqlClientEventSource.Log.SNITraceEvent(" SSL Remote certificate name mismatched."); + SqlClientEventSource.Log.TrySNITraceEvent(" SSL Remote certificate name mismatched."); string certServerName = cert.Subject.Substring(cert.Subject.IndexOf('=') + 1); // Verify that target server name matches subject in the certificate @@ -189,7 +189,7 @@ internal static bool ValidateSslServerCertificate(string targetServerName, objec } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -203,7 +203,7 @@ internal static bool ValidateSslServerCertificate(string targetServerName, objec /// internal static uint ReportSNIError(SNIProviders provider, uint nativeError, uint sniError, string errorMessage) { - SqlClientEventSource.Log.SNITraceEvent(" Provider ={0}, native Error ={1}, SNI Error ={2}, Error Message ={3}", provider, nativeError, sniError, errorMessage); + SqlClientEventSource.Log.TrySNITraceEvent(" Provider ={0}, native Error ={1}, SNI Error ={2}, Error Message ={3}", provider, nativeError, sniError, errorMessage); return ReportSNIError(new SNIError(provider, nativeError, sniError, errorMessage)); } @@ -216,7 +216,7 @@ internal static uint ReportSNIError(SNIProviders provider, uint nativeError, uin /// internal static uint ReportSNIError(SNIProviders provider, uint sniError, Exception sniException) { - SqlClientEventSource.Log.SNITraceEvent(" Provider ={0}, SNI Error ={1}, Exception ={2}", provider, sniError, sniException.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" Provider ={0}, SNI Error ={1}, Exception ={2}", provider, sniError, sniException.Message); return ReportSNIError(new SNIError(provider, sniError, sniException)); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNILoadHandle.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNILoadHandle.cs index 2488e8a8a6..6e885462e5 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNILoadHandle.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNILoadHandle.cs @@ -30,7 +30,7 @@ public SNIError LastError set { - SqlClientEventSource.Log.SNITraceEvent(" Last Error Value = {0}", value); + SqlClientEventSource.Log.TrySNITraceEvent(" Last Error Value = {0}", value); _lastError.Value = value; } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsConnection.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsConnection.cs index 5877508942..555f368241 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsConnection.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsConnection.cs @@ -64,22 +64,22 @@ public SNIMarsHandle CreateMarsSession(object callbackObject, bool async) /// public uint StartReceive() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(" StartReceive"); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(" StartReceive"); try { SNIPacket packet = null; if (ReceiveAsync(ref packet) == TdsEnums.SNI_SUCCESS_IO_PENDING) { - SqlClientEventSource.Log.SNITraceEvent(" Success IO pending."); + SqlClientEventSource.Log.TrySNITraceEvent(" Success IO pending."); return TdsEnums.SNI_SUCCESS_IO_PENDING; } - SqlClientEventSource.Log.SNITraceEvent(" Connection not useable."); + SqlClientEventSource.Log.TrySNITraceEvent(" Connection not useable."); return SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnNotUsableError, string.Empty); } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -90,7 +90,7 @@ public uint StartReceive() /// SNI error code public uint Send(SNIPacket packet) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(" Send"); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(" Send"); try { lock (this) @@ -100,7 +100,7 @@ public uint Send(SNIPacket packet) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -112,7 +112,7 @@ public uint Send(SNIPacket packet) /// SNI error code public uint SendAsync(SNIPacket packet, SNIAsyncCallback callback) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(" SendAsync"); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(" SendAsync"); try { lock (this) @@ -122,7 +122,7 @@ public uint SendAsync(SNIPacket packet, SNIAsyncCallback callback) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -133,7 +133,7 @@ public uint SendAsync(SNIPacket packet, SNIAsyncCallback callback) /// SNI error code public uint ReceiveAsync(ref SNIPacket packet) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(" SendAsync"); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(" SendAsync"); try { if (packet != null) @@ -149,7 +149,7 @@ public uint ReceiveAsync(ref SNIPacket packet) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -159,7 +159,7 @@ public uint ReceiveAsync(ref SNIPacket packet) /// SNI error status public uint CheckConnection() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (this) @@ -169,7 +169,7 @@ public uint CheckConnection() } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -181,7 +181,7 @@ public void HandleReceiveError(SNIPacket packet) Debug.Assert(Monitor.IsEntered(this), "HandleReceiveError was called without being locked."); if (!Monitor.IsEntered(this)) { - SqlClientEventSource.Log.SNITraceEvent(" HandleReceiveError was called without being locked."); + SqlClientEventSource.Log.TrySNITraceEvent(" HandleReceiveError was called without being locked."); } foreach (SNIMarsHandle handle in _sessions.Values) { @@ -211,7 +211,7 @@ public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) /// SNI error code public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { SNISMUXHeader currentHeader = null; @@ -223,7 +223,7 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) lock (this) { HandleReceiveError(packet); - SqlClientEventSource.Log.SNITraceEvent(" not successful."); + SqlClientEventSource.Log.TrySNITraceEvent(" not successful."); return; } } @@ -249,7 +249,7 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING) { - SqlClientEventSource.Log.SNITraceEvent(" not successful."); + SqlClientEventSource.Log.TrySNITraceEvent(" not successful."); return; } @@ -351,7 +351,7 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -360,14 +360,14 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) /// public uint EnableSsl(uint options) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { return _lowerHandle.EnableSsl(options); } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -376,14 +376,14 @@ public uint EnableSsl(uint options) /// public void DisableSsl() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { _lowerHandle.DisableSsl(); } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -403,14 +403,14 @@ public void ReturnPacket(SNIPacket packet) /// public void KillConnection() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { _lowerHandle.KillConnection(); } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } #endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsHandle.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsHandle.cs index 8c35907a8f..5f339f00a2 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsHandle.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsHandle.cs @@ -54,19 +54,19 @@ internal sealed class SNIMarsHandle : SNIHandle /// public override void Dispose() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { SendControlPacket(SNISMUXFlags.SMUX_FIN); } catch (Exception e) { - SqlClientEventSource.Log.SNITraceEvent(" internal exception error = {0}, Member Name={1}", e.Message, e.GetType().Name); + SqlClientEventSource.Log.TrySNITraceEvent(" internal exception error = {0}, Member Name={1}", e.Message, e.GetType().Name); SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e); } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -93,7 +93,7 @@ public SNIMarsHandle(SNIMarsConnection connection, ushort sessionId, object call /// SMUX header flags private void SendControlPacket(SNISMUXFlags flags) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { SNIPacket packet = RentPacket(headerSize: SNISMUXHeader.HEADER_LENGTH, dataSize: 0); @@ -110,7 +110,7 @@ private void SendControlPacket(SNISMUXFlags flags) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -151,7 +151,7 @@ private SNIPacket SetPacketSMUXHeader(SNIPacket packet) public override uint Send(SNIPacket packet) { Debug.Assert(packet.ReservedHeaderSize == SNISMUXHeader.HEADER_LENGTH, "mars handle attempting to send muxed packet without mux reservation in Send"); - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { while (true) @@ -181,7 +181,7 @@ public override uint Send(SNIPacket packet) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -194,14 +194,14 @@ public override uint Send(SNIPacket packet) private uint InternalSendAsync(SNIPacket packet, SNIAsyncCallback callback) { Debug.Assert(packet.ReservedHeaderSize == SNISMUXHeader.HEADER_LENGTH, "mars handle attempting to send muxed packet without mux reservation in InternalSendAsync"); - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (this) { if (_sequenceNumber >= _sendHighwater) { - SqlClientEventSource.Log.SNITraceEvent(" SNI Queue is full"); + SqlClientEventSource.Log.TrySNITraceEvent(" SNI Queue is full"); return TdsEnums.SNI_QUEUE_FULL; } @@ -212,7 +212,7 @@ private uint InternalSendAsync(SNIPacket packet, SNIAsyncCallback callback) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -222,7 +222,7 @@ private uint InternalSendAsync(SNIPacket packet, SNIAsyncCallback callback) /// SNI error code private uint SendPendingPackets() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); SNIMarsQueuedPacket packet = null; try { @@ -239,7 +239,7 @@ private uint SendPendingPackets() if (result != TdsEnums.SNI_SUCCESS && result != TdsEnums.SNI_SUCCESS_IO_PENDING) { - SqlClientEventSource.Log.SNITraceEvent(" InternalSendAsync result is not SNI_SUCCESS and is not SNI_SUCCESS_IO_PENDING"); + SqlClientEventSource.Log.TrySNITraceEvent(" InternalSendAsync result is not SNI_SUCCESS and is not SNI_SUCCESS_IO_PENDING"); return result; } @@ -260,7 +260,7 @@ private uint SendPendingPackets() } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -272,7 +272,7 @@ private uint SendPendingPackets() /// SNI error code public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = null) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (this) @@ -285,7 +285,7 @@ public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = nul } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -296,7 +296,7 @@ public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = nul /// SNI error code public override uint ReceiveAsync(ref SNIPacket packet) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (_receivedPacketQueue) @@ -332,7 +332,7 @@ public override uint ReceiveAsync(ref SNIPacket packet) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -341,7 +341,7 @@ public override uint ReceiveAsync(ref SNIPacket packet) /// public void HandleReceiveError(SNIPacket packet) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { // SNIMarsHandle should only receive calls to this function from the SNIMarsConnection aggregator class @@ -358,7 +358,7 @@ public void HandleReceiveError(SNIPacket packet) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -369,7 +369,7 @@ public void HandleReceiveError(SNIPacket packet) /// SNI error code public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (this) @@ -382,7 +382,7 @@ public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -392,7 +392,7 @@ public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) /// Send highwater mark public void HandleAck(uint highwater) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (this) @@ -406,7 +406,7 @@ public void HandleAck(uint highwater) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -417,7 +417,7 @@ public void HandleAck(uint highwater) /// SMUX header public void HandleReceiveComplete(SNIPacket packet, SNISMUXHeader header) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { lock (this) @@ -454,7 +454,7 @@ public void HandleReceiveComplete(SNIPacket packet, SNISMUXHeader header) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -486,7 +486,7 @@ private void SendAckIfNecessary() /// SNI error code public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { packet = null; @@ -537,7 +537,7 @@ public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNINpHandle.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNINpHandle.cs index 362d4397d2..692aa9b7fe 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNINpHandle.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNINpHandle.cs @@ -40,8 +40,8 @@ internal sealed class SNINpHandle : SNIPhysicalHandle public SNINpHandle(string serverName, string pipeName, long timerExpire, object callbackObject) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(" Constructor"); - SqlClientEventSource.Log.SNITraceEvent(" Constructor. server name = {0}, pipe name = {1}", serverName, pipeName); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(" Constructor"); + SqlClientEventSource.Log.TrySNITraceEvent(" Constructor. server name = {0}, pipe name = {1}", serverName, pipeName); try { _sendSync = new object(); @@ -73,14 +73,14 @@ public SNINpHandle(string serverName, string pipeName, long timerExpire, object { SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, te); _status = TdsEnums.SNI_ERROR; - SqlClientEventSource.Log.SNITraceEvent(" Timed out. Exception = {0}", te.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" Timed out. Exception = {0}", te.Message); return; } catch (IOException ioe) { SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, ioe); _status = TdsEnums.SNI_ERROR; - SqlClientEventSource.Log.SNITraceEvent(" IOException = {0}", ioe.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" IOException = {0}", ioe.Message); return; } @@ -88,7 +88,7 @@ public SNINpHandle(string serverName, string pipeName, long timerExpire, object { SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.ConnOpenFailedError, string.Empty); _status = TdsEnums.SNI_ERROR; - SqlClientEventSource.Log.SNITraceEvent(" Pipe stream is not connected or cannot write or read to/from it."); + SqlClientEventSource.Log.TrySNITraceEvent(" Pipe stream is not connected or cannot write or read to/from it."); return; } @@ -100,7 +100,7 @@ public SNINpHandle(string serverName, string pipeName, long timerExpire, object } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -137,12 +137,12 @@ public override int ProtocolVersion public override uint CheckConnection() { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { if (!_stream.CanWrite || !_stream.CanRead) { - SqlClientEventSource.Log.SNITraceEvent(" cannot write or read to/from the stream"); + SqlClientEventSource.Log.TrySNITraceEvent(" cannot write or read to/from the stream"); return TdsEnums.SNI_ERROR; } else @@ -152,7 +152,7 @@ public override uint CheckConnection() } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -185,7 +185,7 @@ public override void Dispose() public override uint Receive(out SNIPacket packet, int timeout) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { SNIPacket errorPacket; @@ -202,7 +202,7 @@ public override uint Receive(out SNIPacket packet, int timeout) errorPacket = packet; packet = null; var e = new Win32Exception(); - SqlClientEventSource.Log.SNITraceEvent(" packet length is 0."); + SqlClientEventSource.Log.TrySNITraceEvent(" packet length is 0."); return ReportErrorAndReleasePacket(errorPacket, (uint)e.NativeErrorCode, 0, e.Message); } } @@ -210,14 +210,14 @@ public override uint Receive(out SNIPacket packet, int timeout) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.SNITraceEvent(" ObjectDisposedException message = {0}.", ode.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" ObjectDisposedException message = {0}.", ode.Message); return ReportErrorAndReleasePacket(errorPacket, ode); } catch (IOException ioe) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.SNITraceEvent(" IOException message = {0}.", ioe.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" IOException message = {0}.", ioe.Message); return ReportErrorAndReleasePacket(errorPacket, ioe); } return TdsEnums.SNI_SUCCESS; @@ -225,13 +225,13 @@ public override uint Receive(out SNIPacket packet, int timeout) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } public override uint ReceiveAsync(ref SNIPacket packet) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { SNIPacket errorPacket; @@ -246,26 +246,26 @@ public override uint ReceiveAsync(ref SNIPacket packet) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.SNITraceEvent(" ObjectDisposedException message = {0}.", ode.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" ObjectDisposedException message = {0}.", ode.Message); return ReportErrorAndReleasePacket(errorPacket, ode); } catch (IOException ioe) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.SNITraceEvent(" IOException message = {0}.", ioe.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" IOException message = {0}.", ioe.Message); return ReportErrorAndReleasePacket(errorPacket, ioe); } } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } public override uint Send(SNIPacket packet) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { bool releaseLock = false; @@ -297,12 +297,12 @@ public override uint Send(SNIPacket packet) } catch (ObjectDisposedException ode) { - SqlClientEventSource.Log.SNITraceEvent(" ObjectDisposedException message = {0}.", ode.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" ObjectDisposedException message = {0}.", ode.Message); return ReportErrorAndReleasePacket(packet, ode); } catch (IOException ioe) { - SqlClientEventSource.Log.SNITraceEvent(" IOException message = {0}.", ioe.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" IOException message = {0}.", ioe.Message); return ReportErrorAndReleasePacket(packet, ioe); } @@ -318,13 +318,13 @@ public override uint Send(SNIPacket packet) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = null) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { SNIAsyncCallback cb = callback ?? _sendCallback; @@ -333,7 +333,7 @@ public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = nul } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -345,7 +345,7 @@ public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyn public override uint EnableSsl(uint options) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { _validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0; @@ -356,12 +356,12 @@ public override uint EnableSsl(uint options) } catch (AuthenticationException aue) { - SqlClientEventSource.Log.SNITraceEvent(" AuthenticationException message = {0}.", aue.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" AuthenticationException message = {0}.", aue.Message); return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, aue); } catch (InvalidOperationException ioe) { - SqlClientEventSource.Log.SNITraceEvent("InvalidOperationException message = {0}.", ioe.Message); + SqlClientEventSource.Log.TrySNITraceEvent("InvalidOperationException message = {0}.", ioe.Message); return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, ioe); } _stream = _sslStream; @@ -369,7 +369,7 @@ public override uint EnableSsl(uint options) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -393,7 +393,7 @@ public override void DisableSsl() /// true if valid private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors) { - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { if (!_validateCert) @@ -405,7 +405,7 @@ private bool ValidateServerCertificate(object sender, X509Certificate cert, X509 } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SSRP.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SSRP.cs index f444236b70..e4359e2c42 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SSRP.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SSRP.cs @@ -26,7 +26,7 @@ internal static int GetPortByInstanceName(string browserHostName, string instanc { Debug.Assert(!string.IsNullOrWhiteSpace(browserHostName), "browserHostName should not be null, empty, or whitespace"); Debug.Assert(!string.IsNullOrWhiteSpace(instanceName), "instanceName should not be null, empty, or whitespace"); - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { byte[] instanceInfoRequest = CreateInstanceInfoRequest(instanceName); @@ -37,7 +37,7 @@ internal static int GetPortByInstanceName(string browserHostName, string instanc } catch (SocketException se) { - SqlClientEventSource.Log.SNITraceEvent(" SocketException Message = {0}", se.Message); + SqlClientEventSource.Log.TrySNITraceEvent(" SocketException Message = {0}", se.Message); throw new Exception(SQLMessage.SqlServerBrowserNotAccessible(), se); } @@ -61,7 +61,7 @@ internal static int GetPortByInstanceName(string browserHostName, string instanc } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } @@ -73,7 +73,7 @@ internal static int GetPortByInstanceName(string browserHostName, string instanc private static byte[] CreateInstanceInfoRequest(string instanceName) { Debug.Assert(!string.IsNullOrWhiteSpace(instanceName), "instanceName should not be null, empty, or whitespace"); - long scopeID = SqlClientEventSource.Log.SNIScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent(""); try { const byte ClntUcastInst = 0x04; @@ -88,7 +88,7 @@ private static byte[] CreateInstanceInfoRequest(string instanceName) } finally { - SqlClientEventSource.Log.SNIScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.NetCoreApp.cs index 52be62e901..bf7c1632d1 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.NetCoreApp.cs @@ -31,7 +31,7 @@ static SqlAuthenticationProviderManager() catch (ConfigurationErrorsException e) { // Don't throw an error for invalid config files - SqlClientEventSource.Log.TraceEvent("Unable to load custom SqlAuthenticationProviders or SqlClientAuthenticationProviders. ConfigurationManager failed to load due to configuration errors: {0}", e); + SqlClientEventSource.Log.TryTraceEvent("Unable to load custom SqlAuthenticationProviders or SqlClientAuthenticationProviders. ConfigurationManager failed to load due to configuration errors: {0}", e); } Instance = new SqlAuthenticationProviderManager(configurationSection); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index 75b5fb04a3..8b8f689d0c 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs @@ -553,8 +553,8 @@ private string CreateInitialQuery() private Task CreateAndExecuteInitialQueryAsync(out BulkCopySimpleResultSet result) { string TDSCommand = CreateInitialQuery(); - SqlClientEventSource.Log.TraceEvent(" Initial Query: '{0}'", TDSCommand); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryTraceEvent(" Initial Query: '{0}'", TDSCommand); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); if (executeTask == null) @@ -852,7 +852,7 @@ private string TryGetOrderHintText(HashSet destColumnNames) private Task SubmitUpdateBulkCommand(string TDSCommand) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); if (executeTask == null) @@ -2359,7 +2359,7 @@ private void CheckAndRaiseNotification() // It's also the user's chance to cause an exception. _stateObj.BcpLock = true; abortOperation = FireRowsCopiedEvent(_rowsCopied); - SqlClientEventSource.Log.TraceEvent("", "INFO"); + SqlClientEventSource.Log.TryTraceEvent(""); // In case the target connection is closed accidentally. if (ConnectionState.Open != _connection.State) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs deleted file mode 100644 index 880cd3a670..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ /dev/null @@ -1,949 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics.Tracing; -using System.Threading; - -namespace Microsoft.Data.SqlClient -{ - [EventSource(Name = "Microsoft.Data.SqlClient.EventSource")] - internal class SqlClientEventSource : EventSource - { - // Defines the singleton instance for the Resources ETW provider - internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); - - #region Event IDs - // Initialized static Scope IDs - private static long s_nextScopeId = 0; - private static long s_nextNotificationScopeId = 0; - private static long s_nextPoolerScopeId = 0; - private static long s_nextSNIScopeId = 0; - - /// - /// Defines EventId for BeginExecute (Reader, Scalar, NonQuery, XmlReader). - /// - private const int BeginExecuteEventId = 1; - - /// - /// Defines EventId for EndExecute (Reader, Scalar, NonQuery, XmlReader). - /// - private const int EndExecuteEventId = 2; - - /// - /// Defines EventId for Trace() events - /// - private const int TraceEventId = 3; - - /// - /// Defines EventId for ScopeEnter() events - /// - private const int ScopeEnterId = 4; - - /// - /// Defines EventId for ScopeLeave() events - /// - private const int ScopeExitId = 5; - - /// - /// Defines EventId for notificationScopeEnter() events - /// - private const int NotificationScopeEnterId = 6; - - /// - /// Defines EventId for notificationScopeLeave() events - /// - private const int NotificationScopeExitId = 7; - - /// - /// Defines EventId for notificationScopeTrace() events - /// - private const int NotificationTraceId = 8; - - /// - /// Defines EventId for PoolerScopeEnter() events - /// - private const int PoolerScopeEnterId = 9; - - /// - /// Defines EventId for PoolerScopeLeave() events - /// - private const int PoolerScopeExitId = 10; - - /// - /// Defines EventId for PoolerTrace() events - /// - private const int PoolerTraceId = 11; - - /// - /// Defines EventId for AdvancedTrace() events - /// - private const int AdvancedTraceId = 12; - - /// - /// Defines EventId for AdvancedScopeEnter() events - /// - private const int AdvancedScopeEnterId = 13; - - /// - /// Defines EventId for AdvancedScopeLeave() events - /// - private const int AdvancedScopeExitId = 14; - - /// - /// Defines EventId for AdvancedTraceBin() events - /// - private const int AdvancedTraceBinId = 15; - - /// - /// Defines EventId for AdvancedTraceError() events - /// - private const int AdvancedTraceErrorId = 16; - - /// - /// Defines EventId for CorrelationTrace() events - /// - private const int CorrelationTraceId = 17; - - /// - /// Defines EventId for StateDump() events - /// - private const int StateDumpEventId = 18; - - /// - /// Defines EventId for SNITrace() events - /// - private const int SNITraceEventId = 19; - - /// - /// Defines EventId for SNIEnterScope() events - /// - private const int SNIScopeEnterId = 20; - - /// - /// Defines EventId for SNIExitScope() events - /// - private const int SNIScopeExitId = 21; - #endregion - - /// - /// These represent logical groups of events that can be turned on and off independently - /// Often each task has a keyword, but where tasks are determined by subsystem, keywords - /// are determined by usefulness to end users to filter. - /// - /// Generally users don't mind extra events if they are not high volume, so grouping low - /// volume events together in a single keywords is OK (users can post-filter by task if desired) - /// - /// - /// The visibility of the enum has to be public, otherwise there will be an ArgumentException - /// on calling related WriteEvent() method. - /// - /// The Keywords class has to be a nested class. - /// Each keyword must be a power of 2. - /// - /// - /// - #region Keywords - public class Keywords - { - /// - /// Captures Start/Stop events before and after command execution. - /// - internal const EventKeywords ExecutionTrace = (EventKeywords)1; - - /// - /// Captures basic application flow trace events. - /// - internal const EventKeywords Trace = (EventKeywords)2; - - /// - /// Captures basic application scope entering and exiting events. - /// - internal const EventKeywords Scope = (EventKeywords)4; - - /// - /// Captures `SqlNotification` flow trace events. - /// - internal const EventKeywords NotificationTrace = (EventKeywords)8; - - /// - /// Captures `SqlNotification` scope entering and exiting events. - /// - internal const EventKeywords NotificationScope = (EventKeywords)16; - - /// - /// Captures connection pooling flow trace events. - /// - internal const EventKeywords PoolerTrace = (EventKeywords)32; - - /// - /// Captures connection pooling scope trace events. - /// - internal const EventKeywords PoolerScope = (EventKeywords)64; - - /// - /// Captures advanced flow trace events. - /// - internal const EventKeywords AdvancedTrace = (EventKeywords)128; - - /// - /// Captures advanced flow trace events with additional information. - /// - internal const EventKeywords AdvancedTraceBin = (EventKeywords)256; - - /// - /// Captures correlation flow trace events. - /// - internal const EventKeywords CorrelationTrace = (EventKeywords)512; - - /// - /// Captures full state dump of `SqlConnection` - /// - internal const EventKeywords StateDump = (EventKeywords)1024; - - /// - /// Captures application flow traces from Managed networking implementation - /// - internal const EventKeywords SNITrace = (EventKeywords)2048; - - /// - /// Captures scope trace events from Managed networking implementation - /// - internal const EventKeywords SNIScope = (EventKeywords)4096; - } - #endregion - - #region Tasks - /// - /// Tasks supported by SqlClient's EventSource implementation - /// - public static class Tasks - { - /// - /// Task that tracks SqlCommand execution. - /// - public const EventTask ExecuteCommand = (EventTask)1; - } - #endregion - - #region Enable/Disable Events - [NonEvent] - internal bool IsExecutionTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.ExecutionTrace); - - [NonEvent] - internal bool IsTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Trace); - - [NonEvent] - internal bool IsScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.Scope); - - [NonEvent] - internal bool IsNotificationTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationTrace); - - [NonEvent] - internal bool IsNotificationScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.NotificationScope); - - [NonEvent] - internal bool IsPoolerTraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerTrace); - - [NonEvent] - internal bool IsPoolerScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.PoolerScope); - - [NonEvent] - internal bool IsAdvancedTraceOn() => Log.IsEnabled(EventLevel.Verbose, Keywords.AdvancedTrace); - - [NonEvent] - internal bool IsCorrelationEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.CorrelationTrace); - - [NonEvent] - internal bool IsStateDumpEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.StateDump); - - [NonEvent] - internal bool IsSNITraceEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.SNITrace); - - [NonEvent] - internal bool IsSNIScopeEnabled() => Log.IsEnabled(EventLevel.Informational, Keywords.SNIScope); - #endregion - - #region overloads - //Never use event writer directly as they are not checking for enabled/disabled situations. Always use overloads. - - #region Trace - [NonEvent] - internal void TraceEvent(string message) - { - if (Log.IsTraceEnabled()) - { - Trace(message); - } - } - - [NonEvent] - internal void TraceEvent(string message, T0 args0) - { - if (Log.IsTraceEnabled()) - { - Trace(string.Format(message, args0?.ToString() ?? "Null")); - } - } - - [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1) - { - if (Log.IsTraceEnabled()) - { - Trace(string.Format(message, args0?.ToString() ?? "Null", args1?.ToString() ?? "Null")); - } - } - - [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsTraceEnabled()) - { - Trace(string.Format(message, args0, args1, args2)); - } - } - - [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsTraceEnabled()) - { - Trace(string.Format(message, args0, args1, args2, args3)); - } - } - - [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) - { - if (Log.IsTraceEnabled()) - { - Trace(string.Format(message, args0, args1, args2, args3, args4, args5)); - } - } - #endregion - - #region Scope - [NonEvent] - internal long ScopeEnterEvent(string message) - { - if (Log.IsScopeEnabled()) - { - return ScopeEnter(message); - } - return 0; - } - - [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0) - { - if (Log.IsScopeEnabled()) - { - return ScopeEnter(string.Format(message, args0)); - } - return 0; - } - - [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0, T1 args1) - { - if (Log.IsScopeEnabled()) - { - return ScopeEnter(string.Format(message, args0, args1)); - } - return 0; - } - - [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsScopeEnabled()) - { - return ScopeEnter(string.Format(message, args0, args1, args2)); - } - return 0; - } - - [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsScopeEnabled()) - { - return ScopeEnter(string.Format(message, args0, args1, args2, args3)); - } - return 0; - } - - [NonEvent] - internal void ScopeLeaveEvent(long scopeId) - { - if (Log.IsScopeEnabled()) - { - ScopeLeave(scopeId); - } - } - #endregion - - #region Notification Trace - [NonEvent] - internal void NotificationTraceEvent(string message) - { - if (Log.IsNotificationTraceEnabled()) - { - NotificationTrace(message); - } - } - - [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0) - { - if (Log.IsNotificationTraceEnabled()) - { - NotificationTrace(string.Format(message, args0)); - } - } - - [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0, T1 args1) - { - if (Log.IsNotificationTraceEnabled()) - { - NotificationTrace(string.Format(message, args0, args1)); - } - } - - [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsNotificationTraceEnabled()) - { - NotificationTrace(string.Format(message, args0, args1, args2)); - } - } - - [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsNotificationTraceEnabled()) - { - NotificationTrace(string.Format(message, args0, args1, args2, args3)); - } - } - #endregion - - #region Notification Scope - [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0) - { - if (Log.IsNotificationScopeEnabled()) - { - return NotificationScopeEnter(string.Format(message, args0)); - } - return 0; - } - - [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0, T1 args1) - { - if (Log.IsNotificationScopeEnabled()) - { - return NotificationScopeEnter(string.Format(message, args0, args1)); - } - return 0; - } - - [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsNotificationScopeEnabled()) - { - return NotificationScopeEnter(string.Format(message, args0, args1, args2)); - } - return 0; - } - - [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsNotificationScopeEnabled()) - { - return NotificationScopeEnter(string.Format(message, args0, args1, args2, args3)); - } - return 0; - } - - [NonEvent] - internal void NotificationScopeLeaveEvent(long scopeId) - { - if (Log.IsNotificationScopeEnabled()) - { - NotificationScopeLeave(scopeId); - } - } - #endregion - - #region Pooler Trace - [NonEvent] - internal void PoolerTraceEvent(string message, T0 args0) - { - if (Log.IsPoolerTraceEnabled()) - { - PoolerTrace(string.Format(message, args0)); - } - } - - [NonEvent] - internal void PoolerTraceEvent(string message, T0 args0, T1 args1) - { - if (Log.IsPoolerTraceEnabled()) - { - PoolerTrace(string.Format(message, args0, args1)); - } - } - - [NonEvent] - internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsPoolerTraceEnabled()) - { - PoolerTrace(string.Format(message, args0, args1, args2)); - } - } - - [NonEvent] - internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsPoolerTraceEnabled()) - { - PoolerTrace(string.Format(message, args0, args1, args2, args3)); - } - } - #endregion - - #region Pooler Scope - [NonEvent] - internal long PoolerScopeEnterEvent(string message, T0 args0) - { - if (Log.IsPoolerScopeEnabled()) - { - return PoolerScopeEnter(string.Format(message, args0)); - } - return 0; - } - - [NonEvent] - internal void PoolerScopeLeaveEvent(long scopeId) - { - if (Log.IsPoolerScopeEnabled()) - { - PoolerScopeLeave(scopeId); - } - } - #endregion - - #region AdvancedTrace - [NonEvent] - internal void AdvancedTraceEvent(string message) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(message); - } - } - - [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(string.Format(message, args0)); - } - } - - [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(string.Format(message, args0, args1)); - } - } - - [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(string.Format(message, args0, args1, args2)); - } - } - - [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(string.Format(message, args0, args1, args2, args3)); - } - } - - [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(string.Format(message, args0, args1, args2, args3, args4, args5)); - } - } - - [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5, T6 args6, T7 args7) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTrace(string.Format(message, args0, args1, args2, args3, args4, args5, args6, args7)); - } - } - - [NonEvent] - internal long AdvancedScopeEnterEvent(string message, T0 args0) - { - if (Log.IsAdvancedTraceOn()) - { - return AdvancedScopeEnter(string.Format(message, args0)); - } - return 0; - } - - [NonEvent] - internal void AdvanceScopeLeave(long scopeId) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedScopeLeave(scopeId); - } - } - - [NonEvent] - internal void AdvancedTraceBinEvent(string message, T0 args0, T1 args1) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTraceBin(string.Format(message, args0, args1)); - } - } - - [NonEvent] - internal void AdvancedTraceErrorEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4) - { - if (Log.IsAdvancedTraceOn()) - { - AdvancedTraceError(string.Format(message, args0, args1, args2, args3, args4)); - } - } - #endregion - - #region Correlation Trace - [NonEvent] - internal void CorrelationTraceEvent(string message, T0 args0) - { - if (Log.IsCorrelationEnabled()) - { - CorrelationTrace(string.Format(message, args0?.ToString() ?? "Null")); - } - } - - [NonEvent] - internal void CorrelationTraceEvent(string message, T0 args0, T1 args1) - { - if (Log.IsCorrelationEnabled()) - { - CorrelationTrace(string.Format(message, args0?.ToString() ?? "Null", args1?.ToString() ?? "Null")); - } - } - - [NonEvent] - internal void CorrelationTraceEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsCorrelationEnabled()) - { - CorrelationTrace(string.Format(message, args0?.ToString() ?? "Null", args1?.ToString() ?? "Null", args2?.ToString() ?? "Null")); - } - } - #endregion - - #region State Dump - [NonEvent] - internal void StateDumpEvent(string message, T0 args0, T1 args1) - { - if (Log.IsStateDumpEnabled()) - { - StateDump(string.Format(message, args0, args1)); - } - } - #endregion - - #region SNI Trace - [NonEvent] - internal void SNITraceEvent(string message) - { - if (Log.IsSNITraceEnabled()) - { - SNITrace(string.Format(message)); - } - } - - [NonEvent] - internal void SNITraceEvent(string message, T0 args0) - { - if (Log.IsSNITraceEnabled()) - { - SNITrace(string.Format(message, args0)); - } - } - - [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1) - { - if (Log.IsSNITraceEnabled()) - { - SNITrace(string.Format(message, args0, args1)); - } - } - - [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsSNITraceEnabled()) - { - SNITrace(string.Format(message, args0, args1, args2)); - } - } - - [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsSNITraceEnabled()) - { - SNITrace(string.Format(message, args0, args1, args2, args3)); - } - } - - [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4) - { - if (Log.IsSNITraceEnabled()) - { - SNITrace(string.Format(message, args0, args1, args2, args3, args4)); - } - } - #endregion - - #region SNI Scope - [NonEvent] - internal long SNIScopeEnterEvent(string message) - { - if (Log.IsSNIScopeEnabled()) - { - return SNIScopeEnter(message); - } - return 0; - } - - [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0) - { - if (Log.IsSNIScopeEnabled()) - { - return SNIScopeEnter(string.Format(message, args0)); - } - return 0; - } - - [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0, T1 args1) - { - if (Log.IsSNIScopeEnabled()) - { - return SNIScopeEnter(string.Format(message, args0, args1)); - } - return 0; - } - - [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) - { - if (Log.IsSNIScopeEnabled()) - { - return SNIScopeEnter(string.Format(message, args0, args1, args2)); - } - return 0; - } - - [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) - { - if (Log.IsSNIScopeEnabled()) - { - return SNIScopeEnter(string.Format(message, args0, args1, args2, args3)); - } - return 0; - } - - [NonEvent] - internal void SNIScopeLeaveEvent(long scopeId) - { - if (Log.IsSNIScopeEnabled()) - { - SNIScopeLeave(scopeId); - } - } - #endregion - - #endregion - - #region Write Events - [Event(BeginExecuteEventId, Keywords = Keywords.ExecutionTrace, Task = Tasks.ExecuteCommand, Opcode = EventOpcode.Start)] - internal void BeginExecute(int objectId, string dataSource, string database, string commandText) - { - if (Log.IsExecutionTraceEnabled()) - { - WriteEvent(BeginExecuteEventId, objectId, dataSource, database, commandText); - } - } - - [Event(EndExecuteEventId, Keywords = Keywords.ExecutionTrace, Task = Tasks.ExecuteCommand, Opcode = EventOpcode.Stop)] - internal void EndExecute(int objectId, int compositeState, int sqlExceptionNumber) - { - if (Log.IsExecutionTraceEnabled()) - { - WriteEvent(EndExecuteEventId, objectId, compositeState, sqlExceptionNumber); - } - } - - [Event(TraceEventId, Level = EventLevel.Informational, Keywords = Keywords.Trace)] - internal void Trace(string message) - { - WriteEvent(TraceEventId, message); - } - - [Event(ScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.Scope)] - internal long ScopeEnter(string message) - { - long scopeId = Interlocked.Increment(ref s_nextScopeId); - WriteEvent(ScopeEnterId, message); - return scopeId; - } - - [Event(ScopeExitId, Level = EventLevel.Informational, Opcode = EventOpcode.Stop, Keywords = Keywords.Scope)] - internal void ScopeLeave(long scopeId) - { - WriteEvent(ScopeExitId, scopeId); - } - - [Event(NotificationTraceId, Level = EventLevel.Informational, Keywords = Keywords.NotificationTrace)] - internal void NotificationTrace(string message) - { - WriteEvent(NotificationTraceId, message); - } - - [Event(NotificationScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.NotificationScope)] - internal long NotificationScopeEnter(string message) - { - long scopeId = Interlocked.Increment(ref s_nextNotificationScopeId); - WriteEvent(NotificationScopeEnterId, message); - return scopeId; - } - - [Event(NotificationScopeExitId, Level = EventLevel.Informational, Opcode = EventOpcode.Stop, Keywords = Keywords.NotificationScope)] - internal void NotificationScopeLeave(long scopeId) - { - WriteEvent(NotificationScopeExitId, scopeId); - } - - [Event(PoolerTraceId, Level = EventLevel.Informational, Keywords = Keywords.PoolerTrace)] - internal void PoolerTrace(string message) - { - WriteEvent(PoolerTraceId, message); - } - - [Event(PoolerScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.PoolerScope)] - internal long PoolerScopeEnter(string message) - { - long scopeId = Interlocked.Increment(ref s_nextPoolerScopeId); - WriteEvent(PoolerScopeEnterId, message); - return scopeId; - } - - [Event(PoolerScopeExitId, Level = EventLevel.Informational, Opcode = EventOpcode.Stop, Keywords = Keywords.PoolerScope)] - internal void PoolerScopeLeave(long scopeId) - { - WriteEvent(PoolerScopeExitId, scopeId); - } - - [Event(AdvancedTraceId, Level = EventLevel.Verbose, Keywords = Keywords.AdvancedTrace)] - internal void AdvancedTrace(string message) - { - WriteEvent(AdvancedTraceId, message); - } - - [Event(AdvancedScopeEnterId, Level = EventLevel.Verbose, Opcode = EventOpcode.Start, Keywords = Keywords.AdvancedTrace)] - internal long AdvancedScopeEnter(string message) - { - long scopeId = Interlocked.Increment(ref s_nextScopeId); - WriteEvent(AdvancedScopeEnterId, message); - return scopeId; - } - - [Event(AdvancedScopeExitId, Level = EventLevel.Verbose, Opcode = EventOpcode.Stop, Keywords = Keywords.AdvancedTrace)] - internal void AdvancedScopeLeave(long scopeId) - { - WriteEvent(AdvancedScopeExitId, scopeId); - } - - [Event(AdvancedTraceBinId, Level = EventLevel.Verbose, Keywords = Keywords.AdvancedTraceBin)] - internal void AdvancedTraceBin(string message) - { - WriteEvent(AdvancedTraceBinId, message); - } - - [Event(AdvancedTraceErrorId, Level = EventLevel.Error, Keywords = Keywords.AdvancedTrace)] - internal void AdvancedTraceError(string message) - { - WriteEvent(AdvancedTraceErrorId, message); - } - - [Event(CorrelationTraceId, Level = EventLevel.Informational, Keywords = Keywords.CorrelationTrace, Opcode = EventOpcode.Start)] - internal void CorrelationTrace(string message) - { - WriteEvent(CorrelationTraceId, message); - } - - [Event(StateDumpEventId, Level = EventLevel.Verbose, Keywords = Keywords.StateDump)] - internal void StateDump(string message) - { - WriteEvent(StateDumpEventId, message); - } - - [Event(SNITraceEventId, Level = EventLevel.Informational, Keywords = Keywords.SNITrace)] - internal void SNITrace(string message) - { - WriteEvent(SNITraceEventId, message); - } - - [Event(SNIScopeEnterId, Level = EventLevel.Informational, Opcode = EventOpcode.Start, Keywords = Keywords.SNIScope)] - internal long SNIScopeEnter(string message) - { - long scopeId = Interlocked.Increment(ref s_nextSNIScopeId); - WriteEvent(SNIScopeEnterId, message); - return scopeId; - } - - [Event(SNIScopeExitId, Level = EventLevel.Informational, Opcode = EventOpcode.Stop, Keywords = Keywords.SNIScope)] - internal void SNIScopeLeave(long scopeId) - { - WriteEvent(SNIScopeExitId, scopeId); - } - #endregion - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs index aeedc3a346..526459baca 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -448,9 +448,8 @@ private SqlCommand(SqlCommand from) : this() } } } - _activeConnection = value; - SqlClientEventSource.Log.TraceEvent(" {0}, {1}", ObjectID, (null != value) ? value.ObjectID : -1); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value?.ObjectID); } } @@ -484,7 +483,7 @@ public SqlNotificationRequest Notification } set { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); _sqlDep = null; _notification = value; } @@ -528,7 +527,7 @@ internal SqlStatistics Statistics throw SQL.CannotModifyPropertyAsyncOperationInProgress(); } } - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); _transaction = value; } } @@ -556,7 +555,7 @@ override public string CommandText } set { - SqlClientEventSource.Log.TraceEvent(" {0}, String Value = '{1}'", ObjectID, value); + SqlClientEventSource.Log.TryTraceEvent(" {0}, String Value = '{1}'", ObjectID, value); if (_commandText != value) { PropertyChanging(); @@ -577,7 +576,7 @@ override public int CommandTimeout } set { - SqlClientEventSource.Log.TraceEvent(" {0}, {1}", ObjectID, value); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value); if (value < 0) { throw ADP.InvalidCommandTimeout(value); @@ -610,7 +609,7 @@ override public CommandType CommandType } set { - SqlClientEventSource.Log.TraceEvent(" {0}, {1}{2}", ObjectID, (int)value, _commandType); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}{2}", ObjectID, (int)value, _commandType); if (_commandType != value) { switch (value) @@ -715,7 +714,7 @@ internal void OnStatementCompleted(int recordCount) { try { - SqlClientEventSource.Log.TraceEvent(" {0}, recordCount={1}", ObjectID, recordCount); + SqlClientEventSource.Log.TryTraceEvent(" {0}, recordCount={1}", ObjectID, recordCount); handler(this, new StatementCompletedEventArgs(recordCount)); } catch (Exception e) @@ -742,8 +741,8 @@ override public void Prepare() _pendingCancel = false; SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -807,7 +806,7 @@ override public void Prepare() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -857,7 +856,7 @@ internal void Unprepare() } _cachedMetaData = null; - SqlClientEventSource.Log.TraceEvent(" {0}, Command unprepared.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command unprepared.", ObjectID); } // Cancel is supposed to be multi-thread safe. @@ -867,8 +866,8 @@ internal void Unprepare() /// override public void Cancel() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); SqlStatistics statistics = null; try { @@ -945,7 +944,7 @@ override public void Cancel() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -983,8 +982,8 @@ override public object ExecuteScalar() SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Exception e = null; bool success = false; @@ -1013,7 +1012,7 @@ override public object ExecuteScalar() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); if (e != null) { @@ -1067,8 +1066,8 @@ override public int ExecuteNonQuery() SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Exception e = null; try { @@ -1084,7 +1083,7 @@ override public int ExecuteNonQuery() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); if (e != null) { _diagnosticListener.WriteCommandError(operationId, this, _transaction, e); @@ -1106,7 +1105,7 @@ public IAsyncResult BeginExecuteNonQuery() /// public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); return BeginExecuteNonQueryInternal(0, callback, stateObject, 0, inRetry: false); } @@ -1303,7 +1302,7 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); } } @@ -1322,7 +1321,7 @@ private void ThrowIfReconnectionHasBeenCanceled() /// public int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -1522,7 +1521,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, bo { // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as RPC.", ObjectID); SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, completion, timeout, out task, out usedCache, asyncWrite, inRetry, methodName); if (null != reader) @@ -1556,8 +1555,8 @@ public XmlReader ExecuteXmlReader() Guid operationId = _diagnosticListener.WriteCommandBefore(this, _transaction); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); int? sqlExceptionNumber = null; Exception e = null; @@ -1585,7 +1584,7 @@ public XmlReader ExecuteXmlReader() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); if (e != null) { @@ -1608,7 +1607,7 @@ public IAsyncResult BeginExecuteXmlReader() /// public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); return BeginExecuteXmlReaderInternal(CommandBehavior.SequentialAccess, callback, stateObject, 0, inRetry: false); } @@ -1731,13 +1730,13 @@ public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); } } private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -1842,14 +1841,14 @@ private XmlReader CompleteXmlReader(SqlDataReader ds, bool isAsync = false) /// public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); return BeginExecuteReaderInternal(behavior, callback, stateObject, 0, inRetry: false); } /// override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); return ExecuteReader(behavior); } @@ -1857,8 +1856,8 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) new public SqlDataReader ExecuteReader() { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1867,7 +1866,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1925,13 +1924,13 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); } } internal SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2202,16 +2201,16 @@ string endMethod } private void CreateLocalCompletionTask( - CommandBehavior behavior, - object stateObject, - int timeout, + CommandBehavior behavior, + object stateObject, + int timeout, bool usedCache, - bool asyncWrite, - TaskCompletionSource globalCompletion, - TaskCompletionSource localCompletion, + bool asyncWrite, + TaskCompletionSource globalCompletion, + TaskCompletionSource localCompletion, Func endFunc, - Func retryFunc, - string endMethod, + Func retryFunc, + string endMethod, long firstAttemptStart ) { @@ -2288,7 +2287,7 @@ long firstAttemptStart if (ShouldUseEnclaveBasedWorkflow && this.enclavePackage != null) { - EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + EnclaveSessionParameters enclaveSessionParameters = new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, enclaveSessionParameters, this.enclavePackage.EnclaveSession); } @@ -2372,7 +2371,7 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, bool is /// public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Guid operationId = _diagnosticListener.WriteCommandBefore(this, _transaction); TaskCompletionSource source = new TaskCompletionSource(); @@ -2459,7 +2458,7 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b /// new public Task ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); Guid operationId = default(Guid); if (!_parentOperationStarted) { @@ -2493,14 +2492,14 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b { context = new ExecuteReaderAsyncCallContext(); } - context.Set(this, source, registration,behavior, operationId); + context.Set(this, source, registration, behavior, operationId); Task.Factory.FromAsync( - beginMethod: s_beginExecuteReaderAsync, + beginMethod: s_beginExecuteReaderAsync, endMethod: s_endExecuteReaderAsync, state: context ).ContinueWith( - continuationAction: s_cleanupExecuteReaderAsync, + continuationAction: s_cleanupExecuteReaderAsync, TaskScheduler.Default ); } @@ -2617,7 +2616,7 @@ public Task ExecuteXmlReaderAsync() /// public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Guid operationId = _diagnosticListener.WriteCommandBefore(this, _transaction); TaskCompletionSource source = new TaskCompletionSource(); @@ -3159,7 +3158,7 @@ private Task RunExecuteNonQueryTds(string methodName, bool isAsync, int timeout, // no parameters are sent over // no data reader is returned // use this overload for "batch SQL" tds token type - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(this.CommandText, timeout, this.Notification, _stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -3613,9 +3612,9 @@ private SqlDataReader TryFetchInputParameterEncryptionInfo(int timeout, { SqlConnectionAttestationProtocol attestationProtocol = this._activeConnection.AttestationProtocol; string enclaveType = this._activeConnection.Parser.EnclaveType; - - EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); - + + EnclaveSessionParameters enclaveSessionParameters = new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + SqlEnclaveSession sqlEnclaveSession = null; EnclaveDelegate.Instance.GetEnclaveSession(attestationProtocol, enclaveType, enclaveSessionParameters, true, out sqlEnclaveSession, out customData, out customDataLength); if (sqlEnclaveSession == null) @@ -4141,7 +4140,7 @@ private void ReadDescribeEncryptionParameterResults(SqlDataReader ds, ReadOnlyDi SqlConnectionAttestationProtocol attestationProtocol = this._activeConnection.AttestationProtocol; string enclaveType = this._activeConnection.Parser.EnclaveType; - EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + EnclaveSessionParameters enclaveSessionParameters = new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.CreateEnclaveSession(attestationProtocol, enclaveType, enclaveSessionParameters, attestationInfo, enclaveAttestationParameters, customData, customDataLength); enclaveAttestationParameters = null; @@ -4256,7 +4255,7 @@ internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior if (ShouldUseEnclaveBasedWorkflow && this.enclavePackage != null) { - EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + EnclaveSessionParameters enclaveSessionParameters = new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, enclaveSessionParameters, this.enclavePackage.EnclaveSession); } @@ -4300,7 +4299,7 @@ internal SqlDataReader RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior if (ShouldUseEnclaveBasedWorkflow && this.enclavePackage != null) { - EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + EnclaveSessionParameters enclaveSessionParameters = new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); EnclaveDelegate.Instance.InvalidateEnclaveSession(this._activeConnection.AttestationProtocol, this._activeConnection.Parser.EnclaveType, enclaveSessionParameters, this.enclavePackage.EnclaveSession); } @@ -4407,7 +4406,7 @@ private void GenerateEnclavePackage() try { - EnclaveSessionParameters enclaveSessionParameters= new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); + EnclaveSessionParameters enclaveSessionParameters = new EnclaveSessionParameters(this._activeConnection.DataSource, this._activeConnection.EnclaveAttestationUrl, this._activeConnection.Database); this.enclavePackage = EnclaveDelegate.Instance.GenerateEnclavePackage(attestationProtocol, keysToBeSentToEnclave, this.CommandText, enclaveType, enclaveSessionParameters); } @@ -4511,7 +4510,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi if (returnStream) { - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); } string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior); //If the query requires enclave computations, pass the enclavepackage in the SQLBatch TDS stream @@ -4572,7 +4571,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi rpc.options = TdsEnums.RPC_NOMETADATA; if (returnStream) { - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as RPC.", ObjectID); } Debug.Assert(_rpcArrayOf1[0] == rpc); @@ -4590,7 +4589,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi optionSettings = GetSetOptionsString(cmdBehavior); if (returnStream) { - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as RPC.", ObjectID); } // turn set options ON @@ -6255,7 +6254,7 @@ private void NotifyDependency() public SqlCommand Clone() { SqlCommand clone = new SqlCommand(this); - SqlClientEventSource.Log.TraceEvent(" {0}, clone={1}", ObjectID, clone.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, clone={1}", ObjectID, clone.ObjectID); return clone; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index 18c1938401..39916feaae 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -116,7 +116,7 @@ internal int ObjectID internal void Append(SqlCommand command) { ADP.CheckArgumentNull(command, nameof(command)); - SqlClientEventSource.Log.TraceEvent(" {0}, command={1}, parameterCount={2}", ObjectID, command.ObjectID, command.Parameters.Count); + SqlClientEventSource.Log.TryTraceEvent(" {0}, command={1}, parameterCount={2}", ObjectID, command.ObjectID, command.Parameters.Count); string cmdText = command.CommandText; if (string.IsNullOrEmpty(cmdText)) { @@ -248,7 +248,7 @@ internal static void BuildStoredProcedureName(StringBuilder builder, string part internal void Clear() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); DbCommand batchCommand = BatchCommand; if (null != batchCommand) { @@ -264,7 +264,7 @@ internal void Clear() internal void Dispose() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); SqlCommand command = _batchCommand; _commandList = null; _batchCommand = null; @@ -278,7 +278,7 @@ internal void Dispose() internal int ExecuteNonQuery() { ValidateCommandBehavior(nameof(ExecuteNonQuery), CommandBehavior.Default); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { @@ -295,7 +295,7 @@ internal int ExecuteNonQuery() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs index b82137f669..c1fa77b989 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -898,7 +898,7 @@ public SqlTransaction BeginTransaction(string transactionName) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, isolationLevel={1}", ObjectID, (int)isolationLevel); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, isolationLevel={1}", ObjectID, (int)isolationLevel); try { DbTransaction transaction = BeginTransaction(isolationLevel); @@ -913,7 +913,7 @@ override protected DbTransaction BeginDbTransaction(System.Data.IsolationLevel i } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -922,7 +922,7 @@ public SqlTransaction BeginTransaction(System.Data.IsolationLevel iso, string tr { WaitForPendingReconnection(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, iso={1}, transactionName='{2}'", ObjectID, (int)iso, (string.IsNullOrEmpty(transactionName) ? "None" : transactionName)); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, iso={1}, transactionName='{2}'", ObjectID, (int)iso, transactionName); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -947,7 +947,7 @@ public SqlTransaction BeginTransaction(System.Data.IsolationLevel iso, string tr finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -956,7 +956,7 @@ public override void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1001,8 +1001,8 @@ private void CloseInnerConnection() /// public override void Close() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { ConnectionState previousState = State; @@ -1080,7 +1080,7 @@ public override void Close() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1121,8 +1121,8 @@ public override void Open() /// public void Open(SqlConnectionOverrides overrides) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this); @@ -1162,7 +1162,7 @@ public void Open(SqlConnectionOverrides overrides) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1196,7 +1196,7 @@ private async Task ReconnectAsync(int timeout) { if (ctoken.IsCancellationRequested) { - SqlClientEventSource.Log.TraceEvent(" Original ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Original ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId); return; } try @@ -1215,15 +1215,15 @@ private async Task ReconnectAsync(int timeout) { ForceNewConnection = false; } - SqlClientEventSource.Log.TraceEvent(" Reconnection succeeded. ClientConnectionID {0} -> {1}", _originalConnectionId.ToString(), ClientConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Reconnection succeeded. ClientConnectionID {0} -> {1}", _originalConnectionId, ClientConnectionId); return; } catch (SqlException e) { - SqlClientEventSource.Log.TraceEvent(" Original ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message); + SqlClientEventSource.Log.TryTraceEvent(" Original ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message); if (attempt == retryCount - 1) { - SqlClientEventSource.Log.TraceEvent(" Original ClientConnectionID {0} - give up reconnection", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Original ClientConnectionID {0} - give up reconnection", _originalConnectionId); throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) @@ -1296,7 +1296,7 @@ internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; - SqlClientEventSource.Log.TraceEvent(" Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId); _recoverySessionData = cData; if (beforeDisconnect != null) { @@ -1389,8 +1389,8 @@ private void CancelOpenAndWait() /// public override Task OpenAsync(CancellationToken cancellationToken) { - long scopeID = SqlClientEventSource.Log.PoolerScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryPoolerScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this); @@ -1410,7 +1410,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlErrorOpenConnection)) { result.Task.ContinueWith( - continuationAction: s_openAsyncComplete, + continuationAction: s_openAsyncComplete, state: operationId, // connection is passed in TaskCompletionSource async state scheduler: TaskScheduler.Default ); @@ -1467,7 +1467,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.PoolerScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryPoolerScopeLeaveEvent(scopeID); } } @@ -1525,7 +1525,7 @@ public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource retryTask) { - SqlClientEventSource.Log.TraceEvent(" {0}", _parent.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", _parent.ObjectID); _registration.Dispose(); try { @@ -1788,7 +1788,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {0}, Connection broken.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection broken.", ObjectID); Close(); } }; @@ -1797,7 +1797,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {0}, Connection broken.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection broken.", ObjectID); Close(); } } @@ -1848,7 +1848,7 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent) internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) { - SqlClientEventSource.Log.TraceEvent(" {0}, Message='{1}'", ObjectID, (null != imevent) ? imevent.Message : ""); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Message='{1}'", ObjectID, imevent.Message); SqlInfoMessageEventHandler handler = InfoMessage; if (null != handler) { @@ -1874,8 +1874,8 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) /// public static void ChangePassword(string connectionString, string newPassword) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); - SqlClientEventSource.Log.CorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(""); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); try { if (string.IsNullOrEmpty(connectionString)) @@ -1907,15 +1907,15 @@ public static void ChangePassword(string connectionString, string newPassword) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } /// public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); - SqlClientEventSource.Log.CorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(""); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); try { if (string.IsNullOrEmpty(connectionString)) @@ -1968,7 +1968,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -2011,7 +2011,7 @@ internal Task RegisterForConnectionCloseNotification(Task outerTask, ob connection.RemoveWeakReference(obj); return task; - }, + }, state: Tuple.Create(this, value), scheduler: TaskScheduler.Default ).Unwrap(); @@ -2094,7 +2094,7 @@ private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) { if (asmRef.Version != TypeSystemAssemblyVersion && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.TraceEvent(" SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version.ToString(), TypeSystemAssemblyVersion.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version, TypeSystemAssemblyVersion); } asmRef.Version = TypeSystemAssemblyVersion; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs index 0f0ce90477..42b9e7a6d1 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs @@ -182,7 +182,7 @@ override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions { connectionTimeout *= 10; } - SqlClientEventSource.Log.TraceEvent("Set connection pool CreateTimeout={0} when {1} is in use.", connectionTimeout, opt.Authentication); + SqlClientEventSource.Log.TryTraceEvent("Set connection pool CreateTimeout={0} when {1} is in use.", connectionTimeout, opt.Authentication); } poolingOptions = new DbConnectionPoolGroupOptions( opt.IntegratedSecurity, diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs index 1a6f944a6c..cf9ab34507 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionHelper.cs @@ -60,7 +60,7 @@ internal DbConnectionOptions ConnectionOptions private string ConnectionString_Get() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions connectionOptions = UserConnectionOptions; return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); @@ -86,8 +86,10 @@ private void ConnectionString_Set(DbConnectionPoolKey key) { throw ADP.OpenConnectionPropertySet(nameof(ConnectionString), connectionInternal.State); } - string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); - SqlClientEventSource.Log.TraceEvent(" {0}, '{1}'", ObjectID, cstr); + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + SqlClientEventSource.Log.TraceEvent(" {0}, '{1}'", ObjectID, connectionOptions?.UsersConnectionStringForTrace()); + } } internal DbConnectionInternal InnerConnection @@ -135,11 +137,11 @@ internal void Abort(Exception e) // will end the reliable try... if (e is OutOfMemoryException) { - SqlClientEventSource.Log.TraceEvent(" {0}, Aborting operation due to asynchronous exception: {'OutOfMemory'}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Aborting operation due to asynchronous exception: {'OutOfMemory'}", ObjectID); } else { - SqlClientEventSource.Log.TraceEvent(" {0}, Aborting operation due to asynchronous exception: {1}", ObjectID, e); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Aborting operation due to asynchronous exception: {1}", ObjectID, e); } } @@ -151,7 +153,7 @@ internal void AddWeakReference(object value, int tag) /// override protected DbCommand CreateDbCommand() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { DbCommand command = null; @@ -162,7 +164,7 @@ override protected DbCommand CreateDbCommand() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -184,7 +186,7 @@ override protected void Dispose(bool disposing) /// public override void EnlistTransaction(Transaction transaction) { - SqlClientEventSource.Log.TraceEvent(" {0}, Connection enlisting in a transaction.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection enlisting in a transaction.", ObjectID); // If we're currently enlisted in a transaction and we were called // on the EnlistTransaction method (Whidbey) we're not allowed to diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs index 874c44287f..aeaa3fd36e 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs @@ -53,7 +53,7 @@ internal void AliasCheck(string server) } else if (_alias != server) { - SqlClientEventSource.Log.TraceEvent(" alias change detected. Clearing PoolGroup"); + SqlClientEventSource.Log.TryTraceEvent(" alias change detected. Clearing PoolGroup"); base.PoolGroup.Clear(); _alias = server; } @@ -66,7 +66,7 @@ internal void FailoverCheck(SqlInternalConnection connection, bool actualUseFail { if (UseFailoverPartner != actualUseFailoverPartner) { - SqlClientEventSource.Log.TraceEvent(" Failover detected. failover partner='{0}'. Clearing PoolGroup", actualFailoverPartner); + SqlClientEventSource.Log.TryTraceEvent(" Failover detected. failover partner='{0}'. Clearing PoolGroup", actualFailoverPartner); base.PoolGroup.Clear(); _useFailoverPartner = actualUseFailoverPartner; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index 63c11bc371..3852c375b3 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -127,7 +127,7 @@ public override int UpdateBatchSize throw ADP.ArgumentOutOfRange(nameof(UpdateBatchSize)); } _updateBatchSize = value; - SqlClientEventSource.Log.TraceEvent(" {0}, {1}", ObjectID, value); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value); } } @@ -149,7 +149,7 @@ protected override void ClearBatch() protected override int ExecuteBatch() { Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); return _commandSet.ExecuteNonQuery(); } @@ -172,7 +172,7 @@ protected override bool GetBatchedRecordsAffected(int commandIdentifier, out int /// protected override void InitializeBatching() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); _commandSet = new SqlCommandSet(); SqlCommand command = SelectCommand; if (null == command) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs index dd7d898f85..83fa69a74f 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -844,7 +844,7 @@ protected override void Dispose(bool disposing) /// public override void Close() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); SqlStatistics statistics = null; try { @@ -927,7 +927,7 @@ public override void Close() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1442,7 +1442,7 @@ override public int GetProviderSpecificValues(object[] values) public override DataTable GetSchemaTable() { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1459,7 +1459,7 @@ public override DataTable GetSchemaTable() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -3243,7 +3243,7 @@ override public bool NextResult() private bool TryNextResult(out bool more) { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -3374,7 +3374,7 @@ private bool TryNextResult(out bool more) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -3404,7 +3404,7 @@ override public bool Read() private bool TryReadInternal(bool setTimeout, out bool more) { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -3557,7 +3557,7 @@ private bool TryReadInternal(bool setTimeout, out bool more) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -3935,7 +3935,7 @@ private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateO // broken connection, so check state first. if (parser.State == TdsParserState.OpenLoggedIn) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID '{1}'", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID '{1}'", ObjectID, ActivityCorrelator.Current); Task executeTask = parser.TdsExecuteSQLBatch(_resetOptionsString, (_command != null) ? _command.CommandTimeout : 0, null, stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -4240,7 +4240,7 @@ private void AssertReaderState(bool requireData, bool permitAsync, int? columnIn /// public override Task NextResultAsync(CancellationToken cancellationToken) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { TaskCompletionSource source = new TaskCompletionSource(); @@ -4281,7 +4281,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -4290,7 +4290,7 @@ private static Task NextResultAsyncExecute(Task task, object state) HasNextResultAsyncCallContext context = (HasNextResultAsyncCallContext)state; if (task != null) { - SqlClientEventSource.Log.TraceEvent(" attempt retry {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" attempt retry {0}", ObjectID); context._reader.PrepareForAsyncContinuation(); } @@ -4575,7 +4575,7 @@ out bytesRead /// public override Task ReadAsync(CancellationToken cancellationToken) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { if (IsClosed) @@ -4709,7 +4709,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs index 214076d7b0..d806dc814a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs @@ -80,13 +80,13 @@ public void Initialize() // transaction. SqlInternalConnection connection = _connection; SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, delegating transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, delegating transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try { if (connection.IsEnlistedInTransaction) { - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, was enlisted, now defecting.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, was enlisted, now defecting.", ObjectID, connection.ObjectID); // defect first connection.EnlistNull(); @@ -143,7 +143,7 @@ public byte[] Promote() if (null != connection) { SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, promoting transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, promoting transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try { @@ -215,13 +215,13 @@ public byte[] Promote() else { // The transaction was aborted externally, since it's already doomed above, we only log the same. - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, aborted during promotion.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, aborted during promotion.", ObjectID, connection.ObjectID); } } else { // The transaction was aborted externally, doom the connection to make sure it's eventually rolled back and log the same. - SqlClientEventSource.Log.TraceEvent(" {0}, Connection null, aborted before promoting.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection null, aborted before promoting.", ObjectID); } return returnValue; } @@ -235,7 +235,7 @@ public void Rollback(SinglePhaseEnlistment enlistment) if (null != connection) { SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, rolling back transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, rolling back transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try { @@ -304,7 +304,7 @@ public void Rollback(SinglePhaseEnlistment enlistment) { // The transaction was aborted, report that to SysTx and log the same. enlistment.Aborted(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection null, aborted before rollback.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection null, aborted before rollback.", ObjectID); } } @@ -317,7 +317,7 @@ public void SinglePhaseCommit(SinglePhaseEnlistment enlistment) if (null != connection) { SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, committing transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, committing transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try { @@ -421,7 +421,7 @@ public void SinglePhaseCommit(SinglePhaseEnlistment enlistment) { // The transaction was aborted before we could commit, report that to SysTx and log the same. enlistment.Aborted(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection null, aborted before commit.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection null, aborted before commit.", ObjectID); } } @@ -435,7 +435,7 @@ internal void TransactionEnded(Transaction transaction) if (connection != null) { - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, transaction completed externally.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, transaction completed externally.", ObjectID, connection.ObjectID); lock (connection) { if (_atomicTransaction.Equals(transaction)) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependency.cs index 6ed472f518..23c8ad767c 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -245,7 +245,7 @@ public SqlDependency(SqlCommand command) : this(command, null, SQL.SqlDependency /// public SqlDependency(SqlCommand command, string options, int timeout) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, options: '{1}', timeout: '{2}'", ObjectID, options, timeout); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, options: '{1}', timeout: '{2}'", ObjectID, options, timeout); try { if (timeout < 0) @@ -264,7 +264,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -294,7 +294,7 @@ public event OnChangeEventHandler OnChange // EventHandlers to be fired when dependency is notified. add { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { if (null != value) @@ -329,12 +329,12 @@ public event OnChangeEventHandler OnChange } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } remove { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { if (null != value) @@ -352,7 +352,7 @@ public event OnChangeEventHandler OnChange } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } @@ -362,7 +362,7 @@ public event OnChangeEventHandler OnChange public void AddCommandDependency(SqlCommand command) { // Adds command to dependency collection so we automatically create the SqlNotificationsRequest object - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { // and listen for a notification for the added commands. @@ -375,7 +375,7 @@ public void AddCommandDependency(SqlCommand command) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -396,7 +396,7 @@ public static bool Start(string connectionString, string queue) internal static bool Start(string connectionString, string queue, bool useDefaults) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); try { if (string.IsNullOrEmpty(connectionString)) @@ -455,7 +455,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul SqlDependencyPerAppDomainDispatcher.SingletonInstance, out errorOccurred, out appDomainStart); - SqlClientEventSource.Log.NotificationTraceEvent(" Start (defaults) returned: '{0}', with service: '{1}', server: '{2}', database: '{3}'", result, service, server, database); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Start (defaults) returned: '{0}', with service: '{1}', server: '{2}', database: '{3}'", result, service, server, database); } finally { @@ -477,7 +477,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - SqlClientEventSource.Log.NotificationTraceEvent(" Exception occurred from Stop() after duplicate was found on Start()."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception occurred from Stop() after duplicate was found on Start()."); } throw SQL.SqlDependencyDuplicateStart(); } @@ -491,7 +491,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul queue, s_appDomainKey, SqlDependencyPerAppDomainDispatcher.SingletonInstance); - SqlClientEventSource.Log.NotificationTraceEvent(" Start (user provided queue) returned: '{0}'", result); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Start (user provided queue) returned: '{0}'", result); // No need to call AddToServerDatabaseHash since if not using default queue user is required // to provide options themselves. @@ -505,7 +505,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - SqlClientEventSource.Log.NotificationTraceEvent(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); throw; } } @@ -514,7 +514,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -532,7 +532,7 @@ public static bool Stop(string connectionString, string queue) internal static bool Stop(string connectionString, string queue, bool useDefaults, bool startFailed) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); try { if (string.IsNullOrEmpty(connectionString)) @@ -628,7 +628,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -636,7 +636,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault private static bool AddToServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); try { bool result = false; @@ -647,7 +647,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!s_serverUserHash.ContainsKey(server)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Hash did not contain server, adding."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Hash did not contain server, adding."); identityDatabaseHash = new Dictionary>(); s_serverUserHash.Add(server, identityDatabaseHash); } @@ -660,7 +660,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!identityDatabaseHash.ContainsKey(identityUser)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Hash contained server but not user, adding user."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Hash contained server but not user, adding user."); databaseServiceList = new List(); identityDatabaseHash.Add(identityUser, databaseServiceList); } @@ -671,13 +671,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!databaseServiceList.Contains(databaseService)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Adding database."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Adding database."); databaseServiceList.Add(databaseService); result = true; } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash already contained server, user, and database - we will throw!."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash already contained server, user, and database - we will throw!."); } } @@ -685,13 +685,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private static void RemoveFromServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); try { lock (s_serverUserHash) @@ -711,43 +711,43 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair int index = databaseServiceList.IndexOf(databaseService); if (index >= 0) { - SqlClientEventSource.Log.NotificationTraceEvent(" Hash contained server, user, and database - removing database."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Hash contained server, user, and database - removing database."); databaseServiceList.RemoveAt(index); if (databaseServiceList.Count == 0) { - SqlClientEventSource.Log.NotificationTraceEvent(" databaseServiceList count 0, removing the list for this server and user."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" databaseServiceList count 0, removing the list for this server and user."); identityDatabaseHash.Remove(identityUser); if (identityDatabaseHash.Count == 0) { - SqlClientEventSource.Log.NotificationTraceEvent(" identityDatabaseHash count 0, removing the hash for this server."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" identityDatabaseHash count 0, removing the hash for this server."); s_serverUserHash.Remove(server); } } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash contained server and user but not database!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash contained server and user but not database!"); Debug.Fail("Unexpected state - hash did not contain database!"); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash contained server but not user!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash contained server but not user!"); Debug.Fail("Unexpected state - hash did not contain user!"); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash did not contain server!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash did not contain server!"); Debug.Fail("Unexpected state - hash did not contain server!"); } } } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -755,7 +755,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { // Server must be an exact match, but user and database only needs to match exactly if there is more than one // for the given user or database passed. That is ambiguous and we must fail. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" server: '{0}', failoverServer: '{1}', database: '{2}'", server, failoverServer, database); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" server: '{0}', failoverServer: '{1}', database: '{2}'", server, failoverServer, database); try { string result; @@ -767,17 +767,17 @@ internal static string GetDefaultComposedOptions(string server, string failoverS if (0 == s_serverUserHash.Count) { // Special error for no calls to start. - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - no start calls have been made, about to throw."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - no start calls have been made, about to throw."); throw SQL.SqlDepDefaultOptionsButNoStart(); } else if (!string.IsNullOrEmpty(failoverServer) && s_serverUserHash.ContainsKey(failoverServer)) { - SqlClientEventSource.Log.NotificationTraceEvent(" using failover server instead\n"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" using failover server instead\n"); server = failoverServer; } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - not listening to this server, about to throw."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - not listening to this server, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } } @@ -790,7 +790,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { if (identityDatabaseHash.Count > 1) { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - not listening for this user, " + + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - not listening for this user, " + "but listening to more than one other user, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } @@ -839,19 +839,19 @@ internal static string GetDefaultComposedOptions(string server, string failoverS else { // More than one database for given server, ambiguous - fail the default case! - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); throw SQL.SqlDependencyNoMatchingServerDatabaseStart(); } } } Debug.Assert(!string.IsNullOrEmpty(result), "GetDefaultComposedOptions should never return null or empty string!"); - SqlClientEventSource.Log.NotificationTraceEvent(" resulting options: '{0}'.", result); + SqlClientEventSource.Log.TryNotificationTraceEvent(" resulting options: '{0}'.", result); return result; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -861,7 +861,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS // use this list for a reverse lookup based on server. internal void AddToServerList(string server) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); try { lock (_serverList) @@ -877,7 +877,7 @@ internal void AddToServerList(string server) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -891,7 +891,7 @@ internal bool ContainsServer(string server) internal string ComputeHashAndAddToDispatcher(SqlCommand command) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, command.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, command.ObjectID); try { // Create a string representing the concatenation of the connection string, command text and .ToString on all parameter values. @@ -903,18 +903,18 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) string commandHash = ComputeCommandHash(command.Connection.ConnectionString, command); // calculate the string representation of command string idString = SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddCommandEntry(commandHash, this); // Add to map. - SqlClientEventSource.Log.NotificationTraceEvent(" computed id string: '{0}'.", idString); + SqlClientEventSource.Log.TryNotificationTraceEvent(" computed id string: '{0}'.", idString); return idString; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { List eventList = null; @@ -928,7 +928,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (ExpirationTime >= DateTime.UtcNow) { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - notification received twice - we should never enter this state!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - notification received twice - we should never enter this state!"); Debug.Fail("Received notification twice - we should never enter this state!"); } else @@ -937,7 +937,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql // raises Timeout event but before removing this event from the list. If notification is received from // server in this case, we will hit this code path. // It is safe to ignore this race condition because no event is sent to user and no leak happens. - SqlClientEventSource.Log.NotificationTraceEvent(" ignore notification received after timeout!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ignore notification received after timeout!"); } } else @@ -951,7 +951,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (eventList != null) { - SqlClientEventSource.Log.NotificationTraceEvent(" Firing events."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Firing events."); foreach (EventContextPair pair in eventList) { pair.Invoke(new SqlNotificationEventArgs(type, info, source)); @@ -960,14 +960,14 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is used by SqlCommand. internal void StartTimer(SqlNotificationRequest notificationRequest) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { if (_expirationTime == DateTime.MaxValue) @@ -989,7 +989,7 @@ internal void StartTimer(SqlNotificationRequest notificationRequest) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1000,7 +1000,7 @@ private void AddCommandInternal(SqlCommand cmd) if (cmd != null) { // Don't bother with EventSource if command null. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, cmd.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, cmd.ObjectID); try { SqlConnection connection = cmd.Connection; @@ -1010,7 +1010,7 @@ private void AddCommandInternal(SqlCommand cmd) // Fail if cmd has notification that is not already associated with this dependency. if (cmd._sqlDep == null || cmd._sqlDep != this) { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - throwing command has existing SqlNotificationRequest exception."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - throwing command has existing SqlNotificationRequest exception."); throw SQL.SqlCommandHasExistingSqlNotificationRequest(); } } @@ -1044,7 +1044,7 @@ private void AddCommandInternal(SqlCommand cmd) if (0 == _eventList.Count) { // Keep logic just in case. - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - firing events, though it is unexpected we have events at this point."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - firing events, though it is unexpected we have events at this point."); needToInvalidate = true; // Delay invalidation until outside of lock. } } @@ -1058,14 +1058,14 @@ private void AddCommandInternal(SqlCommand cmd) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } private string ComputeCommandHash(string connectionString, SqlCommand command) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, command.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, command.ObjectID); try { // Create a string representing the concatenation of the connection string, the command text and .ToString on all its parameter values. @@ -1121,12 +1121,12 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) } string result = builder.ToString(); - SqlClientEventSource.Log.NotificationTraceEvent(" ComputeCommandHash result: '{0}'.", result); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ComputeCommandHash result: '{0}'.", result); return result; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index 1b2a03cd15..3fdcdebbec 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -55,7 +55,7 @@ private class SqlConnectionContainer internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, HashHelper?.Queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, HashHelper?.Queue); bool setupCompleted = false; try { @@ -76,7 +76,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str } #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(_hashHelper.ConnectionStringBuilder.ConnectionString); - SqlClientEventSource.Log.NotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif // Always use ConnectionStringBuilder since in default case it is different from the @@ -175,7 +175,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -207,7 +207,7 @@ internal string Database // SqlDependencyProcessDispatcher.QueueAppDomainUnload on AppDomain.Unload. internal bool AppDomainUnload(string appDomainKey) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, AppDomainKey: '{1}'", ObjectID, appDomainKey); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, AppDomainKey: '{1}'", ObjectID, appDomainKey); try { Debug.Assert(!string.IsNullOrEmpty(appDomainKey), "Unexpected empty appDomainKey!"); @@ -219,9 +219,9 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { // Do nothing if AppDomain did not call Start! - SqlClientEventSource.Log.NotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}'.", appDomainKey); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}'.", appDomainKey); int value = _appDomainKeyHash[appDomainKey]; - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{0}' count: '{1}'.", appDomainKey, value); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{0}' count: '{1}'.", appDomainKey, value); Debug.Assert(value > 0, "Why is value 0 or less?"); bool ignored = false; @@ -238,26 +238,26 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{0}' entry not removed from hash. Count: {1}'", appDomainKey, _appDomainKeyHash[appDomainKey]); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{0}' entry not removed from hash. Count: {1}'", appDomainKey, _appDomainKeyHash[appDomainKey]); } } else { - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{0}'.", appDomainKey); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{0}'.", appDomainKey); } } - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{0}'.", _stopped); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{0}'.", _stopped); return _stopped; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void AsynchronouslyQueryServiceBrokerQueue() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { AsyncCallback callback = new AsyncCallback(AsyncResultCallback); @@ -265,13 +265,13 @@ private void AsynchronouslyQueryServiceBrokerQueue() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void AsyncResultCallback(IAsyncResult asyncResult) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { using (SqlDataReader reader = _com.EndExecuteReader(asyncResult)) @@ -297,7 +297,7 @@ private void AsyncResultCallback(IAsyncResult asyncResult) _errorState = true; throw; } - SqlClientEventSource.Log.NotificationTraceEvent(" Exception occurred."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception occurred."); if (!_stop) { // Only assert if not in cancel path. @@ -317,13 +317,13 @@ private void AsyncResultCallback(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void CreateQueueAndService(bool restart) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { SqlCommand com = new SqlCommand() @@ -457,18 +457,18 @@ private void CreateQueueAndService(bool restart) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { appDomainStart = false; // Reset out param. int result = Interlocked.Increment(ref _startCount); // Add to refCount. - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> {0}, incremented _startCount: {1}", s_staticInstance.ObjectID, result); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> {0}, incremented _startCount: {1}", s_staticInstance.ObjectID, result); // Dictionary used to track how many times start has been called per app domain. // For each increment, add to count, and create entry if not present. @@ -477,25 +477,25 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { _appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1; - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{0}', incremented count: '{1}'.", appDomainKey, _appDomainKeyHash[appDomainKey]); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{0}', incremented count: '{1}'.", appDomainKey, _appDomainKeyHash[appDomainKey]); } else { _appDomainKeyHash[appDomainKey] = 1; appDomainStart = true; - SqlClientEventSource.Log.NotificationTraceEvent(" _appDomainKeyHash did not contain AppDomainKey: '{0}', added to hashtable and value set to 1.", appDomainKey); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _appDomainKeyHash did not contain AppDomainKey: '{0}', added to hashtable and value set to 1.", appDomainKey); } } } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void ProcessNotificationResults(SqlDataReader reader) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); Guid handle = Guid.Empty; // Conversation_handle. Always close this! try { @@ -503,18 +503,18 @@ private void ProcessNotificationResults(SqlDataReader reader) { while (reader.Read()) { - SqlClientEventSource.Log.NotificationTraceEvent(" Row read."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Row read."); #if DEBUG if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) { for (int i = 0; i < reader.FieldCount; i++) { - SqlClientEventSource.Log.NotificationTraceEvent(" column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i).ToString()); + SqlClientEventSource.Log.NotificationTraceEvent(" column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i)); } } #endif string msgType = reader.GetString(0); - SqlClientEventSource.Log.NotificationTraceEvent(" msgType: '{0}'", msgType); + SqlClientEventSource.Log.TryNotificationTraceEvent(" msgType: '{0}'", msgType); handle = reader.GetGuid(1); // Only process QueryNotification messages. @@ -527,7 +527,7 @@ private void ProcessNotificationResults(SqlDataReader reader) if (null != notification) { string key = notification.Key; - SqlClientEventSource.Log.NotificationTraceEvent(" Key: '{0}'", key); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Key: '{0}'", key); int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash" if (index >= 0) @@ -556,31 +556,31 @@ private void ProcessNotificationResults(SqlDataReader reader) else { Debug.Fail("Received notification but do not have an associated PerAppDomainDispatcher!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Received notification but do not have an associated PerAppDomainDispatcher!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Received notification but do not have an associated PerAppDomainDispatcher!"); } } else { Debug.Fail("Unexpected ID format received!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Unexpected ID format received!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Unexpected ID format received!"); } } else { Debug.Fail("Null notification returned from ProcessMessage!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Null notification returned from ProcessMessage!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Null notification returned from ProcessMessage!"); } } else { Debug.Fail("Null payload for QN notification type!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Null payload for QN notification type!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Null payload for QN notification type!"); } } else { handle = Guid.Empty; - SqlClientEventSource.Log.NotificationTraceEvent(" Unexpected message format received!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Unexpected message format received!"); } } } @@ -608,13 +608,13 @@ private void ProcessNotificationResults(SqlDataReader reader) } Debug.Assert(_com.Parameters.Count == 2, "Unexpected number of parameters!"); } - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void Restart(object unused) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { // Unused arg required by TimerCallback. @@ -762,13 +762,13 @@ private void Restart(object unused) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } internal bool Stop(string appDomainKey, out bool appDomainStop) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { appDomainStop = false; @@ -786,7 +786,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) int value = _appDomainKeyHash[appDomainKey]; Debug.Assert(value > 0, "Unexpected count for appDomainKey"); - SqlClientEventSource.Log.NotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}', pre-decrement Count: '{1}'.", appDomainKey, value); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}', pre-decrement Count: '{1}'.", appDomainKey, value); if (value > 0) { @@ -794,7 +794,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR pre-decremented count <= 0!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR pre-decremented count <= 0!"); Debug.Fail("Unexpected AppDomainKey count in Stop()"); } @@ -806,7 +806,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR appDomainKey not null and not found in hash!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR appDomainKey not null and not found in hash!"); Debug.Fail("Unexpected state on Stop() - no AppDomainKey entry in hashtable!"); } } @@ -819,7 +819,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) { // If we've reached refCount 0, destroy. // Lock to ensure Cancel() complete prior to other thread calling TearDown. - SqlClientEventSource.Log.NotificationTraceEvent(" Reached 0 count, cancelling and waiting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Reached 0 count, cancelling and waiting."); lock (this) { @@ -862,7 +862,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) // TearDownAndDispose in the maximum retry period case as well as in the _errorState case. if (_errorState || retryStopwatch.Elapsed.Seconds >= 30) { - SqlClientEventSource.Log.NotificationTraceEvent(" forcing cleanup. elapsedSeconds: '{0}', _errorState: '{1}'.", retryStopwatch.Elapsed.Seconds, _errorState); + SqlClientEventSource.Log.TryNotificationTraceEvent(" forcing cleanup. elapsedSeconds: '{0}', _errorState: '{1}'.", retryStopwatch.Elapsed.Seconds, _errorState); Timer retryTimer = _retryTimer; _retryTimer = null; if (retryTimer != null) @@ -881,7 +881,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" _startCount not 0 after decrement. _startCount: '{0}'.", _startCount); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _startCount not 0 after decrement. _startCount: '{0}'.", _startCount); } Debug.Assert(0 <= _startCount, "Invalid start count state"); @@ -890,13 +890,13 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void SynchronouslyQueryServiceBrokerQueue() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { using (SqlDataReader reader = _com.ExecuteReader()) @@ -906,14 +906,14 @@ private void SynchronouslyQueryServiceBrokerQueue() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } [SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")] private void TearDownAndDispose() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { lock (this) @@ -981,7 +981,7 @@ private void TearDownAndDispose() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } @@ -1116,42 +1116,42 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) catch (ArgumentException e) { ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace. - SqlClientEventSource.Log.TraceEvent(" Exception thrown - Enum.Parse failed to parse the value '{0}' of the attribute '{1}'.", xmlReader.Value, xmlReader.LocalName); + SqlClientEventSource.Log.TryTraceEvent(" Exception thrown - Enum.Parse failed to parse the value '{0}' of the attribute '{1}'.", xmlReader.Value, xmlReader.LocalName); return null; } } if (MessageAttributes.All != messageAttributes) { - SqlClientEventSource.Log.TraceEvent(" Not all expected attributes in Message; messageAttributes = '{0}'.", (int)messageAttributes); + SqlClientEventSource.Log.TryTraceEvent(" Not all expected attributes in Message; messageAttributes = '{0}'.", (int)messageAttributes); return null; } // Proceed to the "Message" node. if (!xmlReader.Read()) { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Verify state after Read(). if ((XmlNodeType.Element != xmlReader.NodeType) || (0 != string.Compare(xmlReader.LocalName, MessageNode, StringComparison.OrdinalIgnoreCase))) { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Proceed to the Text Node. if (!xmlReader.Read()) { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Verify state after Read(). if (xmlReader.NodeType != XmlNodeType.Text) { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } @@ -1161,7 +1161,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the Text Node. if (!xmlMessageReader.Read()) { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } @@ -1172,7 +1172,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } } @@ -1181,7 +1181,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - SqlClientEventSource.Log.TraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; // failure } } @@ -1310,19 +1310,19 @@ public override int GetHashCode() private SqlDependencyProcessDispatcher(object dummyVariable) { Debug.Assert(null == s_staticInstance, "Real constructor called with static instance already created!"); - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); #endif _connectionContainers = new Dictionary(); _sqlDependencyPerAppDomainDispatchers = new Dictionary(); } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1331,17 +1331,17 @@ private SqlDependencyProcessDispatcher(object dummyVariable) public SqlDependencyProcessDispatcher() { // Empty constructor and object - dummy to obtain singleton. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); #endif } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1358,7 +1358,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper( out string user, string queue) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: {1}", s_staticInstance.ObjectID, queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: {1}", s_staticInstance.ObjectID, queue); try { // Force certain connection string properties to be used by SqlDependencyProcessDispatcher. @@ -1392,7 +1392,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper( } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1404,7 +1404,7 @@ public override object InitializeLifetimeService() private void Invalidate(string server, SqlNotification sqlNotification) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, server: {1}", ObjectID, server); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, server: {1}", ObjectID, server); try { Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1436,7 +1436,7 @@ private void Invalidate(string server, SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1451,7 +1451,7 @@ internal void QueueAppDomainUnloading(string appDomainKey) // This method is only called by queued work-items from the method above. private void AppDomainUnloading(object state) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { string appDomainKey = (string)state; @@ -1483,7 +1483,7 @@ private void AppDomainUnloading(object state) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1553,7 +1553,7 @@ private bool Start( bool useDefaults) { Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!"); - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: '{1}', appDomainKey: '{2}', perAppDomainDispatcher ID: '{3}'", ObjectID, queueService, appDomainKey, dispatcher.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: '{1}', appDomainKey: '{2}', perAppDomainDispatcher ID: '{3}'", ObjectID, queueService, appDomainKey, dispatcher.ObjectID); try { server = null; // Reset out params. @@ -1578,7 +1578,7 @@ private bool Start( queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - SqlClientEventSource.Log.NotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif bool started = false; @@ -1588,7 +1588,7 @@ private bool Start( { if (!_connectionContainers.ContainsKey(hashHelper)) { - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable miss, creating new container.", ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable miss, creating new container.", ObjectID); container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults); _connectionContainers.Add(hashHelper, container); started = true; @@ -1597,10 +1597,10 @@ private bool Start( else { container = _connectionContainers[hashHelper]; - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); if (container.InErrorState) { - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, container: {1} is in error state!", ObjectID, container.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, container: {1} is in error state!", ObjectID, container.ObjectID); errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start(). } else @@ -1615,14 +1615,14 @@ private bool Start( server = container.Server; database = container.Database; queueService = container.Queue; - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, default service: '{1}', server: '{2}', database: '{3}'", ObjectID, queueService, server, database); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, default service: '{1}', server: '{2}', database: '{3}'", ObjectID, queueService, server, database); } - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, started: {1}", ObjectID, started); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, started: {1}", ObjectID, started); return started; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1638,7 +1638,7 @@ internal bool Stop( string appDomainKey, out bool appDomainStop) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, queueService); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, queueService); Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!"); try { @@ -1655,7 +1655,7 @@ internal bool Stop( queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - SqlClientEventSource.Log.NotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif bool stopped = false; @@ -1665,7 +1665,7 @@ internal bool Stop( if (_connectionContainers.ContainsKey(hashHelper)) { SqlConnectionContainer container = _connectionContainers[hashHelper]; - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); server = container.Server; // Return server, database, and queue info for use by calling SqlDependency. database = container.Database; queueService = container.Queue; @@ -1678,15 +1678,15 @@ internal bool Stop( } else { - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable miss.", ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable miss.", ObjectID); } } - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, stopped: {1}", ObjectID, stopped); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, stopped: {1}", ObjectID, stopped); return stopped; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.AppDomain.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.AppDomain.cs index 65bc264f21..0ebb461cc7 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.AppDomain.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.AppDomain.cs @@ -19,7 +19,7 @@ private void SubscribeToAppDomainUnload() private void UnloadEventHandler(object sender, EventArgs e) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { // Make non-blocking call to ProcessDispatcher to ThreadPool.QueueUserWorkItem to complete @@ -31,7 +31,7 @@ private void UnloadEventHandler(object sender, EventArgs e) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs index 98f474ea2b..e4f2a4446a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs @@ -80,7 +80,7 @@ internal DependencyList(string commandHash) private SqlDependencyPerAppDomainDispatcher() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { _dependencyIdToDependencyHash = new Dictionary(); @@ -97,7 +97,7 @@ private SqlDependencyPerAppDomainDispatcher() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -113,7 +113,7 @@ public override object InitializeLifetimeService() // This method is called upon SqlDependency constructor. internal void AddDependencyEntry(SqlDependency dep) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); try { lock (_instanceLock) @@ -123,14 +123,14 @@ internal void AddDependencyEntry(SqlDependency dep) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is called upon Execute of a command associated with a SqlDependency object. internal string AddCommandEntry(string commandHash, SqlDependency dep) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, commandHash: '{1}', SqlDependency: {2}", ObjectID, commandHash, dep.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, commandHash: '{1}', SqlDependency: {2}", ObjectID, commandHash, dep.ObjectID); string notificationId = string.Empty; try { @@ -139,7 +139,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) if (!_dependencyIdToDependencyHash.ContainsKey(dep.Id)) { // Determine if depId->dep hashtable contains dependency. If not, it's been invalidated. - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency not present in depId->dep hash, must have been invalidated."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency not present in depId->dep hash, must have been invalidated."); } else { @@ -160,12 +160,12 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // join the new dependency to the list if (!dependencyList.Contains(dep)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency not present for commandHash, adding."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency not present for commandHash, adding."); dependencyList.Add(dep); } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency already present for commandHash."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency already present for commandHash."); } } else @@ -179,7 +179,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) SqlDependency.AppDomainKey, // must be first Guid.NewGuid().ToString("D", System.Globalization.CultureInfo.InvariantCulture) ); - SqlClientEventSource.Log.NotificationTraceEvent(" Creating new Dependencies list for commandHash."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Creating new Dependencies list for commandHash."); DependencyList dependencyList = new DependencyList(commandHash); dependencyList.Add(dep); @@ -196,14 +196,14 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is called by the ProcessDispatcher upon a notification for this AppDomain. internal void InvalidateCommandID(SqlNotification sqlNotification) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, sqlNotification.Key); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, sqlNotification.Key); try { List dependencyList = null; @@ -214,7 +214,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) if (null != dependencyList) { - SqlClientEventSource.Log.NotificationTraceEvent(" commandHash found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" commandHash found in hashtable."); foreach (SqlDependency dependency in dependencyList) { // Ensure we remove from process static app domain hash for dependency initiated invalidates. @@ -226,7 +226,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" commandHash NOT found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" commandHash NOT found in hashtable."); } } @@ -235,7 +235,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) // After removal from hashtables, invalidate. foreach (SqlDependency dependency in dependencyList) { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency found in commandHash dependency ArrayList - calling invalidate."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency found in commandHash dependency ArrayList - calling invalidate."); try { dependency.Invalidate(sqlNotification.Type, sqlNotification.Info, sqlNotification.Source); @@ -256,14 +256,14 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is called when a connection goes down or other unknown error occurs in the ProcessDispatcher. internal void InvalidateServer(string server, SqlNotification sqlNotification) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); try { List dependencies = new List(); @@ -310,14 +310,14 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is called by SqlCommand to enable ASP.NET scenarios - map from ID to Dependency. internal SqlDependency LookupDependencyEntry(string id) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, Key: '{1}'", ObjectID, id); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, Key: '{1}'", ObjectID, id); try { if (null == id) @@ -339,7 +339,7 @@ internal SqlDependency LookupDependencyEntry(string id) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - dependency ID mismatch - not throwing."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - dependency ID mismatch - not throwing."); } } @@ -347,21 +347,21 @@ internal SqlDependency LookupDependencyEntry(string id) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // Remove the dependency from the hashtable with the passed id. private void LookupDependencyEntryWithRemove(string id) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, id: '{1}'", ObjectID, id); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, id: '{1}'", ObjectID, id); try { lock (_instanceLock) { if (_dependencyIdToDependencyHash.ContainsKey(id)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Entry found in hashtable - removing."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entry found in hashtable - removing."); _dependencyIdToDependencyHash.Remove(id); // if there are no more dependencies then we can dispose the timer. @@ -373,20 +373,20 @@ private void LookupDependencyEntryWithRemove(string id) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Entry NOT found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entry NOT found in hashtable."); } } } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // Find and return arraylist, and remove passed hash value. private List LookupCommandEntryWithRemove(string notificationId) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, notificationId); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, notificationId); try { DependencyList entry = null; @@ -395,7 +395,7 @@ private List LookupCommandEntryWithRemove(string notificationId) { if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Entries found in hashtable - removing."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entries found in hashtable - removing."); // update the tables _notificationIdToDependenciesHash.Remove(notificationId); @@ -404,7 +404,7 @@ private List LookupCommandEntryWithRemove(string notificationId) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Entries NOT found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entries NOT found in hashtable."); } Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!"); @@ -414,14 +414,14 @@ private List LookupCommandEntryWithRemove(string notificationId) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // Remove from commandToDependenciesHash all references to the passed dependency. private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency dependency) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dependency.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dependency.ObjectID); try { lock (_instanceLock) @@ -434,7 +434,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende DependencyList dependencies = entry.Value; if (dependencies.Remove(dependency)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Removed SqlDependency: {0}, with ID: '{1}'.", dependency.ObjectID, dependency.Id); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Removed SqlDependency: {0}, with ID: '{1}'.", dependency.ObjectID, dependency.Id); if (dependencies.Count == 0) { // this dependency was the last associated with this notification ID, remove the entry @@ -461,7 +461,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -469,7 +469,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende internal void StartTimer(SqlDependency dep) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); try { // If this dependency expires sooner than the current next timeout, change @@ -480,7 +480,7 @@ internal void StartTimer(SqlDependency dep) // Enable the timer if needed (disable when empty, enable on the first addition). if (!_sqlDependencyTimeOutTimerStarted) { - SqlClientEventSource.Log.NotificationTraceEvent(" Timer not yet started, starting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Timer not yet started, starting."); _timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */); // Save this as the earlier timeout to come. @@ -489,7 +489,7 @@ internal void StartTimer(SqlDependency dep) } else if (_nextTimeout > dep.ExpirationTime) { - SqlClientEventSource.Log.NotificationTraceEvent(" Timer already started, resetting time."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Timer already started, resetting time."); // Save this as the earlier timeout to come. _nextTimeout = dep.ExpirationTime; @@ -498,13 +498,13 @@ internal void StartTimer(SqlDependency dep) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private static void TimeoutTimerCallback(object state) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" AppDomainKey: '{0}'", SqlDependency.AppDomainKey); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" AppDomainKey: '{0}'", SqlDependency.AppDomainKey); try { SqlDependency[] dependencies; @@ -516,14 +516,14 @@ private static void TimeoutTimerCallback(object state) { if (0 == SingletonInstance._dependencyIdToDependencyHash.Count) { - SqlClientEventSource.Log.NotificationTraceEvent(" No dependencies, exiting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" No dependencies, exiting."); // Nothing to check. return; } if (SingletonInstance._nextTimeout > DateTime.UtcNow) { - SqlClientEventSource.Log.NotificationTraceEvent(" No timeouts expired, exiting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" No timeouts expired, exiting."); // No dependency timed-out yet. return; @@ -594,7 +594,7 @@ private static void TimeoutTimerCallback(object state) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs index 05c1dd75b5..5d9f130578 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlError.cs @@ -28,7 +28,7 @@ internal SqlError(int infoNumber, byte errorState, byte errorClass, string serve Exception = exception; if (errorClass != 0) { - SqlClientEventSource.Log.TraceEvent(" infoNumber={0}, errorState={1}, errorClass={2}, errorMessage='{3}', procedure='{4}', lineNumber={5}", infoNumber, (int)errorState, (int)errorClass, errorMessage, procedure ?? "None", (int)lineNumber); + SqlClientEventSource.Log.TryTraceEvent(" infoNumber={0}, errorState={1}, errorClass={2}, errorMessage='{3}', procedure='{4}', lineNumber={5}", infoNumber, (int)errorState, (int)errorClass, errorMessage, procedure ?? "None", (int)lineNumber); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index fa7c78364e..8255b4d4bb 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -254,7 +254,7 @@ override protected void Deactivate() { try { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} deactivating", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} deactivating", ObjectID); SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection; if (null != referenceCollection) { @@ -334,12 +334,12 @@ protected void Enlist(Transaction tx) private void EnlistNonNull(Transaction tx) { Debug.Assert(null != tx, "null transaction?"); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transaction {1}.", ObjectID, tx.GetHashCode()); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transaction {1}.", ObjectID, tx.GetHashCode()); bool hasDelegatedTransaction = false; // Promotable transactions are only supported on Yukon // servers or newer. - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, attempting to delegate", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, attempting to delegate", ObjectID); SqlDelegatedTransaction delegatedTransaction = new SqlDelegatedTransaction(this, tx); try @@ -403,7 +403,7 @@ private void EnlistNonNull(Transaction tx) if (hasDelegatedTransaction) { this.DelegatedTransaction = delegatedTransaction; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, delegated to transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, delegated to transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); } } catch (SqlException e) @@ -433,7 +433,7 @@ private void EnlistNonNull(Transaction tx) if (!hasDelegatedTransaction) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, delegation not possible, enlisting.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, delegation not possible, enlisting.", ObjectID); byte[] cookie = null; if (_isGlobalTransaction) @@ -464,7 +464,7 @@ private void EnlistNonNull(Transaction tx) PropagateTransactionCookie(cookie); _isEnlistedInTransaction = true; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, enlisted with transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, enlisted with transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); } EnlistedTransaction = tx; // Tell the base class about our enlistment @@ -488,7 +488,7 @@ private void EnlistNonNull(Transaction tx) internal void EnlistNull() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, unenlisting.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, unenlisting.", ObjectID); // We were in a transaction, but now we are not - so send // message to server with empty transaction - confirmed proper // behavior from Sameet Agarwal @@ -506,7 +506,7 @@ internal void EnlistNull() _isEnlistedInTransaction = false; EnlistedTransaction = null; // Tell the base class about our enlistment - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, unenlisted.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, unenlisted.", ObjectID); // The EnlistTransaction above will return an TransactionEnded event, // which causes the TdsParser or SmiEventSink should to clear the diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs index 912596b55d..04debd8d09 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs @@ -530,7 +530,7 @@ internal SqlInternalConnectionTds( ThreadHasParserLockForClose = false; _parserLock.Release(); } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, constructed new TDS internal connection", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, constructed new TDS internal connection", ObjectID); } // Returns true if the Sql error is a transient. @@ -728,7 +728,7 @@ protected override void ChangeDatabaseInternal(string database) public override void Dispose() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} disposing", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} disposing", ObjectID); try { TdsParser parser = Interlocked.Exchange(ref _parser, null); // guard against multiple concurrent dispose calls -- Delegated Transactions might cause this. @@ -1176,12 +1176,12 @@ private void CompleteLogin(bool enlistOK) // ROR should not affect state of connection recovery if (_federatedAuthenticationRequested && !_federatedAuthenticationAcknowledged) { - SqlClientEventSource.Log.TraceEvent(" {0}, Server did not acknowledge the federated authentication request", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Server did not acknowledge the federated authentication request", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged); } if (_federatedAuthenticationInfoRequested && !_federatedAuthenticationInfoReceived) { - SqlClientEventSource.Log.TraceEvent(" {0}, Server never sent the requested federated authentication info", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Server never sent the requested federated authentication info", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoNotReceived); } if (!_sessionRecoveryAcknowledged) @@ -1218,7 +1218,7 @@ private void CompleteLogin(bool enlistOK) _parser.EnableMars(); _fConnectionOpen = true; // mark connection as open - SqlClientEventSource.Log.AdvancedTraceEvent(" Post-Login Phase: Server connection obtained."); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Post-Login Phase: Server connection obtained."); // for non-pooled connections, enlist in a distributed transaction // if present - and user specified to enlist @@ -1340,7 +1340,7 @@ private void Login(ServerInfo server, TimeoutTimer timeout, string newPassword, private void LoginFailure() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); // If the parser was allocated and we failed, then we must have failed on // either the Connect or Login, either way we should call Disconnect. @@ -1456,7 +1456,7 @@ private void LoginNoFailover(ServerInfo serverInfo, Debug.Assert(object.ReferenceEquals(connectionOptions, this.ConnectionOptions), "ConnectionOptions argument and property must be the same"); // consider removing the argument int routingAttempts = 0; ServerInfo originalServerInfo = serverInfo; // serverInfo may end up pointing to new object due to routing, original object is used to set CurrentDatasource - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, host={1}", ObjectID, serverInfo.UserServerName); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, host={1}", ObjectID, serverInfo.UserServerName); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. ResolveExtendedServerName(serverInfo, !redirectedUserInstance, connectionOptions); @@ -1525,7 +1525,7 @@ private void LoginNoFailover(ServerInfo serverInfo, if (RoutingInfo != null) { - SqlClientEventSource.Log.TraceEvent(" Routed to {0}", serverInfo.ExtendedServerName); + SqlClientEventSource.Log.TryTraceEvent(" Routed to {0}", serverInfo.ExtendedServerName); if (routingAttempts > 0) { throw SQL.ROR_RecursiveRoutingNotSupported(this); @@ -1611,7 +1611,7 @@ private void LoginNoFailover(ServerInfo serverInfo, // Sleep for a bit to prevent clogging the network with requests, // then update sleep interval for next iteration (max 1 second interval) - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } @@ -1675,7 +1675,7 @@ TimeoutTimer timeout ) { Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used"); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, useFailover={1}[bool], primary={2}, failover={3}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName, failoverHost ?? "null"); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, useFailover={1}[bool], primary={2}, failover={3}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName, failoverHost); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. long timeoutUnitInterval; @@ -1734,7 +1734,7 @@ TimeoutTimer timeout // Primary server may give us a different failover partner than the connection string indicates. Update it if (null != ServerProvidedFailOverPartner && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); failoverServerInfo.SetDerivedNames(string.Empty, ServerProvidedFailOverPartner); } currentServerInfo = failoverServerInfo; @@ -1764,7 +1764,7 @@ TimeoutTimer timeout // If it is read-only routing - we did not supply AppIntent=RO (it should be checked before) // If it is something else, not known yet (future server) - this client is not designed to support this. // In any case, server should not have sent the routing info. - SqlClientEventSource.Log.TraceEvent(" Routed to {0}", RoutingInfo.ServerName); + SqlClientEventSource.Log.TryTraceEvent(" Routed to {0}", RoutingInfo.ServerName); throw SQL.ROR_UnexpectedRoutingInfo(this); } break; // leave the while loop -- we've successfully connected @@ -1804,7 +1804,7 @@ TimeoutTimer timeout // the network with requests, then update sleep interval for next iteration (max 1 second interval) if (1 == attemptNumber % 2) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } @@ -1860,7 +1860,7 @@ private void AttemptOneLogin( TimeoutTimer timeout, bool withFailover = false) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); RoutingInfo = null; // forget routing information _parser._physicalStateObj.SniContext = SniContext.Snix_Connect; @@ -1962,7 +1962,7 @@ internal bool GetSessionAndReconnectIfNeeded(SqlConnection parent, int timeout = internal void BreakConnection() { var connection = Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Breaking connection.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Breaking connection.", ObjectID); DoomThisConnection(); // Mark connection as unusable, so it will be destroyed if (null != connection) { @@ -2068,7 +2068,7 @@ internal void OnEnvChange(SqlEnvChange rec) break; case TdsEnums.ENV_ROUTING: - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received routing info", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received routing info", ObjectID); if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0) { throw SQL.ROR_InvalidRoutingInfo(this); @@ -2112,7 +2112,7 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) "Credentials aren't provided for calling MSAL"); Debug.Assert(fedAuthInfo != null, "info should not be null."); Debug.Assert(_dbConnectionPoolAuthenticationContextKey == null, "_dbConnectionPoolAuthenticationContextKey should be null."); - SqlClientEventSource.Log.TraceEvent(" {0}, Generating federated authentication token", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Generating federated authentication token", ObjectID); DbConnectionPoolAuthenticationContext dbConnectionPoolAuthenticationContext = null; // We want to refresh the token without taking a lock on the context, allowed when the access token is expiring within the next 10 mins. @@ -2141,9 +2141,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // And on successful login, try to update the cache with the new token. if (contextValidity <= _dbAuthenticationContextUnLockedRefreshTimeSpan) { - SqlClientEventSource.Log.TraceEvent(" {0}, " + - "The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + - "The expiration time is {1}. Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + SqlClientEventSource.Log.TraceEvent(" {0}, " + + "The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + + "The expiration time is {1}. Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + } attemptRefreshTokenUnLocked = true; } @@ -2163,9 +2166,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // If a thread is already doing the refresh, just use the existing token in the cache and proceed. else if (contextValidity <= _dbAuthenticationContextLockedRefreshTimeSpan) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, " + - "The authentication context needs a refresh.The expiration time is {1}. " + - "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, " + + "The authentication context needs a refresh.The expiration time is {1}. " + + "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + } // Call the function which tries to acquire a lock over the authentication context before trying to update. // If the lock could not be obtained, it will return false, without attempting to fetch a new token. @@ -2179,10 +2185,10 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // Indicate in EventSource Trace that we are successful with the update. if (attemptRefreshTokenLocked) { - SqlClientEventSource.Log.TraceEvent(" {0}, The attempt to get a new access token succeeded under the locked mode.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, The attempt to get a new access token succeeded under the locked mode.", ObjectID); } } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); } } @@ -2243,14 +2249,17 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP // Else some other thread is already updating it, so just proceed forward with the existing token in the cache. if (dbConnectionPoolAuthenticationContext.LockToUpdate()) { - SqlClientEventSource.Log.TraceEvent(" {0}, " + - "Acquired the lock to update the authentication context.The expiration time is {1}. " + - "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + SqlClientEventSource.Log.TraceEvent(" {0}, " + + "Acquired the lock to update the authentication context.The expiration time is {1}. " + + "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + } authenticationContextLocked = true; } else { - SqlClientEventSource.Log.TraceEvent(" {0}, Refreshing the context is already in progress by another thread.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Refreshing the context is already in progress by another thread.", ObjectID); } if (authenticationContextLocked) @@ -2421,7 +2430,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) || _timeout.IsExpired || _timeout.MillisecondsRemaining <= sleepInterval) { - SqlClientEventSource.Log.TraceEvent(" {0}", msalException.ErrorCode); + SqlClientEventSource.Log.TryTraceEvent(" {0}", msalException.ErrorCode); // Error[0] SqlErrorCollection sqlErs = new SqlErrorCollection(); sqlErs.Add(new SqlError(0, (byte)0x00, (byte)TdsEnums.MIN_ERROR_CLASS, ConnectionOptions.DataSource, StringsHelper.GetString(Strings.SQL_MSALFailure, username, ConnectionOptions.Authentication.ToString("G")), ActiveDirectoryAuthentication.MSALGetAccessTokenFunctionName, 0)); @@ -2439,8 +2448,8 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) throw exc; } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); Thread.Sleep(sleepInterval); sleepInterval *= 2; @@ -2456,7 +2465,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) DateTime expirationTime = DateTime.FromFileTimeUtc(_fedAuthToken.expirationFileTime); _newDbConnectionPoolAuthenticationContext = new DbConnectionPoolAuthenticationContext(_fedAuthToken.accessToken, expirationTime); } - SqlClientEventSource.Log.TraceEvent(" {0}, Finished generating federated authentication token.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Finished generating federated authentication token.", ObjectID); return _fedAuthToken; } @@ -2524,10 +2533,10 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for GlobalTransactions", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for GlobalTransactions", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown version number for GlobalTransactions", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown version number for GlobalTransactions", ObjectID); throw SQL.ParsingError(); } @@ -2540,10 +2549,10 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_FEDAUTH: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for federated authentication", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for federated authentication", ObjectID); if (!_federatedAuthenticationRequested) { - SqlClientEventSource.Log.TraceEvent(" {0}, Did not request federated authentication", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Did not request federated authentication", ObjectID); throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); } @@ -2556,14 +2565,14 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // The server shouldn't have sent any additional data with the ack (like a nonce) if (data.Length != 0) { - SqlClientEventSource.Log.TraceEvent(" {0}, Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthFeatureAckContainsExtraData); } break; default: Debug.Fail("Unknown _fedAuthLibrary type"); - SqlClientEventSource.Log.TraceEvent(" {0}, Attempting to use unknown federated authentication library", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Attempting to use unknown federated authentication library", ObjectID); throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType); } _federatedAuthenticationAcknowledged = true; @@ -2582,11 +2591,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) { - SqlClientEventSource.Log.TraceEvent(" {0}, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); } else { - SqlClientEventSource.Log.TraceEvent(" {0}, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); } #endif } @@ -2595,17 +2604,17 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_TCE: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for TCE", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for TCE", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown version number for TCE", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown version number for TCE", ObjectID); throw SQL.ParsingError(ParsingErrorState.TceUnknownVersion); } byte supportedTceVersion = data[0]; if (0 == supportedTceVersion || supportedTceVersion > TdsEnums.MAX_SUPPORTED_TCE_VERSION) { - SqlClientEventSource.Log.TraceEvent(" {0}, Invalid version number for TCE", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Invalid version number for TCE", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidVersion, supportedTceVersion); } @@ -2624,32 +2633,32 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_UTF8SUPPORT: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for UTF8 support", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for UTF8 support", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown value for UTF8 support", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown value for UTF8 support", ObjectID); throw SQL.ParsingError(); } break; } case TdsEnums.FEATUREEXT_DATACLASSIFICATION: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte supportedDataClassificationVersion = data[0]; if ((0 == supportedDataClassificationVersion) || (supportedDataClassificationVersion > TdsEnums.DATA_CLASSIFICATION_VERSION_MAX_SUPPORTED)) { - SqlClientEventSource.Log.TraceEvent(" {0}, Invalid version number for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Invalid version number for DATACLASSIFICATION", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.DataClassificationInvalidVersion, supportedDataClassificationVersion); } if (data.Length != 2) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte enabled = data[1]; @@ -2659,11 +2668,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_SQLDNSCACHING: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for SQLDNSCACHING", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for SQLDNSCACHING", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown token for SQLDNSCACHING", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown token for SQLDNSCACHING", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalTransaction.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalTransaction.cs index fc3ebc5487..77030bd20e 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlInternalTransaction.cs @@ -52,7 +52,7 @@ internal SqlInternalTransaction(SqlInternalConnection innerConnection, Transacti internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction, long transactionId) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Created for connection {1}, outer transaction {2}, Type {3}", ObjectID, innerConnection.ObjectID, (null != outerTransaction) ? outerTransaction.ObjectID : -1, (int)type); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Created for connection {1}, outer transaction {2}, Type {3}", ObjectID, innerConnection.ObjectID, outerTransaction?.ObjectID, (int)type); _innerConnection = innerConnection; _transactionType = type; @@ -254,7 +254,7 @@ internal void CloseFromConnection() SqlInternalConnection innerConnection = _innerConnection; Debug.Assert(innerConnection != null, "How can we be here if the connection is null?"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Closing", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Closing", ObjectID); bool processFinallyBlock = true; try { @@ -280,7 +280,7 @@ internal void CloseFromConnection() internal void Commit() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { @@ -310,7 +310,7 @@ internal void Commit() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -339,7 +339,7 @@ internal void Dispose() private /*protected override*/ void Dispose(bool disposing) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Disposing", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Disposing", ObjectID); if (disposing) { if (null != _innerConnection) @@ -390,7 +390,7 @@ internal void InitParent(SqlTransaction transaction) internal void Rollback() { - var scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + var scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { throw SQL.ConnectionLockedForBcpEvent(); @@ -426,13 +426,13 @@ internal void Rollback() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } internal void Rollback(string transactionName) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, transactionName={1}", ObjectID, transactionName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, transactionName={1}", ObjectID, transactionName); if (_innerConnection.IsLockedForBulkCopy) { throw SQL.ConnectionLockedForBcpEvent(); @@ -462,13 +462,13 @@ internal void Rollback(string transactionName) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } internal void Save(string savePointName) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, savePointName={1}", ObjectID, savePointName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, savePointName={1}", ObjectID, savePointName); _innerConnection.ValidateConnectionForExecute(null); // ROLLBACK takes either a save point name or a transaction name. It will rollback the @@ -495,7 +495,7 @@ internal void Save(string savePointName) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlTransaction.cs index 4a936b4c7c..620b56917e 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -141,8 +141,8 @@ override public void Commit() ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -172,7 +172,7 @@ override public void Commit() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); if (e != null) { s_diagnosticListener.WriteTransactionCommitError(operationId, _isolationLevel, _connection, InternalTransaction, e); @@ -208,7 +208,7 @@ override public void Rollback() if (IsYukonPartialZombie) { // Put something in the trace in case a customer has an issue - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} partial zombie no rollback required", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} partial zombie no rollback required", ObjectID); _internalTransaction = null; // yukon zombification } else @@ -216,8 +216,8 @@ override public void Rollback() ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -234,7 +234,7 @@ override public void Rollback() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); if (e != null) { s_diagnosticListener.WriteTransactionRollbackError(operationId, _isolationLevel, _connection, InternalTransaction, e); @@ -255,7 +255,7 @@ public void Rollback(string transactionName) Guid operationId = s_diagnosticListener.WriteTransactionRollbackBefore(_isolationLevel, _connection, InternalTransaction, transactionName); ZombieCheck(); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} transactionName='{1}'", ObjectID, transactionName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} transactionName='{1}'", ObjectID, transactionName); SqlStatistics statistics = null; try { @@ -273,7 +273,7 @@ public void Rollback(string transactionName) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); if (e != null) { s_diagnosticListener.WriteTransactionRollbackError(operationId, _isolationLevel, _connection, InternalTransaction, e, transactionName); @@ -294,7 +294,7 @@ public void Save(string savePointName) ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} savePointName='{1}'", ObjectID, savePointName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} savePointName='{1}'", ObjectID, savePointName); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -304,7 +304,7 @@ public void Save(string savePointName) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -322,7 +322,7 @@ internal void Zombie() SqlInternalConnection internalConnection = (_connection.InnerConnection as SqlInternalConnection); if (null != internalConnection && !_isFromAPI) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} yukon deferred zombie", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} yukon deferred zombie", ObjectID); } else { diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs index 50f012d574..230509be7f 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -383,25 +383,25 @@ internal void Connect( switch (authType) { case SqlAuthenticationMethod.ActiveDirectoryPassword: - SqlClientEventSource.Log.TraceEvent(" Active Directory Password authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Password authentication"); break; case SqlAuthenticationMethod.ActiveDirectoryIntegrated: - SqlClientEventSource.Log.TraceEvent(" Active Directory Integrated authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Integrated authentication"); break; case SqlAuthenticationMethod.ActiveDirectoryInteractive: - SqlClientEventSource.Log.TraceEvent(" Active Directory Interactive authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Interactive authentication"); break; case SqlAuthenticationMethod.ActiveDirectoryServicePrincipal: - SqlClientEventSource.Log.TraceEvent(" Active Directory Service Principal authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Service Principal authentication"); break; case SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow: - SqlClientEventSource.Log.TraceEvent(" Active Directory Device Code Flow authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Device Code Flow authentication"); break; case SqlAuthenticationMethod.SqlPassword: - SqlClientEventSource.Log.TraceEvent(" SQL Password authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" SQL Password authentication"); break; default: - SqlClientEventSource.Log.TraceEvent(" SQL authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" SQL authentication"); break; } } @@ -412,7 +412,7 @@ internal void Connect( if (integratedSecurity || authType == SqlAuthenticationMethod.ActiveDirectoryIntegrated) { LoadSSPILibrary(); - SqlClientEventSource.Log.TraceEvent(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication"); } byte[] instanceName = null; @@ -446,7 +446,7 @@ internal void Connect( // don't, the memory for the connection object might not be accurate and thus // a bad error could be returned (as it was when it was freed to early for me). _physicalStateObj.Dispose(); - SqlClientEventSource.Log.TraceEvent(" Login failure", "ERR|SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Login failure"); ThrowExceptionAndWarning(_physicalStateObj); Debug.Fail("SNI returned status != success, but no error thrown?"); } @@ -481,19 +481,19 @@ internal void Connect( _physicalStateObj.AssignPendingDNSInfo(serverInfo.UserProtocol, FQDNforDNSCahce, ref _connHandler.pendingSQLDNSObject); } - SqlClientEventSource.Log.TraceEvent(" Sending prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending prelogin handshake"); SendPreLoginHandshake(instanceName, encrypt); _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake); _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake); _physicalStateObj.SniContext = SniContext.Snix_PreLogin; - SqlClientEventSource.Log.TraceEvent(" Consuming prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Consuming prelogin handshake"); PreLoginHandshakeStatus status = ConsumePreLoginHandshake(encrypt, trustServerCert, integratedSecurity, out marsCapable, out _connHandler._fedAuthRequired); if (status == PreLoginHandshakeStatus.InstanceFailure) { - SqlClientEventSource.Log.TraceEvent(" Prelogin handshake unsuccessful. Reattempting prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Prelogin handshake unsuccessful. Reattempting prelogin handshake"); _physicalStateObj.Dispose(); // Close previous connection // On Instance failure re-connect and flush SNI named instance cache. @@ -504,14 +504,14 @@ internal void Connect( if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); - SqlClientEventSource.Log.TraceEvent(" Login failure", "ERR|SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Login failure"); ThrowExceptionAndWarning(_physicalStateObj); } uint retCode = _physicalStateObj.SniGetConnectionId(ref _connHandler._clientConnectionId); Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); - SqlClientEventSource.Log.TraceEvent(" Sending prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending prelogin handshake"); if (null == _connHandler.pendingSQLDNSObject) { @@ -526,7 +526,7 @@ internal void Connect( // one pre-login packet and know we are connecting to Shiloh. if (status == PreLoginHandshakeStatus.InstanceFailure) { - SqlClientEventSource.Log.TraceEvent(" Prelogin handshake unsuccessful. Login failure", "ERR|SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Prelogin handshake unsuccessful. Login failure"); throw SQL.InstanceFailure(); } } @@ -587,7 +587,7 @@ internal void EnableMars() internal TdsParserStateObject CreateSession() { TdsParserStateObject session = TdsParserStateObjectFactory.Singleton.CreateSessionObject(this, _pMarsPhysicalConObj, true); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} created session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} created session {1}", ObjectID, session.ObjectID); return session; } @@ -599,12 +599,12 @@ internal TdsParserStateObject GetSession(object owner) session = _sessionPool.GetSession(owner); Debug.Assert(!session.HasPendingData, "pending data on a pooled MARS session"); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} getting session {1} from pool", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} getting session {1} from pool", ObjectID, session.ObjectID); } else { session = _physicalStateObj; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} getting physical session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} getting physical session {1}", ObjectID, session.ObjectID); } Debug.Assert(session._outputPacketNumber == 1, "The packet number is expected to be 1"); return session; @@ -764,7 +764,7 @@ private void SendPreLoginHandshake(byte[] instanceName, bool encrypt) int actIdSize = GUID_SIZE + sizeof(uint); offset += actIdSize; optionDataSize += actIdSize; - SqlClientEventSource.Log.TraceEvent(" ClientConnectionID {0}, ActivityID {1}", _connHandler._clientConnectionId.ToString(), actId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" ClientConnectionID {0}, ActivityID {1}", _connHandler?._clientConnectionId, actId); break; case (int)PreLoginOptions.FEDAUTHREQUIRED: @@ -1005,7 +1005,7 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(bool encrypt, bool trus // Only 0x00 and 0x01 are accepted values from the server. if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01) { - SqlClientEventSource.Log.TraceEvent(" {0}, " + + SqlClientEventSource.Log.TryTraceEvent(" {0}, " + "Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {1}.", ObjectID, (int)payload[payloadOffset]); throw SQL.ParsingErrorValue(ParsingErrorState.FedAuthRequiredPreLoginResponseInvalidValue, (int)payload[payloadOffset]); } @@ -1046,7 +1046,7 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(bool encrypt, bool trus internal void Deactivate(bool connectionIsDoomed) { // Called when the connection that owns us is deactivated. - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} deactivating", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} deactivating", ObjectID); if (SqlClientEventSource.Log.IsStateDumpEnabled()) { SqlClientEventSource.Log.StateDumpEvent(" {0} {1}", ObjectID, TraceString()); @@ -1206,11 +1206,12 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle // be copied to the end of the error collection so that the user may see all the errors and also the // warnings that occurred. // can be deleted) + //_errorAndWarningsLock lock is implemented inside GetFullErrorAndWarningCollection SqlErrorCollection temp = stateObj.GetFullErrorAndWarningCollection(out breakConnection); if (temp.Count == 0) { - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {0}", ObjectID); } Debug.Assert(temp != null, "TdsParser::ThrowExceptionAndWarning: null errors collection!"); Debug.Assert(temp.Count > 0, "TdsParser::ThrowExceptionAndWarning called with no exceptions or warnings!"); @@ -1252,7 +1253,6 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle } } - // call OnError outside of _ErrorCollectionLock to avoid deadlock if (exception != null) { if (breakConnection) @@ -1317,13 +1317,13 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle internal SqlError ProcessSNIError(TdsParserStateObject stateObj) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(""); try { #if DEBUG // There is an exception here for MARS as its possible that another thread has closed the connection just as we see an error Debug.Assert(SniContext.Undefined != stateObj.DebugOnlyCopyOfSniContext || ((_fMARS) && ((_state == TdsParserState.Closed) || (_state == TdsParserState.Broken))), "SniContext must not be None"); - SqlClientEventSource.Log.SNITraceEvent(" SNIContext must not be None = {0}, _fMARS = {1}, TDS Parser State = {2}", stateObj.DebugOnlyCopyOfSniContext, _fMARS, _state); + SqlClientEventSource.Log.TrySNITraceEvent(" SNIContext must not be None = {0}, _fMARS = {1}, TDS Parser State = {2}", stateObj.DebugOnlyCopyOfSniContext, _fMARS, _state); #endif SNIErrorDetails details = GetSniErrorDetails(); @@ -1335,17 +1335,17 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) { case (int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithMoreThan64IPs: // Connecting with the MultiSubnetFailover connection option to a SQL Server instance configured with more than 64 IP addresses is not supported. - SqlClientEventSource.Log.AdvancedTraceEvent(" Connecting with the MultiSubnetFailover connection option to a SQL Server instance configured with more than 64 IP addresses is not supported."); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Connecting with the MultiSubnetFailover connection option to a SQL Server instance configured with more than 64 IP addresses is not supported."); throw SQL.MultiSubnetFailoverWithMoreThan64IPs(); case (int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithInstanceSpecified: // Connecting to a named SQL Server instance using the MultiSubnetFailover connection option is not supported. - SqlClientEventSource.Log.AdvancedTraceEvent(" Connecting to a named SQL Server instance using the MultiSubnetFailover connection option is not supported."); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Connecting to a named SQL Server instance using the MultiSubnetFailover connection option is not supported."); throw SQL.MultiSubnetFailoverWithInstanceSpecified(); case (int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithNonTcpProtocol: // Connecting to a SQL Server instance using the MultiSubnetFailover connection option is only supported when using the TCP protocol. - SqlClientEventSource.Log.AdvancedTraceEvent(" Connecting to a SQL Server instance using the MultiSubnetFailover connection option is only supported when using the TCP protocol."); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Connecting to a SQL Server instance using the MultiSubnetFailover connection option is only supported when using the TCP protocol."); throw SQL.MultiSubnetFailoverWithNonTcpProtocol(); // continue building SqlError instance } @@ -1353,7 +1353,7 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) // PInvoke code automatically sets the length of the string for us // So no need to look for \0 string errorMessage = details.errorMessage; - SqlClientEventSource.Log.AdvancedTraceEvent("< sc.TdsParser.ProcessSNIError |ERR|ADV > Error message Detail: {0}", details.errorMessage); + SqlClientEventSource.Log.TryAdvancedTraceEvent("< sc.TdsParser.ProcessSNIError |ERR|ADV > Error message Detail: {0}", details.errorMessage); /* Format SNI errors and add Context Information * @@ -1371,12 +1371,12 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) if (TdsParserStateObjectFactory.UseManagedSNI) { Debug.Assert(!string.IsNullOrEmpty(details.errorMessage) || details.sniErrorNumber != 0, "Empty error message received from SNI"); - SqlClientEventSource.Log.AdvancedTraceEvent(" Empty error message received from SNI. Error Message = {0}, SNI Error Number ={1}", details.errorMessage, details.sniErrorNumber); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Empty error message received from SNI. Error Message = {0}, SNI Error Number ={1}", details.errorMessage, details.sniErrorNumber); } else { Debug.Assert(!string.IsNullOrEmpty(details.errorMessage), "Empty error message received from SNI"); - SqlClientEventSource.Log.AdvancedTraceEvent(" Empty error message received from SNI. Error Message = {0}", details.errorMessage); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Empty error message received from SNI. Error Message = {0}", details.errorMessage); } string sniContextEnumName = TdsEnums.GetSniContextEnumName(stateObj.SniContext); @@ -1386,7 +1386,7 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) string providerName = StringsHelper.GetResourceString(providerRid); Debug.Assert(!string.IsNullOrEmpty(providerName), $"invalid providerResourceId '{providerRid}'"); uint win32ErrorCode = details.nativeError; - SqlClientEventSource.Log.AdvancedTraceEvent(" SNI Native Error Code = {0}", win32ErrorCode); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" SNI Native Error Code = {0}", win32ErrorCode); if (details.sniErrorNumber == 0) { // Provider error. The message from provider is preceeded with non-localizable info from SNI @@ -1394,9 +1394,9 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) // int iColon = errorMessage.IndexOf(':'); Debug.Assert(0 <= iColon, "':' character missing in sni errorMessage"); - SqlClientEventSource.Log.AdvancedTraceEvent(" ':' character missing in sni errorMessage. Error Message index of ':' = {0}", iColon); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" ':' character missing in sni errorMessage. Error Message index of ':' = {0}", iColon); Debug.Assert(errorMessage.Length > iColon + 1 && errorMessage[iColon + 1] == ' ', "Expecting a space after the ':' character"); - SqlClientEventSource.Log.AdvancedTraceEvent(" Expecting a space after the ':' character. Error Message Length = {0}", errorMessage.Length); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Expecting a space after the ':' character. Error Message Length = {0}", errorMessage.Length); // extract the message excluding the colon and trailing cr/lf chars if (0 <= iColon) { @@ -1445,7 +1445,7 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) errorMessage = string.Format("{0} (provider: {1}, error: {2} - {3})", sqlContextInfo, providerName, (int)details.sniErrorNumber, errorMessage); - SqlClientEventSource.Log.AdvancedTraceErrorEvent(" SNI Error Message. Native Error = {0}, Line Number ={1}, Function ={2}, Exception ={3}, Server = {4}", + SqlClientEventSource.Log.TryAdvancedTraceErrorEvent(" SNI Error Message. Native Error = {0}, Line Number ={1}, Function ={2}, Exception ={3}, Server = {4}", (int)details.nativeError, (int)details.lineNumber, details.function, details.exception, _server); return new SqlError((int)details.nativeError, 0x00, TdsEnums.FATAL_ERROR_CLASS, @@ -1453,7 +1453,7 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1930,7 +1930,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead Debug.Fail($"unexpected token; token = {token,-2:X2}"); _state = TdsParserState.Broken; _connHandler.BreakConnection(); - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, unexpected TDS token found {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, unexpected TDS token found {0}", ObjectID); throw SQL.ParsingError(); } @@ -2254,7 +2254,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead } case TdsEnums.SQLLOGINACK: { - SqlClientEventSource.Log.TraceEvent(" Received login acknowledgement token", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Received login acknowledgement token"); SqlLoginAck ack; if (!TryProcessLoginAck(stateObj, out ack)) { @@ -3680,11 +3680,11 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, SqlFedAuthInfo tempFedAuthInfo = new SqlFedAuthInfo(); // Skip reading token length, since it has already been read in caller - SqlClientEventSource.Log.AdvancedTraceEvent(" FEDAUTHINFO token stream length = {0}", tokenLen); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" FEDAUTHINFO token stream length = {0}", tokenLen); if (tokenLen < sizeof(uint)) { // the token must at least contain a DWORD indicating the number of info IDs - SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); + SqlClientEventSource.Log.TryTraceEvent(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen); } @@ -3692,22 +3692,27 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, uint optionsCount; if (!stateObj.TryReadUInt32(out optionsCount)) { - SqlClientEventSource.Log.TraceEvent(" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream."); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadCountOfInfoIds); } tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount - SqlClientEventSource.Log.AdvancedTraceEvent(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); + } if (tokenLen > 0) { // read the rest of the token byte[] tokenData = new byte[tokenLen]; int totalRead = 0; bool successfulRead = stateObj.TryReadByteArray(tokenData, tokenLen, out totalRead); - SqlClientEventSource.Log.AdvancedTraceEvent(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); - + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); + } if (!successfulRead || totalRead != tokenLen) { - SqlClientEventSource.Log.TraceEvent(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}", tokenLen, totalRead); + SqlClientEventSource.Log.TryTraceEvent(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}", tokenLen, totalRead); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadTokenStream); } @@ -3728,7 +3733,10 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, byte id = tokenData[currentOptionOffset]; uint dataLen = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 1))); uint dataOffset = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 5))); - SqlClientEventSource.Log.AdvancedTraceEvent(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture)); + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture)); + } // offset is measured from optCount, so subtract to make offset measured // from the beginning of tokenData @@ -3740,7 +3748,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, // if dataOffset points to a region within FedAuthInfoOpt or after the end of the token, throw if (dataOffset < totalOptionsSize || dataOffset >= tokenLen) { - SqlClientEventSource.Log.TraceEvent(" FedAuthInfoDataOffset points to an invalid location.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FedAuthInfoDataOffset points to an invalid location."); throw SQL.ParsingErrorOffset(ParsingErrorState.FedAuthInfoInvalidOffset, unchecked((int)dataOffset)); } @@ -3752,15 +3760,15 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } catch (ArgumentOutOfRangeException e) { - SqlClientEventSource.Log.TraceEvent(" Failed to read FedAuthInfoData.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" Failed to read FedAuthInfoData."); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadData, e); } catch (ArgumentException e) { - SqlClientEventSource.Log.TraceEvent(" FedAuthInfoData is not in unicode format.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FedAuthInfoData is not in unicode format."); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e); } - SqlClientEventSource.Log.AdvancedTraceEvent(" FedAuthInfoData: {0}", data); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" FedAuthInfoData: {0}", data); // store data in tempFedAuthInfo switch ((TdsEnums.FedAuthInfoId)id) @@ -3774,22 +3782,22 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, break; default: - SqlClientEventSource.Log.AdvancedTraceEvent(" Ignoring unknown federated authentication info option: {0}", id); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Ignoring unknown federated authentication info option: {0}", id); break; } } } else { - SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream is not long enough to contain the data it claims to.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FEDAUTHINFO token stream is not long enough to contain the data it claims to."); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForData, tokenLen); } - SqlClientEventSource.Log.TraceEvent(" Processed FEDAUTHINFO token stream: {0}", tempFedAuthInfo.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Processed FEDAUTHINFO token stream: {0}", tempFedAuthInfo); if (string.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || string.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) { // We should be receiving both stsurl and spn - SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream does not contain both STSURL and SPN.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FEDAUTHINFO token stream does not contain both STSURL and SPN."); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDoesNotContainStsurlAndSpn); } @@ -4156,7 +4164,7 @@ internal bool TryProcessTceCryptoMetadata(TdsParserStateObject stateObj, // validate the index (ordinal passed) if (index >= cipherTable.Value.Size) { - SqlClientEventSource.Log.TraceEvent(" Incorrect ordinal received {0}, max tab size: {1}", index, cipherTable.Value.Size); + SqlClientEventSource.Log.TryTraceEvent(" Incorrect ordinal received {0}, max tab size: {1}", index, cipherTable.Value.Size); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidOrdinalIntoCipherInfoTable, index); } } @@ -8133,7 +8141,7 @@ internal void TdsLogin(SqlLogin rec, TdsEnums.FeatureExtension requestedFeatures } WriteInt(log7Flags, _physicalStateObj); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, TDS Login7 flags = {1}:", ObjectID, log7Flags); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, TDS Login7 flags = {1}:", ObjectID, log7Flags); WriteInt(0, _physicalStateObj); // ClientTimeZone is not used WriteInt(0, _physicalStateObj); // LCID is unused by server @@ -8253,7 +8261,7 @@ internal void TdsLogin(SqlLogin rec, TdsEnums.FeatureExtension requestedFeatures { if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) { - SqlClientEventSource.Log.TraceEvent(" Sending federated authentication feature request", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending federated authentication feature request"); } WriteInt(feOffset, _physicalStateObj); @@ -8288,7 +8296,7 @@ internal void TdsLogin(SqlLogin rec, TdsEnums.FeatureExtension requestedFeatures } if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) { - SqlClientEventSource.Log.TraceEvent(" Sending federated authentication feature request", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending federated authentication feature request"); Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null."); WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true); } @@ -8348,7 +8356,7 @@ internal void SendFedAuthToken(SqlFedAuthToken fedAuthToken) { Debug.Assert(fedAuthToken != null, "fedAuthToken cannot be null"); Debug.Assert(fedAuthToken.accessToken != null, "fedAuthToken.accessToken cannot be null"); - SqlClientEventSource.Log.TraceEvent(" Sending federated authentication token", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending federated authentication token"); _physicalStateObj._outputMessageType = TdsEnums.MT_FEDAUTH; byte[] accessToken = fedAuthToken.accessToken; @@ -8721,7 +8729,7 @@ internal SqlDataReader TdsExecuteTransactionManagerRequest( internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) { int old_outputPacketNumber = stateObj._outputPacketNumber; - SqlClientEventSource.Log.TraceEvent(" Exception caught on ExecuteXXX: '{0}'", e.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Exception caught on ExecuteXXX: '{0}'", e); if (stateObj.HasOpenResult) { // Need to decrement openResultCount if operation failed. @@ -8752,7 +8760,7 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) // Reset the ThreadHasParserLock value in case our caller expects it to be set\not set _connHandler.ThreadHasParserLockForClose = originalThreadHasParserLock; } - SqlClientEventSource.Log.TraceEvent(" Exception rethrown.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" Exception rethrown."); } } @@ -8810,7 +8818,7 @@ internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationReques if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); } stateObj.SniContext = SniContext.Snix_Execute; @@ -8939,7 +8947,7 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); } stateObj.SniContext = SniContext.Snix_Execute; @@ -9764,7 +9772,7 @@ private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefa if (advancedTraceIsOn) { var sendDefaultValue = sendDefault ? 1 : 0; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); } // @@ -10804,7 +10812,7 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio Debug.Assert(ushort.MaxValue >= service.Length, "Service length is out of range"); Debug.Assert(-1 <= timeout, "Timeout"); - SqlClientEventSource.Log.NotificationTraceEvent(" NotificationRequest: userData: '{0}', options: '{1}', timeout: '{2}'", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); + SqlClientEventSource.Log.TryNotificationTraceEvent(" NotificationRequest: userData: '{0}', options: '{1}', timeout: '{2}'", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj); // Query notifications Type WriteShort(callbackId.Length * 2, stateObj); // Length in bytes @@ -10829,7 +10837,7 @@ private void WriteTraceHeaderData(TdsParserStateObject stateObj) stateObj.WriteByteArray(actId.Id.ToByteArray(), GUID_SIZE, 0); // Id (Guid) WriteUnsignedInt(actId.Sequence, stateObj); // sequence number - SqlClientEventSource.Log.TraceEvent(" ActivityID {0}", actId); + SqlClientEventSource.Log.TryTraceEvent(" ActivityID {0}", actId); } private void WriteRPCBatchHeaders(TdsParserStateObject stateObj, SqlNotificationRequest notificationRequest) diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index 7de3dad2b5..f89086384b 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -36,7 +36,7 @@ internal TdsParserSessionPool(TdsParser parser) _cache = new List(); _freeStateObjects = new TdsParserStateObject[MaxInactiveCount]; _freeStateObjectCount = 0; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} created session pool for parser {1}", ObjectID, parser.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} created session pool for parser {1}", ObjectID, parser.ObjectID); } private bool IsDisposed @@ -60,7 +60,7 @@ internal void Deactivate() // When being deactivated, we check all the sessions in the // cache to make sure they're cleaned up and then we dispose of // sessions that are past what we want to keep around. - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} deactivating cachedCount={1}", ObjectID, _cachedCount); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} deactivating cachedCount={1}", ObjectID, _cachedCount); try { lock (_cache) @@ -79,7 +79,7 @@ internal void Deactivate() if (session.IsOrphaned) { // TODO: consider adding a performance counter for the number of sessions we reclaim - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} reclaiming session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} reclaiming session {1}", ObjectID, session.ObjectID); PutSession(session); } } @@ -90,13 +90,13 @@ internal void Deactivate() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } internal void Dispose() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} disposing cachedCount={1}", ObjectID, _cachedCount); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} disposing cachedCount={1}", ObjectID, _cachedCount); lock (_cache) { // Dispose free sessions @@ -154,7 +154,7 @@ internal TdsParserStateObject GetSession(object owner) { // No free objects, create a new one session = _parser.CreateSession(); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} adding session {1} to pool", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} adding session {1} to pool", ObjectID, session.ObjectID); _cache.Add(session); _cachedCount = _cache.Count; @@ -163,7 +163,7 @@ internal TdsParserStateObject GetSession(object owner) session.Activate(owner); } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} using session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} using session {1}", ObjectID, session.ObjectID); return session; } @@ -185,7 +185,7 @@ internal void PutSession(TdsParserStateObject session) else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount)) { // Session is good to re-use and our cache has space - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} keeping session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} keeping session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); Debug.Assert(!session.HasPendingData, "pending data on a pooled session?"); _freeStateObjects[_freeStateObjectCount] = session; @@ -194,7 +194,7 @@ internal void PutSession(TdsParserStateObject session) else { // Either the session is bad, or we have no cache space - so dispose the session and remove it - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} disposing session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} disposing session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); bool removed = _cache.Remove(session); Debug.Assert(removed, "session not in pool?"); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index 78bdda5c7c..a5e84c2a6a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -542,8 +542,8 @@ internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount) return false; } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount); - SqlClientEventSource.Log.AdvancedTraceBinEvent(" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount); + SqlClientEventSource.Log.TryAdvancedTraceBinEvent(" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); return true; } @@ -873,7 +873,7 @@ internal void DecrementOpenResultCount() internal int DecrementPendingCallbacks(bool release) { int remaining = Interlocked.Decrement(ref _pendingCallbacks); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); FreeGcHandle(remaining, release); // NOTE: TdsParserSessionPool may call DecrementPendingCallbacks on a TdsParserStateObject which is already disposed // This is not dangerous (since the stateObj is no longer in use), but we need to add a workaround in the assert for it @@ -926,7 +926,7 @@ internal int IncrementAndObtainOpenResultCount(SqlInternalTransaction transactio internal int IncrementPendingCallbacks() { int remaining = Interlocked.Increment(ref _pendingCallbacks); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}"); return remaining; } @@ -2534,7 +2534,7 @@ internal bool IsConnectionAlive(bool throwOnException) if ((error != TdsEnums.SNI_SUCCESS) && (error != TdsEnums.SNI_WAIT_TIMEOUT)) { // Connection is dead - SqlClientEventSource.Log.TraceEvent(" received error {0} on idle connection", (int)error); + SqlClientEventSource.Log.TryTraceEvent(" received error {0} on idle connection", (int)error); isAlive = false; if (throwOnException) { @@ -2923,7 +2923,7 @@ public void WriteAsyncCallback(IntPtr key, PacketHandle packet, uint sniError) { if (sniError != TdsEnums.SNI_SUCCESS) { - SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)sniError); + SqlClientEventSource.Log.TryTraceEvent(" write async returned error code {0}", (int)sniError); try { AddError(_parser.ProcessSNIError(this)); @@ -3413,7 +3413,7 @@ private Task SNIWritePacket(PacketHandle packet, out uint sniError, bool canAccu if (error != TdsEnums.SNI_SUCCESS) { - SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)error); + SqlClientEventSource.Log.TryTraceEvent(" write async returned error code {0}", (int)error); AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(); } @@ -3448,7 +3448,7 @@ private Task SNIWritePacket(PacketHandle packet, out uint sniError, bool canAccu } else { - SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)sniError); + SqlClientEventSource.Log.TryTraceEvent(" write async returned error code {0}", (int)sniError); AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(callerHasConnectionLock); } @@ -3487,35 +3487,35 @@ internal void SendAttention(bool mustTakeWriteLock = false) if (!_skipSendAttention) { #endif - // Take lock and send attention - bool releaseLock = false; - if ((mustTakeWriteLock) && (!_parser.Connection.ThreadHasParserLockForClose)) - { - releaseLock = true; - _parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false); - _parser.Connection.ThreadHasParserLockForClose = true; - } - try - { - // Check again (just in case the connection was closed while we were waiting) - if (_parser.State == TdsParserState.Closed || _parser.State == TdsParserState.Broken) + // Take lock and send attention + bool releaseLock = false; + if ((mustTakeWriteLock) && (!_parser.Connection.ThreadHasParserLockForClose)) { - return; + releaseLock = true; + _parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false); + _parser.Connection.ThreadHasParserLockForClose = true; } + try + { + // Check again (just in case the connection was closed while we were waiting) + if (_parser.State == TdsParserState.Closed || _parser.State == TdsParserState.Broken) + { + return; + } - uint sniError; - _parser._asyncWrite = false; // stop async write - SNIWritePacket(attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false); - SqlClientEventSource.Log.TraceEvent(" Send Attention ASync.", "Info"); - } - finally - { - if (releaseLock) + uint sniError; + _parser._asyncWrite = false; // stop async write + SNIWritePacket(attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false); + SqlClientEventSource.Log.TryTraceEvent(" Send Attention ASync."); + } + finally { - _parser.Connection.ThreadHasParserLockForClose = false; - _parser.Connection._parserLock.Release(); + if (releaseLock) + { + _parser.Connection.ThreadHasParserLockForClose = false; + _parser.Connection._parserLock.Release(); + } } - } #if DEBUG } #endif @@ -3528,8 +3528,8 @@ internal void SendAttention(bool mustTakeWriteLock = false) _attentionSending = false; } - SqlClientEventSource.Log.AdvancedTraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); - SqlClientEventSource.Log.TraceEvent(" Attention sent to the server.", "Info"); + SqlClientEventSource.Log.TryAdvancedTraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); + SqlClientEventSource.Log.TryTraceEvent(" Attention sent to the server."); AssertValidState(); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs index 193babd231..7d5b995776 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs @@ -39,13 +39,13 @@ public TdsParserStateObject CreateTdsParserStateObject(TdsParser parser) { if (UseManagedSNI) { - SqlClientEventSource.Log.TraceEvent(" Found AppContext switch '{0}' enabled, managed networking implementation will be used." + SqlClientEventSource.Log.TryTraceEvent(" Found AppContext switch '{0}' enabled, managed networking implementation will be used." , UseManagedNetworkingOnWindows); return new TdsParserStateObjectManaged(parser); } else { - SqlClientEventSource.Log.TraceEvent(" AppContext switch '{0}' not enabled, native networking implementation will be used." + SqlClientEventSource.Log.TryTraceEvent(" AppContext switch '{0}' not enabled, native networking implementation will be used." , UseManagedNetworkingOnWindows); return new TdsParserStateObjectNative(parser); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlTypes/SqlFileStream.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlTypes/SqlFileStream.Windows.cs index fec2f1f768..509a2e7700 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlTypes/SqlFileStream.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlTypes/SqlFileStream.Windows.cs @@ -61,7 +61,7 @@ public SqlFileStream(string path, byte[] transactionContext, FileAccess access) /// public SqlFileStream(string path, byte[] transactionContext, FileAccess access, FileOptions options, long allocationSize) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} access={1} options={2} path='{3}'", ObjectID, (int)access, (int)options, path); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} access={1} options={2} path='{3}'", ObjectID, (int)access, (int)options, path); try { //----------------------------------------------------------------- @@ -86,7 +86,7 @@ public SqlFileStream(string path, byte[] transactionContext, FileAccess access, } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -599,7 +599,7 @@ long allocationSize eaBuffer: b, eaLength: (uint)fullSize); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, desiredAccess=0x{1}, allocationSize={2}, " + + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, desiredAccess=0x{1}, allocationSize={2}, " + "fileAttributes=0x{3}, shareAccess=0x{4}, dwCreateDisposition=0x{5}, createOptions=0x{ dwCreateOptions}", ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)nShareAccess, dwCreateDisposition); retval = status; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs index 659c4f31be..e52a60e1e0 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/AdapterUtil.cs @@ -101,7 +101,7 @@ static private void TraceException(string trace, Exception e) Debug.Assert(null != e, "TraceException: null Exception"); if (null != e) { - SqlClientEventSource.Log.TraceEvent(trace, e); + SqlClientEventSource.Log.TryTraceEvent(trace, e); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs index 794332c1fa..c51f4f2730 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DBConnectionString.cs @@ -470,7 +470,7 @@ static private string[] NoDuplicateUnion(string[] a, string[] b) private static string[] ParseRestrictions(string restrictions, Hashtable synonyms) { #if DEBUG - SqlClientEventSource.Log.AdvancedTraceEvent(" Restrictions='{0}'", restrictions); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Restrictions='{0}'", restrictions); #endif List restrictionValues = new List(); StringBuilder buffer = new StringBuilder(restrictions.Length); @@ -486,7 +486,7 @@ private static string[] ParseRestrictions(string restrictions, Hashtable synonym if (!ADP.IsEmpty(keyname)) { #if DEBUG - SqlClientEventSource.Log.AdvancedTraceEvent(" KeyName='{0}'", keyname); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" KeyName='{0}'", keyname); #endif string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144 if (ADP.IsEmpty(realkeyname)) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs index 4274ad3eba..07431834fb 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionOptions.cs @@ -641,7 +641,7 @@ private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hash } else { - SqlClientEventSource.Log.AdvancedTraceEvent(" KeyName='{0}'", keyname); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" KeyName='{0}'", keyname); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs index 4170e38943..7f02867eed 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/DataException.cs @@ -28,10 +28,10 @@ static private void TraceException( Debug.Assert(null != e, "TraceException: null Exception"); if (null != e) { - SqlClientEventSource.Log.AdvancedTraceEvent(trace, e.Message); + SqlClientEventSource.Log.TryAdvancedTraceEvent(trace, e.Message); try { - SqlClientEventSource.Log.AdvancedTraceEvent(" Environment StackTrace = '{0}'", Environment.StackTrace); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Environment StackTrace = '{0}'", Environment.StackTrace); } catch (System.Security.SecurityException) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs index fa5eddef35..50383d27a7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionFactory.cs @@ -65,7 +65,7 @@ internal int ObjectID public void ClearAllPools() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent("", "API"); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(""); try { Dictionary connectionPoolGroups = _connectionPoolGroups; @@ -80,14 +80,14 @@ public void ClearAllPools() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } public void ClearPool(DbConnection connection) { ADP.CheckArgumentNull(connection, "connection"); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", GetObjectId(connection)); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", GetObjectId(connection)); try { DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection); @@ -98,7 +98,7 @@ public void ClearPool(DbConnection connection) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -106,7 +106,7 @@ public void ClearPool(DbConnectionPoolKey key) { Debug.Assert(key != null, "key cannot be null"); ADP.CheckArgumentNull(key.ConnectionString, "key.ConnectionString"); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" connectionString"); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" connectionString"); try { @@ -119,7 +119,7 @@ public void ClearPool(DbConnectionPoolKey key) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -151,7 +151,7 @@ internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConne PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakeNonPooledObject(owningConnection, PerformanceCounters); } - SqlClientEventSource.Log.TraceEvent(" {0}, Non-pooled database connection created.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Non-pooled database connection created.", ObjectID); return newConnection; } @@ -167,7 +167,7 @@ internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbCo PerformanceCounters.HardConnectsPerSecond.Increment(); newConnection.MakePooledConnection(pool); } - SqlClientEventSource.Log.TraceEvent(" {0}, Pooled database connection created.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Pooled database connection created.", ObjectID); return newConnection; } @@ -362,7 +362,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour // connection creation failed on semaphore waiting or if max pool reached if (connectionPool.IsRunning) { - SqlClientEventSource.Log.TraceEvent(" {0}, GetConnection failed because a pool timeout occurred.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, GetConnection failed because a pool timeout occurred.", ObjectID); // If GetConnection failed while the pool is running, the pool timeout occurred. throw ADP.PooledOpenTimeout(); @@ -381,7 +381,7 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour if (connection == null) { - SqlClientEventSource.Log.TraceEvent(" {0}, GetConnection failed because a pool timeout occurred and all retries were exhausted.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, GetConnection failed because a pool timeout occurred and all retries were exhausted.", ObjectID); // exhausted all retries or timed out - give up throw ADP.PooledOpenTimeout(); @@ -408,7 +408,7 @@ private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnecti // however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)) { - SqlClientEventSource.Log.TraceEvent(" {0}, DisabledPoolGroup={1}", ObjectID, connectionPoolGroup.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, DisabledPoolGroup={1}", ObjectID, connectionPoolGroup.ObjectID); // reusing existing pool option in case user originally used SetConnectionPoolOptions DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions; @@ -539,7 +539,7 @@ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPo private void PruneConnectionPoolGroups(object state) { // when debugging this method, expect multiple threads at the same time - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}", ObjectID); // First, walk the pool release list and attempt to clear each // pool, when the pool is finally empty, we dispose of it. If the @@ -559,7 +559,7 @@ private void PruneConnectionPoolGroups(object state) if (0 == pool.Count) { _poolsToRelease.Remove(pool); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, ReleasePool={1}", ObjectID, pool.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, ReleasePool={1}", ObjectID, pool.ObjectID); PerformanceCounters.NumberOfInactiveConnectionPools.Decrement(); } } @@ -584,7 +584,7 @@ private void PruneConnectionPoolGroups(object state) if (0 == poolsLeft) { _poolGroupsToRelease.Remove(poolGroup); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, ReleasePoolGroup={1}", ObjectID, poolGroup.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, ReleasePoolGroup={1}", ObjectID, poolGroup.ObjectID); PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Decrement(); } } @@ -650,7 +650,7 @@ internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing) internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup) { Debug.Assert(null != poolGroup, "null poolGroup?"); - SqlClientEventSource.Log.TraceEvent(" {0}, poolGroup={1}", ObjectID, poolGroup.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, poolGroup={1}", ObjectID, poolGroup.ObjectID); lock (_poolGroupsToRelease) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs index 25ef54f6f7..3256c9c39a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionInternal.cs @@ -163,7 +163,7 @@ protected internal SysTx.Transaction EnlistedTransaction if (null != value) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Enlisting.", ObjectID, value.GetHashCode()); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Enlisting.", ObjectID, value.GetHashCode()); TransactionOutcomeEnlist(value); } } @@ -390,7 +390,7 @@ internal void ActivateConnection(SysTx.Transaction transaction) { // Internal method called from the connection pooler so we don't expose // the Activate method publicly. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Activating", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Activating", ObjectID); #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); Debug.Assert(1 == activateCount, "activated multiple times?"); @@ -461,7 +461,7 @@ internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFac //////////////////////////////////////////////////////////////// Debug.Assert(null != owningObject, "null owningObject"); Debug.Assert(null != connectionFactory, "null connectionFactory"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0} Closing.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0} Closing.", ObjectID); // if an exception occurs after the state change but before the try block // the connection will be stuck in OpenBusy state. The commented out try-catch @@ -566,7 +566,7 @@ internal void DeactivateConnection() { // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Deactivating", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Deactivating", ObjectID); #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); Debug.Assert(0 == activateCount, "activated multiple times?"); @@ -600,7 +600,7 @@ virtual internal void DelegatedTransactionEnded() // IMPORTANT NOTE: You must have taken a lock on the object before // you call this method to prevent race conditions with Clear and // ReclaimEmancipatedObjects. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Delegated Transaction Completed.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Delegated Transaction Completed.", ObjectID); if (1 == _pooledCount) { @@ -663,7 +663,7 @@ public virtual void Dispose() protected internal void DoNotPoolThisConnection() { _cannotBePooled = true; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Marking pooled object as non-poolable so it will be disposed", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Marking pooled object as non-poolable so it will be disposed", ObjectID); } /// Ensure that this connection cannot be put back into the pool. @@ -671,7 +671,7 @@ protected internal void DoNotPoolThisConnection() protected internal void DoomThisConnection() { _connectionIsDoomed = true; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Dooming", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Dooming", ObjectID); } // Reset connection doomed status so it can be re-connected and pooled. @@ -805,7 +805,7 @@ internal void PrePush(object expectedOwner) } //DbConnection x = (expectedOwner as DbConnection); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Preparing to push into pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Preparing to push into pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount); _pooledCount++; _owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2% @@ -837,7 +837,7 @@ internal void PostPop(object newOwner) _pooledCount--; //DbConnection x = (newOwner as DbConnection); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Preparing to pop from pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Preparing to pop from pool, owning connection {1}, pooledCount={2}", ObjectID, 0, _pooledCount); //3 // The following tests are retail assertions of things we can't allow to happen. if (null != Pool) @@ -894,7 +894,7 @@ internal void DetachCurrentTransactionIfEnded() // Detach transaction from connection. internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction Completed. (pooledCount={1})", ObjectID, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction Completed. (pooledCount={1})", ObjectID, _pooledCount); // potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new // transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should @@ -935,7 +935,7 @@ internal void CleanupConnectionOnTransactionCompletion(SysTx.Transaction transac void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) { SysTx.Transaction transaction = e.Transaction; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); CleanupTransactionOnCompletion(transaction); CleanupConnectionOnTransactionCompletion(transaction); @@ -952,7 +952,7 @@ private void TransactionOutcomeEnlist(SysTx.Transaction transaction) internal void SetInStasis() { _isInStasis = true; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.", ObjectID); PerformanceCounters.NumberOfStasisConnections.Increment(); } @@ -960,11 +960,11 @@ private void TerminateStasis(bool returningToPool) { if (returningToPool) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed. Returning to general pool.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed. Returning to general pool.", ObjectID); } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed/leaked. Disposing.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Delegated Transaction has ended, connection is closed/leaked. Disposing.", ObjectID); } PerformanceCounters.NumberOfStasisConnections.Decrement(); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs index 214c080622..b69d3bb122 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs @@ -81,7 +81,7 @@ internal TransactedConnectionPool(DbConnectionPool pool) Debug.Assert(null != pool, "null pool?"); _pool = pool; _transactedCxns = new Dictionary(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Constructed for connection pool {1}", ObjectID, _pool.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Constructed for connection pool {1}", ObjectID, _pool.ObjectID); } internal int ObjectID @@ -140,7 +140,7 @@ internal DbConnectionInternal GetTransactedObject(SysTx.Transaction transaction) if (null != transactedObject) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Popped.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } return transactedObject; } @@ -167,7 +167,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); connections.Add(transactedObject); } } @@ -202,13 +202,13 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt lock (connections) { Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Pushing.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); connections.Add(transactedObject); } } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Adding List to transacted pool.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Adding List to transacted pool.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); // add the connection/transacted object to the list newConnections.Add(transactedObject); @@ -236,7 +236,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt } } } - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Added.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Added.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } Pool.PerformanceCounters.NumberOfFreeConnections.Increment(); @@ -245,7 +245,7 @@ internal void PutTransactedObject(SysTx.Transaction transaction, DbConnectionInt internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionInternal transactedObject) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); TransactedConnectionList connections; int entry = -1; @@ -279,7 +279,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern // safely remove the list from the transacted pool. if (0 >= connections.Count) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Removing List from transacted pool.", ObjectID, transaction.GetHashCode()); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Removing List from transacted pool.", ObjectID, transaction.GetHashCode()); _transactedCxns.Remove(transaction); // we really need to dispose our connection list; it may have @@ -296,7 +296,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern else { //Debug.Assert ( false, "TransactionCompletedEvent fired before PutTransactedObject put the connection in the transacted pool." ); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transacted pool not yet created prior to transaction completing. Connection may be leaked.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transacted pool not yet created prior to transaction completing. Connection may be leaked.", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); } } @@ -523,7 +523,7 @@ internal DbConnectionPool( _poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback _state = State.Running; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Constructed.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Constructed.", ObjectID); //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls // StartBackgroundCallbacks after pool is actually in the collection @@ -671,7 +671,7 @@ private void CleanupCallback(Object state) // // With this logic, objects are pruned from the pool if unused for // at least one period but not more than two periods. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}", ObjectID); // Destroy free objects that put us above MinPoolSize from old stack. while (Count > MinPoolSize) @@ -745,7 +745,7 @@ private void CleanupCallback(Object state) break; Debug.Assert(obj != null, "null connection is not expected"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, ChangeStacks={1}", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, ChangeStacks={1}", ObjectID, obj.ObjectID); Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); Debug.Assert(obj.CanBePooled, "pooled object is not poolable"); @@ -760,7 +760,7 @@ private void CleanupCallback(Object state) internal void Clear() { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Clearing.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Clearing.", ObjectID); DbConnectionInternal obj; // First, quickly doom everything. @@ -796,7 +796,7 @@ internal void Clear() // Finally, reclaim everything that's emancipated (which, because // it's been doomed, will cause it to be disposed of as well) ReclaimEmancipatedObjects(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Cleared.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Cleared.", ObjectID); } private Timer CreateCleanupTimer() @@ -886,7 +886,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio } } } - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Added to pool.", ObjectID, newObj != null ? newObj?.ObjectID.ToString() ?? "null" : "null"); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Added to pool.", ObjectID, newObj?.ObjectID); // Reset the error wait: _errorWait = ERROR_WAIT_DEFAULT; @@ -947,7 +947,7 @@ private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectio private void DeactivateObject(DbConnectionInternal obj) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Deactivating.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Deactivating.", ObjectID, obj.ObjectID); obj.DeactivateConnection(); // we presume this operation is safe outside of a lock... bool returnToGeneralPool = false; @@ -1087,11 +1087,11 @@ internal void DestroyObject(DbConnectionInternal obj) // again. if (obj.IsTxRootWaitingForTxEnd) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Has Delegated Transaction, waiting to Dispose.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Has Delegated Transaction, waiting to Dispose.", ObjectID, obj.ObjectID); } else { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Removing from pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Removing from pool.", ObjectID, obj.ObjectID); bool removed = false; lock (_objectList) { @@ -1102,18 +1102,18 @@ internal void DestroyObject(DbConnectionInternal obj) if (removed) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Removed from pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Removed from pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfPooledConnections.Decrement(); } obj.Dispose(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Disposed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Disposed.", ObjectID, obj.ObjectID); PerformanceCounters.HardDisconnectsPerSecond.Increment(); } } private void ErrorCallback(Object state) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Resetting Error handling.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Resetting Error handling.", ObjectID); _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); @@ -1287,7 +1287,7 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource {0}, DbConnectionInternal State != Running.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, DbConnectionInternal State != Running.", ObjectID); connection = null; return true; } @@ -1332,7 +1332,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj SysTx.Transaction transaction = null; PerformanceCounters.SoftConnectsPerSecond.Increment(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Getting connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Getting connection.", ObjectID); // If automatic transaction enlistment is required, then we try to // get the connection from the transacted connection pool first. @@ -1385,7 +1385,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj switch (waitResult) { case WAIT_TIMEOUT: - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Wait timed out.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Wait timed out.", ObjectID); Interlocked.Decrement(ref _waitCount); connection = null; return false; @@ -1393,12 +1393,12 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case ERROR_HANDLE: // Throw the error that PoolCreateRequest stashed. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Errors are set.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Errors are set.", ObjectID); Interlocked.Decrement(ref _waitCount); throw TryCloneCachedException(); case CREATION_HANDLE: - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Creating new connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Creating new connection.", ObjectID); try { obj = UserCreateRequest(owningObject, userOptions); @@ -1451,7 +1451,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj if ((obj != null) && (!obj.IsConnectionAlive())) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); obj = null; // Setting to null in case creating a new object fails @@ -1462,7 +1462,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj RuntimeHelpers.PrepareConstrainedRegions(); try { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Creating new connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Creating new connection.", ObjectID); obj = UserCreateRequest(owningObject, userOptions); } finally @@ -1473,7 +1473,7 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj else { // Timeout waiting for creation semaphore - return null - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Wait timed out.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Wait timed out.", ObjectID); connection = null; return false; } @@ -1483,28 +1483,28 @@ private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObj case WAIT_FAILED: Debug.Assert(waitForMultipleObjectsExHR != 0, "WaitForMultipleObjectsEx failed but waitForMultipleObjectsExHR remained 0"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Wait failed.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Wait failed.", ObjectID); Interlocked.Decrement(ref _waitCount); Marshal.ThrowExceptionForHR(waitForMultipleObjectsExHR); goto default; // if ThrowExceptionForHR didn't throw for some reason case (WAIT_ABANDONED + SEMAPHORE_HANDLE): - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Semaphore handle abandonded.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Semaphore handle abandonded.", ObjectID); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(SEMAPHORE_HANDLE, _waitHandles.PoolSemaphore); case (WAIT_ABANDONED + ERROR_HANDLE): - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Error handle abandonded.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Error handle abandonded.", ObjectID); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(ERROR_HANDLE, _waitHandles.ErrorEvent); case (WAIT_ABANDONED + CREATION_HANDLE): - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Creation handle abandoned.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Creation handle abandoned.", ObjectID); Interlocked.Decrement(ref _waitCount); throw new AbandonedMutexException(CREATION_HANDLE, _waitHandles.CreationSemaphore); default: - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, WaitForMultipleObjects={1}", ObjectID, waitResult); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, WaitForMultipleObjects={1}", ObjectID, waitResult); Interlocked.Decrement(ref _waitCount); throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult); } @@ -1576,7 +1576,7 @@ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal o internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) { PerformanceCounters.SoftConnectsPerSecond.Increment(); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, replacing connection.", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, replacing connection.", ObjectID); DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); if (newConnection != null) @@ -1618,7 +1618,7 @@ private DbConnectionInternal GetFromGeneralPool() if (null != obj) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Popped from general pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Popped from general pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfFreeConnections.Decrement(); } return (obj); @@ -1635,7 +1635,7 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac if (null != obj) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Popped from transacted pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Popped from transacted pool.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfFreeConnections.Decrement(); if (obj.IsTransactionRoot) @@ -1646,14 +1646,14 @@ private DbConnectionInternal GetFromTransactedPool(out SysTx.Transaction transac } catch { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); throw; } } else if (!obj.IsConnectionAlive()) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, found dead and removed.", ObjectID, obj.ObjectID); DestroyObject(obj); obj = null; } @@ -1668,7 +1668,7 @@ private void PoolCreateRequest(object state) { // called by pooler to ensure pool requests are currently being satisfied - // creation mutex has not been obtained - long scopeID = SqlClientEventSource.Log.PoolerScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryPoolerScopeEnterEvent(" {0}", ObjectID); try { if (State.Running == _state) @@ -1753,7 +1753,7 @@ private void PoolCreateRequest(object state) else { // trace waitResult and ignore the failure - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, PoolCreateRequest called WaitForSingleObject failed {1}", ObjectID, waitResult); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, PoolCreateRequest called WaitForSingleObject failed {1}", ObjectID, waitResult); } } catch (Exception e) @@ -1767,7 +1767,7 @@ private void PoolCreateRequest(object state) // Now that CreateObject can throw, we need to catch the exception and discard it. // There is no further action we can take beyond tracing. The error will be // thrown to the user the next time they request a connection. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, PoolCreateRequest called CreateConnection which threw an exception: {1}", ObjectID, e); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, PoolCreateRequest called CreateConnection which threw an exception: {1}", ObjectID, e); } finally { @@ -1787,7 +1787,7 @@ private void PoolCreateRequest(object state) } finally { - SqlClientEventSource.Log.PoolerScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryPoolerScopeLeaveEvent(scopeID); } } @@ -1800,7 +1800,7 @@ internal void PutNewObject(DbConnectionInternal obj) // causes the following assert to fire, which really mucks up stress // against checked bits. // Debug.Assert(obj.CanBePooled, "non-poolable object in pool"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Pushing to general pool.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Pushing to general pool.", ObjectID, obj.ObjectID); _stackNew.Push(obj); _waitHandles.PoolSemaphore.Release(1); @@ -1849,7 +1849,7 @@ internal void PutObjectFromTransactedPool(DbConnectionInternal obj) // method, we can safely presume that the caller is the only person // that is using the connection, and that all pre-push logic has been // done and all transactions are ended. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Transaction has ended.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Transaction has ended.", ObjectID, obj.ObjectID); if (_state == State.Running && obj.CanBePooled) { @@ -1874,7 +1874,7 @@ private void QueuePoolCreateRequest() private bool ReclaimEmancipatedObjects() { bool emancipatedObjectFound = false; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}", ObjectID); List reclaimedObjects = new List(); int count; @@ -1926,7 +1926,7 @@ private bool ReclaimEmancipatedObjects() for (int i = 0; i < count; ++i) { DbConnectionInternal obj = reclaimedObjects[i]; - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Connection {1}, Reclaiming.", ObjectID, obj.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Connection {1}, Reclaiming.", ObjectID, obj.ObjectID); PerformanceCounters.NumberOfReclaimedConnections.Increment(); emancipatedObjectFound = true; @@ -1939,7 +1939,7 @@ private bool ReclaimEmancipatedObjects() internal void Startup() { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, CleanupWait={1}", ObjectID, _cleanupWait); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, CleanupWait={1}", ObjectID, _cleanupWait); _cleanupTimer = CreateCleanupTimer(); if (NeedToReplenish) @@ -1950,7 +1950,7 @@ internal void Startup() internal void Shutdown() { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}", ObjectID); _state = State.ShuttingDown; // deactivate timer callbacks @@ -1972,7 +1972,7 @@ internal void TransactionEnded(SysTx.Transaction transaction, DbConnectionIntern Debug.Assert(null != transactedObject, "null transactedObject?"); // Note: connection may still be associated with transaction due to Explicit Unbinding requirement. - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Transaction {1}, Connection {2}, Transaction Completed", ObjectID, transaction.GetHashCode(), transactedObject.ObjectID); // called by the internal connection when it get's told that the // transaction is completed. We tell the transacted pool to remove diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs index 8cd608d127..6aa0847667 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/DbConnectionPoolGroup.cs @@ -273,7 +273,7 @@ private bool MarkPoolGroupAsActive() if (PoolGroupStateIdle == _state) { _state = PoolGroupStateActive; - SqlClientEventSource.Log.TraceEvent(" {0}, Active", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Active", ObjectID); } return (PoolGroupStateActive == _state); } @@ -335,12 +335,12 @@ internal bool Prune() if (PoolGroupStateActive == _state) { _state = PoolGroupStateIdle; - SqlClientEventSource.Log.TraceEvent(" {0}, Idle", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Idle", ObjectID); } else if (PoolGroupStateIdle == _state) { _state = PoolGroupStateDisabled; - SqlClientEventSource.Log.TraceEvent(" {0}, Disabled", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Disabled", ObjectID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs index 618a6ea183..ad0e88a1d2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/ProviderBase/SqlConnectionHelper.cs @@ -87,7 +87,7 @@ internal DbConnectionOptions ConnectionOptions private string ConnectionString_Get() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); bool hidePassword = InnerConnection.ShouldHidePassword; DbConnectionOptions connectionOptions = UserConnectionOptions; return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : ""); @@ -131,8 +131,10 @@ private void ConnectionString_Set(DbConnectionPoolKey key) throw ADP.OpenConnectionPropertySet(ADP.ConnectionString, connectionInternal.State); } - string cstr = ((null != connectionOptions) ? connectionOptions.UsersConnectionStringForTrace() : ""); - SqlClientEventSource.Log.TraceEvent(" {0}, '{1}'", ObjectID, cstr); + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + SqlClientEventSource.Log.TraceEvent(" {0}, '{1}'", ObjectID, connectionOptions.UsersConnectionStringForTrace()); + } } internal DbConnectionInternal InnerConnection @@ -182,11 +184,11 @@ internal void Abort(Exception e) // will end the reliable try... if (e is OutOfMemoryException) { - SqlClientEventSource.Log.TraceEvent(" {0}, Aborting operation due to asynchronous exception: {'OutOfMemory'}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Aborting operation due to asynchronous exception: {'OutOfMemory'}", ObjectID); } else { - SqlClientEventSource.Log.TraceEvent(" {0}, Aborting operation due to asynchronous exception: {1}", ObjectID, e.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Aborting operation due to asynchronous exception: {1}", ObjectID, e); } } @@ -199,7 +201,7 @@ internal void AddWeakReference(object value, int tag) override protected DbCommand CreateDbCommand() { DbCommand command = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; @@ -208,7 +210,7 @@ override protected DbCommand CreateDbCommand() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } return command; } @@ -245,7 +247,7 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)); permissionSet.Demand(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection enlisting in a transaction.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection enlisting in a transaction.", ObjectID); SysTx.Transaction indigoTransaction = null; if (null != transaction) @@ -270,7 +272,7 @@ private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITrans override public void EnlistTransaction(SysTx.Transaction transaction) { SqlConnection.ExecutePermission.Demand(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection enlisting in a transaction.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection enlisting in a transaction.", ObjectID); // If we're currently enlisted in a transaction and we were called // on the EnlistTransaction method (Whidbey) we're not allowed to diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs index 6d29848ed3..c18fdda558 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs @@ -73,7 +73,7 @@ static IntPtr UserInstanceDLLHandle SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle); if (s_userInstanceDLLHandle != IntPtr.Zero) { - SqlClientEventSource.Log.TraceEvent(" LocalDB - handle obtained"); + SqlClientEventSource.Log.TryTraceEvent(" LocalDB - handle obtained"); } else { @@ -117,7 +117,7 @@ static LocalDBCreateInstanceDelegate LocalDBCreateInstance if (functionAddr == IntPtr.Zero) { int hResult = Marshal.GetLastWin32Error(); - SqlClientEventSource.Log.TraceEvent(" GetProcAddress for LocalDBCreateInstance error 0x{0}", hResult); + SqlClientEventSource.Log.TryTraceEvent(" GetProcAddress for LocalDBCreateInstance error 0x{0}", hResult); throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); } s_localDBCreateInstance = (LocalDBCreateInstanceDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBCreateInstanceDelegate)); @@ -159,7 +159,7 @@ static LocalDBFormatMessageDelegate LocalDBFormatMessage { // SNI checks for LocalDBFormatMessage during DLL loading, so it is practically impossible to get this error. int hResult = Marshal.GetLastWin32Error(); - SqlClientEventSource.Log.TraceEvent(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); + SqlClientEventSource.Log.TryTraceEvent(" GetProcAddress for LocalDBFormatMessage error 0x{0}", hResult); throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_MethodNotFound")); } s_localDBFormatMessage = (LocalDBFormatMessageDelegate)Marshal.GetDelegateForFunctionPointer(functionAddr, typeof(LocalDBFormatMessageDelegate)); @@ -315,7 +315,7 @@ internal static void CreateLocalDBInstance(string instance) } else { - SqlClientEventSource.Log.TraceEvent(" No system.data.localdb section found in configuration"); + SqlClientEventSource.Log.TryTraceEvent(" No system.data.localdb section found in configuration"); } s_configurableInstances = tempConfigurableInstances; } @@ -342,14 +342,14 @@ internal static void CreateLocalDBInstance(string instance) // LocalDBCreateInstance is thread- and cross-process safe method, it is OK to call from two threads simultaneously int hr = LocalDBCreateInstance(instanceInfo.version, instance, flags: 0); - SqlClientEventSource.Log.TraceEvent(" Starting creation of instance {0} version {1}", instance, instanceInfo.version); + SqlClientEventSource.Log.TryTraceEvent(" Starting creation of instance {0} version {1}", instance, instanceInfo.version); if (hr < 0) { throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_CreateFailed"), instance: instance, localDbError: hr); } - SqlClientEventSource.Log.TraceEvent(" Finished creation of instance {0}", instance); + SqlClientEventSource.Log.TryTraceEvent(" Finished creation of instance {0}", instance); instanceInfo.created = true; // mark instance as created } // CreateLocalDbInstance } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs index 3cc4328ce8..663d042127 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiEventSink_Default.cs @@ -267,7 +267,7 @@ internal override void MessagePosted(int number, byte state, byte errorClass, st { if (null == _parent) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, number={1} state={2} errorClass={3} server='{4}' message='{5}' procedure='{6}' linenumber={7}.", 0, number, state, errorClass, server ?? "", message ?? "", procedure ?? "", lineNumber); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, number={1} state={2} errorClass={3} server='{4}' message='{5}' procedure='{6}' linenumber={7}.", 0, number, state, errorClass, server, message, procedure, lineNumber); SqlError error = new SqlError(number, state, errorClass, server, message, procedure, lineNumber); if (error.Class < TdsEnums.MIN_ERROR_CLASS) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiMetaData.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiMetaData.cs index 22d8d1c469..1c4312d9b1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiMetaData.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/Server/SmiMetaData.cs @@ -830,7 +830,7 @@ virtual internal string TraceString(int indent) } } - return String.Format(CultureInfo.InvariantCulture, "\n\t" + return string.Format(CultureInfo.InvariantCulture, "\n\t" + "{0} SqlDbType={1:g}\n\t" + "{0} MaxLength={2:d}\n\t" + "{0} Precision={3:d}\n\t" diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs index af9a603898..06bdc0bb6b 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlAuthenticationProviderManager.cs @@ -38,7 +38,7 @@ static SqlAuthenticationProviderManager() catch (ConfigurationErrorsException e) { // Don't throw an error for invalid config files - SqlClientEventSource.Log.TraceEvent("Unable to load custom SqlAuthenticationProviders or SqlClientAuthenticationProviders. ConfigurationManager failed to load due to configuration errors: {0}", e); + SqlClientEventSource.Log.TryTraceEvent("Unable to load custom SqlAuthenticationProviders or SqlClientAuthenticationProviders. ConfigurationManager failed to load due to configuration errors: {0}", e); } Instance = new SqlAuthenticationProviderManager(configurationSection); Instance.SetProvider(SqlAuthenticationMethod.ActiveDirectoryIntegrated, activeDirectoryAuthProvider); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs index 37a4ff7c30..fdfbc1a71b 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlBulkCopy.cs @@ -632,8 +632,8 @@ private string CreateInitialQuery() private Task CreateAndExecuteInitialQueryAsync(out BulkCopySimpleResultSet result) { string TDSCommand = CreateInitialQuery(); - SqlClientEventSource.Log.TraceEvent(" Initial Query: '{0}'", TDSCommand); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryTraceEvent(" Initial Query: '{0}'", TDSCommand); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); if (executeTask == null) @@ -956,7 +956,7 @@ private string TryGetOrderHintText(HashSet destColumnNames) // private Task SubmitUpdateBulkCommand(string TDSCommand) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Task executeTask = _parser.TdsExecuteSQLBatch(TDSCommand, this.BulkCopyTimeout, null, _stateObj, sync: !_isAsyncBulkCopy, callerHasConnectionLock: true); if (executeTask == null) @@ -2586,7 +2586,7 @@ private void CheckAndRaiseNotification() // it's also the user's chance to cause an exception ... _stateObj.BcpLock = true; abortOperation = FireRowsCopiedEvent(_rowsCopied); - SqlClientEventSource.Log.TraceEvent("", "INFO"); + SqlClientEventSource.Log.TryTraceEvent(""); // just in case some pathological person closes the target connection ... if (ConnectionState.Open != _connection.State) @@ -2975,18 +2975,18 @@ private void CopyBatchesAsyncContinuedOnError(bool cleanupParser) { tdsReliabilitySection.Start(); #endif //DEBUG - if ((cleanupParser) && (_parser != null) && (_stateObj != null)) - { - _parser._asyncWrite = false; - Task task = _parser.WriteBulkCopyDone(_stateObj); - Debug.Assert(task == null, "Write should not pend when error occurs"); - RunParser(); - } + if ((cleanupParser) && (_parser != null) && (_stateObj != null)) + { + _parser._asyncWrite = false; + Task task = _parser.WriteBulkCopyDone(_stateObj); + Debug.Assert(task == null, "Write should not pend when error occurs"); + RunParser(); + } - if (_stateObj != null) - { - CleanUpStateObject(); - } + if (_stateObj != null) + { + CleanUpStateObject(); + } #if DEBUG } finally diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs index 26db371812..d0a9d96be7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -343,7 +343,7 @@ internal CommandEventSink(SqlCommand command) : base() internal override void StatementCompleted(int rowsAffected) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, rowsAffected={1}.", _command.ObjectID, rowsAffected); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, rowsAffected={1}.", _command.ObjectID, rowsAffected); _command.InternalRecordsAffected = rowsAffected; // UNDONE: need to fire events back to user code, but this may be called @@ -355,12 +355,12 @@ internal override void StatementCompleted(int rowsAffected) internal override void BatchCompleted() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}.", _command.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}.", _command.ObjectID); } internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITypedGettersV3 parameterValues) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} metaData.Length={1}.", _command.ObjectID, (null != metaData) ? metaData.Length : -1); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} metaData.Length={1}.", _command.ObjectID, metaData?.Length); if (SqlClientEventSource.Log.IsAdvancedTraceOn()) { @@ -368,7 +368,7 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp { for (int i = 0; i < metaData.Length; i++) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, metaData[{1}] is {2}{3}", _command.ObjectID, i, metaData[i].GetType().ToString(), metaData[i].TraceString()); + SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, metaData[{1}] is {2}{3}", _command.ObjectID, i, metaData[i].GetType(), metaData[i].TraceString()); } } } @@ -379,7 +379,10 @@ internal override void ParametersAvailable(SmiParameterMetaData[] metaData, ITyp internal override void ParameterAvailable(SmiParameterMetaData metaData, SmiTypedGetterSetter parameterValues, int ordinal) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, metaData[{1}] is {2}{ 3}", _command.ObjectID, ordinal, metaData.GetType().ToString(), metaData.TraceString()); + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, metaData[{1}] is {2}{ 3}", _command.ObjectID, ordinal, metaData?.GetType(), metaData?.TraceString()); + } Debug.Assert(SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion); _command.OnParameterAvailableSmi(metaData, parameterValues, ordinal); } @@ -562,7 +565,7 @@ private SqlCommand(SqlCommand from) : this() } } _activeConnection = value; // UNDONE: Designers need this setter. Should we block other scenarios? - SqlClientEventSource.Log.TraceEvent(" {0}, {1}", ObjectID, (null != value) ? value.ObjectID : -1); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value?.ObjectID); } } @@ -640,7 +643,7 @@ public SqlNotificationRequest Notification } set { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); _sqlDep = null; _notification = value; } @@ -690,7 +693,7 @@ internal SqlStatistics Statistics } // TODO: Add objid here - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); _transaction = value; } } @@ -725,7 +728,7 @@ override public string CommandText } set { - SqlClientEventSource.Log.TraceEvent(" {0}, String Value = '{1}'", ObjectID, value); + SqlClientEventSource.Log.TryTraceEvent(" {0}, String Value = '{1}'", ObjectID, value); if (0 != ADP.SrcCompare(_commandText, value)) { @@ -763,7 +766,7 @@ override public int CommandTimeout } set { - SqlClientEventSource.Log.TraceEvent(" {0}, {1}", ObjectID, value); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value); if (value < 0) { throw ADP.InvalidCommandTimeout(value); @@ -808,7 +811,7 @@ override public CommandType CommandType } set { - SqlClientEventSource.Log.TraceEvent(" {0}, {1}{2}", ObjectID, (int)value, _commandType); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}{2}", ObjectID, (int)value, _commandType); if (_commandType != value) { switch (value) @@ -951,7 +954,7 @@ internal void OnStatementCompleted(int recordCount) { try { - SqlClientEventSource.Log.TraceEvent(" {0}, recordCount={1}", ObjectID, recordCount); + SqlClientEventSource.Log.TryTraceEvent(" {0}, recordCount={1}", ObjectID, recordCount); handler(this, new StatementCompletedEventArgs(recordCount)); } catch (Exception e) @@ -989,8 +992,8 @@ override public void Prepare() } SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); statistics = SqlStatistics.StartTimer(Statistics); @@ -1092,7 +1095,7 @@ override public void Prepare() } SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } private void InternalPrepare() @@ -1156,7 +1159,7 @@ internal void Unprepare() } _cachedMetaData = null; - SqlClientEventSource.Log.TraceEvent(" {0}, Command unprepared.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command unprepared.", ObjectID); } // Cancel is supposed to be multi-thread safe. @@ -1166,8 +1169,8 @@ internal void Unprepare() /// override public void Cancel() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); SqlStatistics statistics = null; try @@ -1286,7 +1289,7 @@ override public void Cancel() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1329,8 +1332,8 @@ override public object ExecuteScalar() _pendingCancel = false; SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); bool success = false; int? sqlExceptionNumber = null; @@ -1353,7 +1356,7 @@ override public object ExecuteScalar() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1399,8 +1402,8 @@ override public int ExecuteNonQuery() SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); bool success = false; int? sqlExceptionNumber = null; @@ -1421,7 +1424,7 @@ override public int ExecuteNonQuery() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -1437,7 +1440,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) _pendingCancel = false; SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -1447,7 +1450,7 @@ internal void ExecuteToPipe(SmiContext pipeContext) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1463,7 +1466,7 @@ public IAsyncResult BeginExecuteNonQuery() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); SqlConnection.ExecutePermission.Demand(); return BeginExecuteNonQueryInternal(0, callback, stateObject, 0, inRetry: false); } @@ -1689,7 +1692,7 @@ public int EndExecuteNonQuery(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); } } @@ -1707,7 +1710,7 @@ private void ThrowIfReconnectionHasBeenCanceled() private int EndExecuteNonQueryAsync(IAsyncResult asyncResult) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -1969,7 +1972,7 @@ private Task InternalExecuteNonQuery(TaskCompletionSource completion, st { // otherwise, use a full-fledged execute that can handle params and stored procs Debug.Assert(!sendToPipe, "trying to send non-context command to pipe"); - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as RPC.", ObjectID); SqlDataReader reader = RunExecuteReader(0, RunBehavior.UntilDone, false, methodName, completion, timeout, out task, out usedCache, asyncWrite, inRetry); if (null != reader) @@ -2023,8 +2026,8 @@ public XmlReader ExecuteXmlReader() SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); bool success = false; int? sqlExceptionNumber = null; @@ -2048,7 +2051,7 @@ public XmlReader ExecuteXmlReader() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); WriteEndExecuteEvent(success, sqlExceptionNumber, synchronous: true); } } @@ -2065,7 +2068,7 @@ public IAsyncResult BeginExecuteXmlReader() [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteXmlReader(AsyncCallback callback, object stateObject) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); SqlConnection.ExecutePermission.Demand(); return BeginExecuteXmlReaderInternal(CommandBehavior.SequentialAccess, callback, stateObject, 0, inRetry: false); } @@ -2218,13 +2221,13 @@ public XmlReader EndExecuteXmlReader(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); } } private XmlReader EndExecuteXmlReaderAsync(IAsyncResult asyncResult) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2343,7 +2346,7 @@ public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObjec /// override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); return ExecuteReader(behavior, ADP.ExecuteReader); } @@ -2351,8 +2354,8 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) new public SqlDataReader ExecuteReader() { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { statistics = SqlStatistics.StartTimer(Statistics); @@ -2361,15 +2364,15 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } /// new public SqlDataReader ExecuteReader(CommandBehavior behavior) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, behavior={1}", ObjectID, (int)behavior); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, behavior={1}", ObjectID, (int)behavior); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); try { @@ -2377,7 +2380,7 @@ override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -2392,7 +2395,7 @@ public IAsyncResult BeginExecuteReader(CommandBehavior behavior) [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public IAsyncResult BeginExecuteReader(AsyncCallback callback, object stateObject, CommandBehavior behavior) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); SqlConnection.ExecutePermission.Demand(); return BeginExecuteReaderInternal(behavior, callback, stateObject, 0, inRetry: false); } @@ -2473,13 +2476,13 @@ public SqlDataReader EndExecuteReader(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); } } private SqlDataReader EndExecuteReaderAsync(IAsyncResult asyncResult) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); Debug.Assert(!_internalEndExecuteInitiated || _stateObj == null); Exception asyncException = ((Task)asyncResult).Exception; @@ -2881,7 +2884,7 @@ private SqlDataReader InternalEndExecuteReader(IAsyncResult asyncResult, string /// public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -2966,7 +2969,7 @@ protected override Task ExecuteDbDataReaderAsync(CommandBehavior b /// new public Task ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, behavior={1}, ActivityID {2}", ObjectID, (int)behavior, ActivityCorrelator.Current); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3100,7 +3103,7 @@ public Task ExecuteXmlReaderAsync() /// public Task ExecuteXmlReaderAsync(CancellationToken cancellationToken) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); SqlConnection.ExecutePermission.Demand(); TaskCompletionSource source = new TaskCompletionSource(); @@ -3706,7 +3709,7 @@ private Task RunExecuteNonQueryTds(string methodName, bool async, int timeout, b // no parameters are sent over // no data reader is returned // use this overload for "batch SQL" tds token type - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); Task executeTask = _stateObj.Parser.TdsExecuteSQLBatch(this.CommandText, timeout, this.Notification, _stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -3768,7 +3771,7 @@ private void RunExecuteNonQuerySmi(bool sendToPipe) SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, innerConnection={1}, transactionId=0x{2}, cmdBehavior={3}.", ObjectID, innerConnection.ObjectID, transactionId, (int)CommandBehavior.Default); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, innerConnection={1}, transactionId=0x{2}, cmdBehavior={3}.", ObjectID, innerConnection.ObjectID, transactionId, (int)CommandBehavior.Default); if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { @@ -5250,7 +5253,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi Debug.Assert(!IsUserPrepared, "CommandType.Text with no params should not be prepared!"); if (returnStream) { - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as SQLBATCH.", ObjectID); } string text = GetCommandText(cmdBehavior) + GetResetOptionsString(cmdBehavior); @@ -5315,7 +5318,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi rpc.options = TdsEnums.RPC_NOMETADATA; if (returnStream) { - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as RPC.", ObjectID); } // TODO: Medusa: Unprepare only happens for SQL 7.0 which may be broken anyway (it's not re-prepared). Consider removing the reset here if we're really dropping 7.0 support. @@ -5338,7 +5341,7 @@ private SqlDataReader RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavi optionSettings = GetSetOptionsString(cmdBehavior); if (returnStream) { - SqlClientEventSource.Log.TraceEvent(" {0}, Command executed as RPC.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Command executed as RPC.", ObjectID); } // turn set options ON @@ -5433,7 +5436,7 @@ private SqlDataReader RunExecuteReaderSmi(CommandBehavior cmdBehavior, RunBehavi long transactionId; SysTx.Transaction transaction; innerConnection.GetCurrentTransactionPair(out transactionId, out transaction); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, innerConnection={1}, transactionId=0x{2}, commandBehavior={(int)cmdBehavior}.", ObjectID, innerConnection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, innerConnection={1}, transactionId=0x{2}, commandBehavior={(int)cmdBehavior}.", ObjectID, innerConnection.ObjectID, transactionId); if (SmiContextFactory.Instance.NegotiatedSmiVersion >= SmiContextFactory.KatmaiVersion) { @@ -5653,7 +5656,7 @@ private void NotifyDependency() public SqlCommand Clone() { SqlCommand clone = new SqlCommand(this); - SqlClientEventSource.Log.TraceEvent(" {0}, clone={1}", ObjectID, clone.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, clone={1}", ObjectID, clone?.ObjectID); return clone; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs index 7f833e8907..6c5c3a306a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlCommandSet.cs @@ -129,7 +129,7 @@ internal int ObjectID internal void Append(SqlCommand command) { ADP.CheckArgumentNull(command, "command"); - SqlClientEventSource.Log.TraceEvent(" {0}, command={1}, parameterCount={2}", ObjectID, command.ObjectID, command.Parameters.Count); + SqlClientEventSource.Log.TryTraceEvent(" {0}, command={1}, parameterCount={2}", ObjectID, command.ObjectID, command.Parameters.Count); string cmdText = command.CommandText; if (ADP.IsEmpty(cmdText)) @@ -264,7 +264,7 @@ internal static void BuildStoredProcedureName(StringBuilder builder, string part internal void Clear() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); DbCommand batchCommand = BatchCommand; if (null != batchCommand) { @@ -280,7 +280,7 @@ internal void Clear() internal void Dispose() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); SqlCommand command = _batchCommand; _commandList = null; _batchCommand = null; @@ -294,7 +294,7 @@ internal void Dispose() internal int ExecuteNonQuery() { SqlConnection.ExecutePermission.Demand(); - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { @@ -315,7 +315,7 @@ internal int ExecuteNonQuery() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs index 8181a4e27d..491ff0cc0a 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs @@ -1196,7 +1196,7 @@ public SqlTransaction BeginTransaction(string transactionName) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, isolationLevel={1}", ObjectID, (int)isolationLevel); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, isolationLevel={1}", ObjectID, (int)isolationLevel); try { @@ -1212,7 +1212,7 @@ override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLeve } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1221,7 +1221,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam { WaitForPendingReconnection(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, iso={1}, transactionName='{2}'", ObjectID, (int)iso, (ADP.IsEmpty(transactionName) ? "None" : transactionName)); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, iso={1}, transactionName='{2}'", ObjectID, (int)iso, transactionName); try { @@ -1249,7 +1249,7 @@ public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionNam } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); SqlStatistics.StopTimer(statistics); } } @@ -1259,7 +1259,7 @@ override public void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -1353,8 +1353,8 @@ void CloseInnerConnection() /// override public void Close() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { @@ -1438,7 +1438,7 @@ override public void Close() SqlDebugContext sdc = _sdc; _sdc = null; - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); if (sdc != null) { @@ -1498,8 +1498,8 @@ override public void Open() /// public void Open(SqlConnectionOverrides overrides) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { @@ -1533,7 +1533,7 @@ public void Open(SqlConnectionOverrides overrides) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1567,7 +1567,7 @@ private async Task ReconnectAsync(int timeout) { if (ctoken.IsCancellationRequested) { - SqlClientEventSource.Log.TraceEvent(" Original ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Original ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId); return; } try @@ -1589,15 +1589,15 @@ private async Task ReconnectAsync(int timeout) ForceNewConnection = false; } - SqlClientEventSource.Log.TraceEvent(" Reconnection succeeded. ClientConnectionID {0} -> {1}", _originalConnectionId.ToString(), ClientConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Reconnection succeeded. ClientConnectionID {0} -> {1}", _originalConnectionId, ClientConnectionId); return; } catch (SqlException e) { - SqlClientEventSource.Log.TraceEvent(" Original ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message); + SqlClientEventSource.Log.TryTraceEvent(" Original ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message); if (attempt == retryCount - 1) { - SqlClientEventSource.Log.TraceEvent(" Original ClientConnectionID {0} - give up reconnection", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Original ClientConnectionID {0} - give up reconnection", _originalConnectionId); throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) @@ -1664,7 +1664,7 @@ internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; - SqlClientEventSource.Log.TraceEvent(" Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId); _recoverySessionData = cData; if (beforeDisconnect != null) @@ -1757,8 +1757,8 @@ void CancelOpenAndWait() /// public override Task OpenAsync(CancellationToken cancellationToken) { - long scopeID = SqlClientEventSource.Log.PoolerScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryPoolerScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); try { @@ -1835,7 +1835,7 @@ public override Task OpenAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.PoolerScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryPoolerScopeLeaveEvent(scopeID); } } @@ -1856,7 +1856,7 @@ public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource retryTask) { - SqlClientEventSource.Log.TraceEvent(" {0}", _parent.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", _parent.ObjectID); _registration.Dispose(); try @@ -2213,7 +2213,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {0}, Connection broken.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection broken.", ObjectID); Close(); } }; @@ -2222,7 +2222,7 @@ internal void OnError(SqlException exception, bool breakConnection, Action {0}, Connection broken.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection broken.", ObjectID); Close(); } } @@ -2330,7 +2330,7 @@ internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) Debug.Assert(null != imevent, "null SqlInfoMessageEventArgs"); var imeventValue = (null != imevent) ? imevent.Message : ""; - SqlClientEventSource.Log.TraceEvent(" {0}, Message='{1}'", ObjectID, imeventValue); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Message='{1}'", ObjectID, imeventValue); SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage]; if (null != handler) @@ -2544,8 +2544,8 @@ private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, s /// public static void ChangePassword(string connectionString, string newPassword) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); - SqlClientEventSource.Log.CorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(""); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); try { @@ -2585,15 +2585,15 @@ public static void ChangePassword(string connectionString, string newPassword) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } /// public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(""); - SqlClientEventSource.Log.CorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(""); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ActivityID {0}", ActivityCorrelator.Current); try { @@ -2655,7 +2655,7 @@ public static void ChangePassword(string connectionString, SqlCredential credent } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -2774,7 +2774,7 @@ private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError) { if (asmRef.Version != TypeSystemAssemblyVersion && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.TraceEvent(" SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version.ToString(), TypeSystemAssemblyVersion.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version, TypeSystemAssemblyVersion); } asmRef.Version = TypeSystemAssemblyVersion; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs index ba0c018224..2c56d89165 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionFactory.cs @@ -192,7 +192,7 @@ override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions { connectionTimeout *= 10; } - SqlClientEventSource.Log.TraceEvent("Set connection pool CreateTimeout={0} when AD Interactive is in use.", connectionTimeout); + SqlClientEventSource.Log.TryTraceEvent("Set connection pool CreateTimeout={0} when AD Interactive is in use.", connectionTimeout); } poolingOptions = new DbConnectionPoolGroupOptions( diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs index 767f5d97db..24071a3db1 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionPoolGroupProviderInfo.cs @@ -55,7 +55,7 @@ internal void AliasCheck(string server) } else if (_alias != server) { - SqlClientEventSource.Log.TraceEvent(" alias change detected. Clearing PoolGroup"); + SqlClientEventSource.Log.TryTraceEvent(" alias change detected. Clearing PoolGroup"); base.PoolGroup.Clear(); _alias = server; } @@ -99,7 +99,7 @@ internal void FailoverCheck(SqlInternalConnection connection, bool actualUseFail if (UseFailoverPartner != actualUseFailoverPartner) { // TODO: will connections in progress somehow be active for two different datasources? - SqlClientEventSource.Log.TraceEvent(" Failover detected. failover partner='{0}'. Clearing PoolGroup", actualFailoverPartner); + SqlClientEventSource.Log.TryTraceEvent(" Failover detected. failover partner='{0}'. Clearing PoolGroup", actualFailoverPartner); base.PoolGroup.Clear(); _useFailoverPartner = actualUseFailoverPartner; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs index 5fbb147c37..68da2c6f4e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataAdapter.cs @@ -142,7 +142,7 @@ override public int UpdateBatchSize throw ADP.ArgumentOutOfRange("UpdateBatchSize"); } _updateBatchSize = value; - SqlClientEventSource.Log.TraceEvent(" {0}, {1}", ObjectID, value); + SqlClientEventSource.Log.TryTraceEvent(" {0}, {1}", ObjectID, value); } } @@ -249,7 +249,7 @@ override protected RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, override protected int ExecuteBatch() { Debug.Assert(null != _commandSet && (0 < _commandSet.CommandCount), "no commands"); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); return _commandSet.ExecuteNonQuery(); } @@ -273,7 +273,7 @@ override protected bool GetBatchedRecordsAffected(int commandIdentifier, out int /// override protected void InitializeBatching() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); _commandSet = new SqlCommandSet(); SqlCommand command = SelectCommand; if (null == command) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs index c29b521eef..176b3ddf3c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReader.cs @@ -939,7 +939,7 @@ private void CleanPartialReadReliable() override public void Close() { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { @@ -1026,7 +1026,7 @@ override public void Close() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -1670,7 +1670,7 @@ override public int GetProviderSpecificValues(object[] values) override public DataTable GetSchemaTable() { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { @@ -1688,7 +1688,7 @@ override public DataTable GetSchemaTable() finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -3596,7 +3596,7 @@ override public bool NextResult() private bool TryNextResult(out bool more) { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -3774,7 +3774,7 @@ private bool TryNextResult(out bool more) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -3802,7 +3802,7 @@ override public bool Read() private bool TryReadInternal(bool setTimeout, out bool more) { SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -4004,7 +4004,7 @@ private bool TryReadInternal(bool setTimeout, out bool more) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -4469,7 +4469,7 @@ private void RestoreServerSettings(TdsParser parser, TdsParserStateObject stateO // broken connection, so check state first. if (parser.State == TdsParserState.OpenLoggedIn) { - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID '{1}'", ObjectID, ActivityCorrelator.Current); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID '{1}'", ObjectID, ActivityCorrelator.Current); Task executeTask = parser.TdsExecuteSQLBatch(_resetOptionsString, (_command != null) ? _command.CommandTimeout : 0, null, stateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); @@ -4781,7 +4781,7 @@ private void AssertReaderState(bool requireData, bool permitAsync, int? columnIn /// public override Task NextResultAsync(CancellationToken cancellationToken) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { @@ -4827,7 +4827,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) { if (t != null) { - SqlClientEventSource.Log.TraceEvent(" attempt retry {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" attempt retry {0}", ObjectID); PrepareForAsyncContinuation(); } @@ -4845,7 +4845,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -4909,7 +4909,7 @@ internal Task GetBytesAsync(int i, byte[] buffer, int index, int length, in { if (t != null) { - SqlClientEventSource.Log.TraceEvent(" attempt retry {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" attempt retry {0}", ObjectID); PrepareForAsyncContinuation(); } @@ -5080,7 +5080,7 @@ private Task GetBytesAsyncReadDataStage(int i, byte[] buffer, int index, in /// public override Task ReadAsync(CancellationToken cancellationToken) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); try { if (IsClosed) @@ -5200,7 +5200,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) { if (t != null) { - SqlClientEventSource.Log.TraceEvent(" attempt retry {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" attempt retry {0}", ObjectID); PrepareForAsyncContinuation(); } @@ -5239,7 +5239,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs index bc5d483954..50fd5e0746 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDataReaderSmi.cs @@ -374,7 +374,7 @@ public override void Close() private void CloseInternal(bool closeConnection) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); bool processFinallyBlock = true; try { @@ -410,7 +410,7 @@ private void CloseInternal(bool closeConnection) Connection.Close(); } - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } } @@ -433,7 +433,7 @@ public override Task NextResultAsync(CancellationToken cancellationToken) internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) { - long scopeID = SqlClientEventSource.Log.AdvancedScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryAdvancedScopeEnterEvent(" {0}", ObjectID); try { _hasRows = false; @@ -466,7 +466,7 @@ internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) } finally { - SqlClientEventSource.Log.AdvanceScopeLeave(scopeID); + SqlClientEventSource.Log.TryAdvanceScopeLeave(scopeID); } } @@ -486,7 +486,7 @@ public override Task ReadAsync(CancellationToken cancellationToken) internal unsafe bool InternalRead(bool ignoreNonFatalErrors) { - long scopeID = SqlClientEventSource.Log.AdvancedScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryAdvancedScopeEnterEvent(" {0}", ObjectID); try { // Don't move unless currently in results. @@ -525,7 +525,7 @@ internal unsafe bool InternalRead(bool ignoreNonFatalErrors) } finally { - SqlClientEventSource.Log.AdvanceScopeLeave(scopeID); + SqlClientEventSource.Log.TryAdvanceScopeLeave(scopeID); } } @@ -1316,7 +1316,7 @@ internal ReaderEventSink(SqlDataReaderSmi reader, SmiEventSink parent) internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIsRow) { var mdLength = (null != md) ? md.Length : -1; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, md.Length={1} nextEventIsRow={2}.", reader.ObjectID, mdLength, nextEventIsRow); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, md.Length={1} nextEventIsRow={2}.", reader.ObjectID, mdLength, nextEventIsRow); if (SqlClientEventSource.Log.IsAdvancedTraceOn()) { @@ -1324,7 +1324,7 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs { for (int i = 0; i < md.Length; i++) { - SqlClientEventSource.Log.TraceEvent(" {0}, metaData[{1}] is {2}{3}", reader.ObjectID, i, md[i].GetType().ToString(), md[i].TraceString()); + SqlClientEventSource.Log.TraceEvent(" {0}, metaData[{1}] is {2}{3}", reader.ObjectID, i, md[i].GetType(), md[i].TraceString()); } } } @@ -1334,25 +1334,25 @@ internal override void MetaDataAvailable(SmiQueryMetaData[] md, bool nextEventIs // Obsolete V2- method internal override void RowAvailable(ITypedGetters row) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} (v2).", reader.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} (v2).", reader.ObjectID); this.reader.RowAvailable(row); } internal override void RowAvailable(ITypedGettersV3 row) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} (ITypedGettersV3).", reader.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} (ITypedGettersV3).", reader.ObjectID); this.reader.RowAvailable(row); } internal override void RowAvailable(SmiTypedGetterSetter rowData) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} (SmiTypedGetterSetter).", reader.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} (SmiTypedGetterSetter).", reader.ObjectID); this.reader.RowAvailable(rowData); } internal override void StatementCompleted(int recordsAffected) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} recordsAffected= {1}.", reader.ObjectID, recordsAffected); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} recordsAffected= {1}.", reader.ObjectID, recordsAffected); // devnote: relies on SmiEventSink_Default to pass event to parent // Both command and reader care about StatementCompleted, but for different reasons. @@ -1362,7 +1362,7 @@ internal override void StatementCompleted(int recordsAffected) internal override void BatchCompleted() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}.", reader.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}.", reader.ObjectID); // devnote: relies on SmiEventSink_Default to pass event to parent // parent's callback *MUST* come before reader's BatchCompleted, since diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs index ef597d5fcd..082de06d3f 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDelegatedTransaction.cs @@ -88,7 +88,7 @@ public void Initialize() // transaction. SqlInternalConnection connection = _connection; SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, delegating transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, delegating transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -105,7 +105,7 @@ public void Initialize() #endif //DEBUG if (connection.IsEnlistedInTransaction) { - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, was enlisted, now defecting.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, was enlisted, now defecting.", ObjectID, connection.ObjectID); // defect first connection.EnlistNull(); @@ -169,7 +169,7 @@ public Byte[] Promote() if (null != connection) { SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, promoting transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, promoting transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -262,13 +262,13 @@ public Byte[] Promote() else { // The transaction was aborted externally, since it's already doomed above, we only log the same. - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, aborted during promote.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, aborted during promote.", ObjectID, connection.ObjectID); } } else { // The transaction was aborted externally, doom the connection to make sure it's eventually rolled back and log the same. - SqlClientEventSource.Log.TraceEvent(" {0}, Connection null, aborted before promoting.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection null, aborted before promoting.", ObjectID); } return returnValue; } @@ -287,7 +287,7 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) #endif //DEBUG SqlConnection usersConnection = connection.Connection; RuntimeHelpers.PrepareConstrainedRegions(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, rolling back transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, rolling back transaction.", ObjectID, connection.ObjectID); try { lock (connection) @@ -364,7 +364,7 @@ public void Rollback(SysTx.SinglePhaseEnlistment enlistment) { // The transaction was aborted, report that to SysTx and log the same. enlistment.Aborted(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection null, aborted before rollback.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection null, aborted before rollback.", ObjectID); } } @@ -378,7 +378,7 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) if (null != connection) { SqlConnection usersConnection = connection.Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, committing transaction.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, committing transaction.", ObjectID, connection.ObjectID); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -501,7 +501,7 @@ public void SinglePhaseCommit(SysTx.SinglePhaseEnlistment enlistment) { // The transaction was aborted before we could commit, report that to SysTx and log the same. enlistment.Aborted(); - SqlClientEventSource.Log.TraceEvent(" {0}, Connection null, aborted before commit.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection null, aborted before commit.", ObjectID); } } @@ -515,7 +515,7 @@ internal void TransactionEnded(SysTx.Transaction transaction) if (connection != null) { - SqlClientEventSource.Log.TraceEvent(" {0}, Connection {1}, transaction completed externally.", ObjectID, connection.ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Connection {1}, transaction completed externally.", ObjectID, connection.ObjectID); lock (connection) { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs index 89fab12b93..52bcec0599 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -339,7 +339,7 @@ public SqlDependency(SqlCommand command) : this(command, null, SQL.SqlDependency [System.Security.Permissions.HostProtectionAttribute(ExternalThreading = true)] public SqlDependency(SqlCommand command, string options, int timeout) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, options: '{1}', timeout: '{2}'", ObjectID, options, timeout); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, options: '{1}', timeout: '{2}'", ObjectID, options, timeout); try { if (InOutOfProcHelper.InProc) @@ -362,7 +362,7 @@ public SqlDependency(SqlCommand command, string options, int timeout) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -459,7 +459,7 @@ public event OnChangeEventHandler OnChange // EventHandlers to be fired when dependency is notified. add { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { @@ -472,12 +472,12 @@ public event OnChangeEventHandler OnChange if (_dependencyFired) { // If fired, fire the new event immediately. - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency already fired, firing new event."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency already fired, firing new event."); sqlNotificationEvent = new SqlNotificationEventArgs(SqlNotificationType.Subscribe, SqlNotificationInfo.AlreadyChanged, SqlNotificationSource.Client); } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency has not fired, adding new event."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency has not fired, adding new event."); EventContextPair pair = new EventContextPair(value, this); if (!_eventList.Contains(pair)) { @@ -498,12 +498,12 @@ public event OnChangeEventHandler OnChange } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } remove { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { if (null != value) @@ -521,7 +521,7 @@ public event OnChangeEventHandler OnChange } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } @@ -538,7 +538,7 @@ public void AddCommandDependency(SqlCommand command) { // Adds command to dependency collection so we automatically create the SqlNotificationsRequest object // and listen for a notification for the added commands. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { if (command == null) @@ -550,7 +550,7 @@ public void AddCommandDependency(SqlCommand command) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -576,10 +576,10 @@ private static void ObtainProcessDispatcher() if (nativeStorage == null) { - SqlClientEventSource.Log.NotificationTraceEvent(" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" nativeStorage null, obtaining dispatcher AppDomain and creating ProcessDispatcher."); #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource.Log.NotificationTraceEvent(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); #endif _AppDomain masterDomain = SNINativeMethodWrapper.GetDefaultAppDomain(); @@ -605,33 +605,33 @@ private static void ObtainProcessDispatcher() } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - ObjectHandle.Unwrap returned null!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - ObjectHandle.Unwrap returned null!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyObtainProcessDispatcherFailureObjectHandle); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - AppDomain.CreateInstance returned null!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - AppDomain.CreateInstance returned null!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureCreateInstance); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - unable to obtain default AppDomain!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - unable to obtain default AppDomain!"); throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureAppDomain); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" nativeStorage not null, obtaining existing dispatcher AppDomain and ProcessDispatcher."); #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource.Log.NotificationTraceEvent(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); #endif BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(nativeStorage); _processDispatcher = GetDeserializedObject(formatter, stream); // Deserialize and set for appdomain. - SqlClientEventSource.Log.NotificationTraceEvent(" processDispatcher obtained, ID: {0}", _processDispatcher.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" processDispatcher obtained, ID: {0}", _processDispatcher.ObjectID); } } @@ -680,7 +680,7 @@ public static bool Start(string connectionString, string queue) internal static bool Start(string connectionString, string queue, bool useDefaults) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -754,7 +754,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul out errorOccurred, out appDomainStart); - SqlClientEventSource.Log.NotificationTraceEvent(" Start (defaults) returned: '{0}', with service: '{1}', server: '{2}', database: '{3}'", result, service, server, database); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Start (defaults) returned: '{0}', with service: '{1}', server: '{2}', database: '{3}'", result, service, server, database); } finally { @@ -776,7 +776,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - SqlClientEventSource.Log.NotificationTraceEvent(" Exception occurred from Stop() after duplicate was found on Start()."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception occurred from Stop() after duplicate was found on Start()."); } throw SQL.SqlDependencyDuplicateStart(); } @@ -789,7 +789,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul queue, _appDomainKey, SqlDependencyPerAppDomainDispatcher.SingletonInstance); - SqlClientEventSource.Log.NotificationTraceEvent(" Start (user provided queue) returned: '{0}'", result); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Start (user provided queue) returned: '{0}'", result); // No need to call AddToServerDatabaseHash since if not using default queue user is required // to provide options themselves. @@ -804,7 +804,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now. - SqlClientEventSource.Log.NotificationTraceEvent(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception occurred from _processDispatcher.Start(...), calling Invalidate(...)."); throw; } } @@ -813,7 +813,7 @@ internal static bool Start(string connectionString, string queue, bool useDefaul } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -833,7 +833,7 @@ public static bool Stop(string connectionString, string queue) internal static bool Stop(string connectionString, string queue, bool useDefaults, bool startFailed) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" AppDomainKey: '{0}', queue: '{1}'", AppDomainKey, queue); try { // The following code exists in Stop as well. It exists here to demand permissions as high in the stack @@ -943,7 +943,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -953,7 +953,7 @@ internal static bool Stop(string connectionString, string queue, bool useDefault private static bool AddToServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); try { bool result = false; @@ -964,7 +964,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!_serverUserHash.ContainsKey(server)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Hash did not contain server, adding."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Hash did not contain server, adding."); identityDatabaseHash = new Dictionary>(); _serverUserHash.Add(server, identityDatabaseHash); } @@ -977,7 +977,7 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!identityDatabaseHash.ContainsKey(identityUser)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Hash contained server but not user, adding user."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Hash contained server but not user, adding user."); databaseServiceList = new List(); identityDatabaseHash.Add(identityUser, databaseServiceList); } @@ -988,13 +988,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden if (!databaseServiceList.Contains(databaseService)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Adding database."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Adding database."); databaseServiceList.Add(databaseService); result = true; } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash already contained server, user, and database - we will throw!."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash already contained server, user, and database - we will throw!."); } } @@ -1002,13 +1002,13 @@ private static bool AddToServerUserHash(string server, IdentityUserNamePair iden } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private static void RemoveFromServerUserHash(string server, IdentityUserNamePair identityUser, DatabaseServicePair databaseService) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" server: '{0}', database: '{1}', service: '{2}'", server, databaseService.Database, databaseService.Service); try { lock (_serverUserHash) @@ -1028,43 +1028,43 @@ private static void RemoveFromServerUserHash(string server, IdentityUserNamePair int index = databaseServiceList.IndexOf(databaseService); if (index >= 0) { - SqlClientEventSource.Log.NotificationTraceEvent(" Hash contained server, user, and database - removing database."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Hash contained server, user, and database - removing database."); databaseServiceList.RemoveAt(index); if (databaseServiceList.Count == 0) { - SqlClientEventSource.Log.NotificationTraceEvent(" databaseServiceList count 0, removing the list for this server and user."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" databaseServiceList count 0, removing the list for this server and user."); identityDatabaseHash.Remove(identityUser); if (identityDatabaseHash.Count == 0) { - SqlClientEventSource.Log.NotificationTraceEvent(" identityDatabaseHash count 0, removing the hash for this server."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" identityDatabaseHash count 0, removing the hash for this server."); _serverUserHash.Remove(server); } } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash contained server and user but not database!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash contained server and user but not database!"); Debug.Assert(false, "Unexpected state - hash did not contain database!"); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash contained server but not user!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash contained server but not user!"); Debug.Assert(false, "Unexpected state - hash did not contain user!"); } } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - hash did not contain server!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - hash did not contain server!"); Debug.Assert(false, "Unexpected state - hash did not contain server!"); } } } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1072,7 +1072,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { // Server must be an exact match, but user and database only needs to match exactly if there is more than one // for the given user or database passed. That is ambiguious and we must fail. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" server: '{0}', failoverServer: '{1}', database: '{2}'", server, failoverServer, database); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" server: '{0}', failoverServer: '{1}', database: '{2}'", server, failoverServer, database); try { @@ -1085,17 +1085,17 @@ internal static string GetDefaultComposedOptions(string server, string failoverS if (0 == _serverUserHash.Count) { // Special error for no calls to start. - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - no start calls have been made, about to throw."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - no start calls have been made, about to throw."); throw SQL.SqlDepDefaultOptionsButNoStart(); } else if (!ADP.IsEmpty(failoverServer) && _serverUserHash.ContainsKey(failoverServer)) { - SqlClientEventSource.Log.NotificationTraceEvent(" using failover server instead\n"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" using failover server instead\n"); server = failoverServer; } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - not listening to this server, about to throw."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - not listening to this server, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } } @@ -1108,7 +1108,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS { if (identityDatabaseHash.Count > 1) { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - not listening for this user, " + + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - not listening for this user, " + "but listening to more than one other user, about to throw."); throw SQL.SqlDependencyNoMatchingServerStart(); } @@ -1156,19 +1156,19 @@ internal static string GetDefaultComposedOptions(string server, string failoverS else { // More than one database for given server, ambiguous - fail the default case! - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - SqlDependency.Start called multiple times for this server/user, but no matching database."); throw SQL.SqlDependencyNoMatchingServerDatabaseStart(); } } } Debug.Assert(!ADP.IsEmpty(result), "GetDefaultComposedOptions should never return null or empty string!"); - SqlClientEventSource.Log.NotificationTraceEvent(" resulting options: '{0}'.", result); + SqlClientEventSource.Log.TryNotificationTraceEvent(" resulting options: '{0}'.", result); return result; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1180,7 +1180,7 @@ internal static string GetDefaultComposedOptions(string server, string failoverS // use this list for a reverse lookup based on server. internal void AddToServerList(string server) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); try { lock (_serverList) @@ -1189,7 +1189,7 @@ internal void AddToServerList(string server) if (0 > index) { // If less than 0, item was not found in list. - SqlClientEventSource.Log.NotificationTraceEvent(" Server not present in hashtable, adding server: '{0}'.", server); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Server not present in hashtable, adding server: '{0}'.", server); index = ~index; // BinarySearch returns the 2's compliment of where the item should be inserted to preserver a sorted list after insertion. _serverList.Insert(index, server); } @@ -1197,7 +1197,7 @@ internal void AddToServerList(string server) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1211,7 +1211,7 @@ internal bool ContainsServer(string server) internal string ComputeHashAndAddToDispatcher(SqlCommand command) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, command.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, command.ObjectID); try { // Create a string representing the concatenation of the connection string, command text and .ToString on all parameter values. @@ -1226,18 +1226,18 @@ internal string ComputeHashAndAddToDispatcher(SqlCommand command) string commandHash = ComputeCommandHash(command.Connection.ConnectionString, command); // calculate the string representation of command string idString = SqlDependencyPerAppDomainDispatcher.SingletonInstance.AddCommandEntry(commandHash, this); // Add to map. - SqlClientEventSource.Log.NotificationTraceEvent(" computed id string: '{0}'.", idString); + SqlClientEventSource.Log.TryNotificationTraceEvent(" computed id string: '{0}'.", idString); return idString; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, SqlNotificationSource source) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { List eventList = null; @@ -1255,12 +1255,12 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql // raises Timeout event but before removing this event from the list. If notification is received from // server in this case, we will hit this code path. // It is safe to ignore this race condition because no event is sent to user and no leak happens. - SqlClientEventSource.Log.NotificationTraceEvent(" ignore notification received after timeout!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ignore notification received after timeout!"); } else { Debug.Assert(false, "Received notification twice - we should never enter this state!"); - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - notification received twice - we should never enter this state!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - notification received twice - we should never enter this state!"); } } else @@ -1274,7 +1274,7 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql if (eventList != null) { - SqlClientEventSource.Log.NotificationTraceEvent(" Firing events."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Firing events."); foreach (EventContextPair pair in eventList) { pair.Invoke(new SqlNotificationEventArgs(type, info, source)); @@ -1283,19 +1283,19 @@ internal void Invalidate(SqlNotificationType type, SqlNotificationInfo info, Sql } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is used by SqlCommand. internal void StartTimer(SqlNotificationRequest notificationRequest) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { if (_expirationTime == DateTime.MaxValue) { - SqlClientEventSource.Log.NotificationTraceEvent(" We've timed out, executing logic."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" We've timed out, executing logic."); int seconds = SQL.SqlDependencyServerTimeout; if (0 != _timeout) { @@ -1313,7 +1313,7 @@ internal void StartTimer(SqlNotificationRequest notificationRequest) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1326,7 +1326,7 @@ private void AddCommandInternal(SqlCommand cmd) if (cmd != null) { // Don't bother with BID if command null. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, cmd.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, cmd.ObjectID); try { SqlConnection connection = cmd.Connection; @@ -1336,7 +1336,7 @@ private void AddCommandInternal(SqlCommand cmd) // Fail if cmd has notification that is not already associated with this dependency. if (cmd._sqlDep == null || cmd._sqlDep != this) { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - throwing command has existing SqlNotificationRequest exception."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - throwing command has existing SqlNotificationRequest exception."); throw SQL.SqlCommandHasExistingSqlNotificationRequest(); } } @@ -1368,7 +1368,7 @@ private void AddCommandInternal(SqlCommand cmd) if (0 == _eventList.Count) { // Keep logic just in case. - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - firing events, though it is unexpected we have events at this point."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - firing events, though it is unexpected we have events at this point."); needToInvalidate = true; // Delay invalidation until outside of lock. } } @@ -1382,14 +1382,14 @@ private void AddCommandInternal(SqlCommand cmd) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } private string ComputeCommandHash(string connectionString, SqlCommand command) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, command.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlCommand: {1}", ObjectID, command.ObjectID); try { // Create a string representing the concatenation of the connection string, the command text and .ToString on all its parameter values. @@ -1446,12 +1446,12 @@ private string ComputeCommandHash(string connectionString, SqlCommand command) } string result = builder.ToString(); - SqlClientEventSource.Log.NotificationTraceEvent(" ComputeCommandHash result: '{0}'.", result); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ComputeCommandHash result: '{0}'.", result); return result; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs index 6566ee1c72..d05a0bb2b2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyListener.cs @@ -78,7 +78,7 @@ internal int ObjectID // ----------- internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, HashHelper?.Queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, HashHelper?.Queue); bool setupCompleted = false; try @@ -101,7 +101,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(_hashHelper.ConnectionStringBuilder.ConnectionString); - SqlClientEventSource.Log.NotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif // Always use ConnectionStringBuilder since in default case it is different from the @@ -216,7 +216,7 @@ internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, str } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -276,7 +276,7 @@ internal string Server // SqlDependencyProcessDispatcher.QueueAppDomainUnload on AppDomain.Unload. internal bool AppDomainUnload(string appDomainKey) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, AppDomainKey: '{1}'", ObjectID, appDomainKey); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, AppDomainKey: '{1}'", ObjectID, appDomainKey); try { Debug.Assert(!ADP.IsEmpty(appDomainKey), "Unexpected empty appDomainKey!"); @@ -288,9 +288,9 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { // Do nothing if AppDomain did not call Start! - SqlClientEventSource.Log.NotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}'.", appDomainKey); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}'.", appDomainKey); int value = _appDomainKeyHash[appDomainKey]; - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{0}' count: '{1}'.", appDomainKey, value); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash for AppDomainKey: '{0}' count: '{1}'.", appDomainKey, value); Debug.Assert(value > 0, "Why is value 0 or less?"); bool ignored = false; @@ -307,26 +307,26 @@ internal bool AppDomainUnload(string appDomainKey) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{0}' entry not removed from hash. Count: {1}'", appDomainKey, _appDomainKeyHash[appDomainKey]); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP|ERR> ERROR - after the Stop() loop, _appDomainKeyHash for AppDomainKey: '{0}' entry not removed from hash. Count: {1}'", appDomainKey, _appDomainKeyHash[appDomainKey]); } } else { - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{0}'.", appDomainKey); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> _appDomainKeyHash did not contain AppDomainKey: '{0}'.", appDomainKey); } } - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{0}'.", _stopped); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.AppDomainUnload|DEP> Exiting, _stopped: '{0}'.", _stopped); return _stopped; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void AsynchronouslyQueryServiceBrokerQueue() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { AsyncCallback callback = new AsyncCallback(AsyncResultCallback); @@ -334,13 +334,13 @@ private void AsynchronouslyQueryServiceBrokerQueue() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void AsyncResultCallback(IAsyncResult asyncResult) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { using (SqlDataReader reader = _com.EndExecuteReader(asyncResult)) @@ -366,7 +366,7 @@ private void AsyncResultCallback(IAsyncResult asyncResult) _errorState = true; throw; } - SqlClientEventSource.Log.NotificationTraceEvent(" Exception occurred."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception occurred."); if (!_stop) { // Only assert if not in cancel path. @@ -386,13 +386,13 @@ private void AsyncResultCallback(IAsyncResult asyncResult) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void CreateQueueAndService(bool restart) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { SqlCommand com = new SqlCommand(); @@ -522,18 +522,18 @@ private void CreateQueueAndService(bool restart) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { appDomainStart = false; // Reset out param. int result = Interlocked.Increment(ref _startCount); // Add to refCount. - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> {0}, incremented _startCount: {1}", _staticInstance.ObjectID, result); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> {0}, incremented _startCount: {1}", _staticInstance.ObjectID, result); // Dictionary used to track how many times start has been called per app domain. // For each increment, add to count, and create entry if not present. @@ -542,25 +542,25 @@ internal void IncrementStartCount(string appDomainKey, out bool appDomainStart) if (_appDomainKeyHash.ContainsKey(appDomainKey)) { _appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1; - SqlClientEventSource.Log.NotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{0}', incremented count: '{1}'.", appDomainKey, _appDomainKeyHash[appDomainKey]); + SqlClientEventSource.Log.TryNotificationTraceEvent("SqlConnectionContainer.IncrementStartCount|DEP> _appDomainKeyHash contained AppDomainKey: '{0}', incremented count: '{1}'.", appDomainKey, _appDomainKeyHash[appDomainKey]); } else { _appDomainKeyHash[appDomainKey] = 1; appDomainStart = true; - SqlClientEventSource.Log.NotificationTraceEvent(" _appDomainKeyHash did not contain AppDomainKey: '{0}', added to hashtable and value set to 1.", appDomainKey); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _appDomainKeyHash did not contain AppDomainKey: '{0}', added to hashtable and value set to 1.", appDomainKey); } } } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void ProcessNotificationResults(SqlDataReader reader) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { Guid handle = Guid.Empty; // Conversation_handle. Always close this! @@ -570,18 +570,18 @@ private void ProcessNotificationResults(SqlDataReader reader) { while (reader.Read()) { - SqlClientEventSource.Log.NotificationTraceEvent(" Row read."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Row read."); #if DEBUG if (SqlClientEventSource.Log.IsNotificationTraceEnabled()) { for (int i = 0; i < reader.FieldCount; i++) { - SqlClientEventSource.Log.NotificationTraceEvent(" column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i).ToString()); + SqlClientEventSource.Log.NotificationTraceEvent(" column: {0}, value: {1}", reader.GetName(i), reader.GetValue(i)); } } #endif string msgType = reader.GetString(0); - SqlClientEventSource.Log.NotificationTraceEvent(" msgType: '{0}'", msgType); + SqlClientEventSource.Log.TryNotificationTraceEvent(" msgType: '{0}'", msgType); handle = reader.GetGuid(1); // Only process QueryNotification messages. @@ -594,7 +594,7 @@ private void ProcessNotificationResults(SqlDataReader reader) if (null != notification) { string key = notification.Key; - SqlClientEventSource.Log.NotificationTraceEvent(" Key: '{0}'", key); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Key: '{0}'", key); int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash" if (index >= 0) @@ -623,25 +623,25 @@ private void ProcessNotificationResults(SqlDataReader reader) else { Debug.Assert(false, "Received notification but do not have an associated PerAppDomainDispatcher!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Received notification but do not have an associated PerAppDomainDispatcher!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Received notification but do not have an associated PerAppDomainDispatcher!"); } } else { Debug.Assert(false, "Unexpected ID format received!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Unexpected ID format received!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Unexpected ID format received!"); } } else { Debug.Assert(false, "Null notification returned from ProcessMessage!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Null notification returned from ProcessMessage!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Null notification returned from ProcessMessage!"); } } else { Debug.Assert(false, "Null payload for QN notification type!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Null payload for QN notification type!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Null payload for QN notification type!"); } } else @@ -649,7 +649,7 @@ private void ProcessNotificationResults(SqlDataReader reader) handle = Guid.Empty; // VSDD 546707: this assert was hit by SQL Notification fuzzing tests, disable it to let these tests run on Debug bits // Debug.Assert(false, "Unexpected message format received!"); - SqlClientEventSource.Log.NotificationTraceEvent(" Unexpected message format received!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Unexpected message format received!"); } } } @@ -681,7 +681,7 @@ private void ProcessNotificationResults(SqlDataReader reader) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -692,7 +692,7 @@ private void ProcessNotificationResults(SqlDataReader reader) private void Restart(object unused) { // Unused arg required by TimerCallback. - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { try @@ -854,13 +854,13 @@ private void Restart(object unused) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } internal bool Stop(string appDomainKey, out bool appDomainStop) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { appDomainStop = false; @@ -880,7 +880,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) int value = _appDomainKeyHash[appDomainKey]; Debug.Assert(value > 0, "Unexpected count for appDomainKey"); - SqlClientEventSource.Log.NotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}', pre-decrement Count: '{1}'.", appDomainKey, value); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _appDomainKeyHash contained AppDomainKey: '{0}', pre-decrement Count: '{1}'.", appDomainKey, value); if (value > 0) { @@ -888,7 +888,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR pre-decremented count <= 0!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR pre-decremented count <= 0!"); Debug.Assert(false, "Unexpected AppDomainKey count in Stop()"); } @@ -900,7 +900,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR appDomainKey not null and not found in hash!"); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR appDomainKey not null and not found in hash!"); Debug.Assert(false, "Unexpected state on Stop() - no AppDomainKey entry in hashtable!"); } } @@ -913,7 +913,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) { // If we've reached refCount 0, destroy. // Lock to ensure Cancel() complete prior to other thread calling TearDown. - SqlClientEventSource.Log.NotificationTraceEvent(" Reached 0 count, cancelling and waiting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Reached 0 count, cancelling and waiting."); lock (this) { @@ -957,7 +957,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) // TearDownAndDispose in the maximum retry period case as well as in the _errorState case. if (_errorState || retryStopwatch.Elapsed.Seconds >= 30) { - SqlClientEventSource.Log.NotificationTraceEvent(" forcing cleanup. elapsedSeconds: '{0}', _errorState: '{1}'.", retryStopwatch.Elapsed.Seconds, _errorState); + SqlClientEventSource.Log.TryNotificationTraceEvent(" forcing cleanup. elapsedSeconds: '{0}', _errorState: '{1}'.", retryStopwatch.Elapsed.Seconds, _errorState); Timer retryTimer = _retryTimer; _retryTimer = null; if (retryTimer != null) @@ -976,7 +976,7 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" _startCount not 0 after decrement. _startCount: '{0}'.", _startCount); + SqlClientEventSource.Log.TryNotificationTraceEvent(" _startCount not 0 after decrement. _startCount: '{0}'.", _startCount); } Debug.Assert(0 <= _startCount, "Invalid start count state"); @@ -985,13 +985,13 @@ internal bool Stop(string appDomainKey, out bool appDomainStop) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private void SynchronouslyQueryServiceBrokerQueue() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { @@ -1002,14 +1002,14 @@ private void SynchronouslyQueryServiceBrokerQueue() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } [SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")] private void TearDownAndDispose() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { @@ -1083,7 +1083,7 @@ private void TearDownAndDispose() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } @@ -1227,42 +1227,42 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) catch (ArgumentException e) { ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace. - SqlClientEventSource.Log.NotificationTraceEvent(" Exception thrown - Enum.Parse failed to parse the value '{0}' of the attribute '{1}'.", xmlReader.Value, xmlReader.LocalName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Exception thrown - Enum.Parse failed to parse the value '{0}' of the attribute '{1}'.", xmlReader.Value, xmlReader.LocalName); return null; } } if (MessageAttributes.All != messageAttributes) { - SqlClientEventSource.Log.NotificationTraceEvent(" Not all expected attributes in Message; messageAttributes = '{0}'.", (int)messageAttributes); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Not all expected attributes in Message; messageAttributes = '{0}'.", (int)messageAttributes); return null; } // Proceed to the "Message" node. if (!xmlReader.Read()) { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Verify state after Read(). if ((XmlNodeType.Element != xmlReader.NodeType) || (0 != string.Compare(xmlReader.LocalName, MessageNode, StringComparison.OrdinalIgnoreCase))) { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Proceed to the Text Node. if (!xmlReader.Read()) { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } // Verify state after Read(). if (xmlReader.NodeType != XmlNodeType.Text) { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } @@ -1272,7 +1272,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) // Proceed to the Text Node. if (!xmlMessageReader.Read()) { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } @@ -1283,7 +1283,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; } } @@ -1292,7 +1292,7 @@ internal static SqlNotification ProcessMessage(SqlXml xmlMessage) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" unexpected Read failure on xml or unexpected structure of xml."); return null; // failure } } @@ -1472,19 +1472,19 @@ internal int ObjectID private SqlDependencyProcessDispatcher(object dummyVariable) { Debug.Assert(null == _staticInstance, "Real constructor called with static instance already created!"); - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); #endif _connectionContainers = new Dictionary(); _sqlDependencyPerAppDomainDispatchers = new Dictionary(); } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1492,18 +1492,18 @@ private SqlDependencyProcessDispatcher(object dummyVariable) // Required to be public, even on internal class, for Remoting infrastructure. public SqlDependencyProcessDispatcher() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { // Empty constructor and object - dummy to obtain singleton. #if DEBUG // Possibly expensive, limit to debug. - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, AppDomain.CurrentDomain.FriendlyName: {1}", ObjectID, AppDomain.CurrentDomain.FriendlyName); #endif } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1529,7 +1529,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS out string user, string queue) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: {1}", _staticInstance.ObjectID, queue); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: {1}", _staticInstance.ObjectID, queue); try { // Force certain connection string properties to be used by SqlDependencyProcessDispatcher. @@ -1562,7 +1562,7 @@ private static SqlConnectionContainerHashHelper GetHashHelper(string connectionS } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1574,7 +1574,7 @@ public override object InitializeLifetimeService() private void Invalidate(string server, SqlNotification sqlNotification) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, server: {1}", ObjectID, server); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, server: {1}", ObjectID, server); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1606,7 +1606,7 @@ private void Invalidate(string server, SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1623,7 +1623,7 @@ internal void QueueAppDomainUnloading(string appDomainKey) // This method is only called by queued work-items from the method above. private void AppDomainUnloading(object state) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { string appDomainKey = (string)state; @@ -1655,7 +1655,7 @@ private void AppDomainUnloading(object state) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1722,7 +1722,7 @@ private bool Start(string connectionString, out bool appDomainStart, bool useDefaults) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: '{1}', appDomainKey: '{2}', perAppDomainDispatcher ID: '{3}'", ObjectID, queueService, appDomainKey, dispatcher.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: '{1}', appDomainKey: '{2}', perAppDomainDispatcher ID: '{3}'", ObjectID, queueService, appDomainKey, dispatcher.ObjectID); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1749,7 +1749,7 @@ private bool Start(string connectionString, queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - SqlClientEventSource.Log.NotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif bool started = false; @@ -1759,7 +1759,7 @@ private bool Start(string connectionString, { if (!_connectionContainers.ContainsKey(hashHelper)) { - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable miss, creating new container.", ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable miss, creating new container.", ObjectID); container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults); _connectionContainers.Add(hashHelper, container); started = true; @@ -1768,10 +1768,10 @@ private bool Start(string connectionString, else { container = _connectionContainers[hashHelper]; - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); if (container.InErrorState) { - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, container: {1} is in error state!", ObjectID, container.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, container: {1} is in error state!", ObjectID, container.ObjectID); errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start(). } else @@ -1786,15 +1786,15 @@ private bool Start(string connectionString, server = container.Server; database = container.Database; queueService = container.Queue; - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, default service: '{1}', server: '{2}', database: '{3}'", ObjectID, queueService, server, database); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, default service: '{1}', server: '{2}', database: '{3}'", ObjectID, queueService, server, database); } - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, started: {1}", ObjectID, started); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, started: {1}", ObjectID, started); return started; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -1811,7 +1811,7 @@ internal bool Stop(string connectionString, string appDomainKey, out bool appDomainStop) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, queueService); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, queue: '{1}'", ObjectID, queueService); try { Debug.Assert(this == _staticInstance, "Instance method called on non _staticInstance instance!"); @@ -1829,7 +1829,7 @@ internal bool Stop(string connectionString, queueService); #if DEBUG SqlConnectionString connectionStringOptions = new SqlConnectionString(connectionStringBuilder.ConnectionString); - SqlClientEventSource.Log.NotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Modified connection string: '{0}'", connectionStringOptions.UsersConnectionStringForTrace()); #endif bool stopped = false; @@ -1839,7 +1839,7 @@ internal bool Stop(string connectionString, if (_connectionContainers.ContainsKey(hashHelper)) { SqlConnectionContainer container = _connectionContainers[hashHelper]; - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable hit, container: {1}", ObjectID, container.ObjectID); server = container.Server; // Return server, database, and queue info for use by calling SqlDependency. database = container.Database; @@ -1852,16 +1852,16 @@ internal bool Stop(string connectionString, } else { - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, hashtable miss.", ObjectID); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, hashtable miss.", ObjectID); } } - SqlClientEventSource.Log.NotificationTraceEvent(" {0}, stopped: {1}", ObjectID, stopped); + SqlClientEventSource.Log.TryNotificationTraceEvent(" {0}, stopped: {1}", ObjectID, stopped); return stopped; } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs index 3de7a11191..6f91683a4d 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlDependencyUtils.cs @@ -92,7 +92,7 @@ internal int ObjectID private SqlDependencyPerAppDomainDispatcher() { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { _dependencyIdToDependencyHash = new Dictionary(); @@ -106,7 +106,7 @@ private SqlDependencyPerAppDomainDispatcher() } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -124,7 +124,7 @@ public override object InitializeLifetimeService() private void UnloadEventHandler(object sender, EventArgs e) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}", ObjectID); try { // Make non-blocking call to ProcessDispatcher to ThreadPool.QueueUserWorkItem to complete @@ -139,7 +139,7 @@ private void UnloadEventHandler(object sender, EventArgs e) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -150,7 +150,7 @@ private void UnloadEventHandler(object sender, EventArgs e) // This method is called upon SqlDependency constructor. internal void AddDependencyEntry(SqlDependency dep) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); try { lock (this) @@ -160,7 +160,7 @@ internal void AddDependencyEntry(SqlDependency dep) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -168,7 +168,7 @@ internal void AddDependencyEntry(SqlDependency dep) internal string AddCommandEntry(string commandHash, SqlDependency dep) { string notificationId = string.Empty; - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, commandHash: '{1}', SqlDependency: {2}", ObjectID, commandHash, dep.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, commandHash: '{1}', SqlDependency: {2}", ObjectID, commandHash, dep.ObjectID); try { lock (this) @@ -176,7 +176,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) if (!_dependencyIdToDependencyHash.ContainsKey(dep.Id)) { // Determine if depId->dep hashtable contains dependency. If not, it's been invalidated. - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency not present in depId->dep hash, must have been invalidated."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency not present in depId->dep hash, must have been invalidated."); } else { @@ -197,12 +197,12 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // join the new dependency to the list if (!dependencyList.Contains(dep)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency not present for commandHash, adding."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency not present for commandHash, adding."); dependencyList.Add(dep); } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency already present for commandHash."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency already present for commandHash."); } } else @@ -216,7 +216,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) SqlDependency.AppDomainKey, // must be first Guid.NewGuid().ToString("D", System.Globalization.CultureInfo.InvariantCulture) ); - SqlClientEventSource.Log.NotificationTraceEvent(" Creating new Dependencies list for commandHash."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Creating new Dependencies list for commandHash."); DependencyList dependencyList = new DependencyList(commandHash); dependencyList.Add(dep); @@ -238,7 +238,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } return notificationId; @@ -247,7 +247,7 @@ internal string AddCommandEntry(string commandHash, SqlDependency dep) // This method is called by the ProcessDispatcher upon a notification for this AppDomain. internal void InvalidateCommandID(SqlNotification sqlNotification) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, sqlNotification.Key); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, sqlNotification.Key); try { List dependencyList = null; @@ -258,7 +258,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) if (null != dependencyList) { - SqlClientEventSource.Log.NotificationTraceEvent(" commandHash found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" commandHash found in hashtable."); foreach (SqlDependency dependency in dependencyList) { // Ensure we remove from process static app domain hash for dependency initiated invalidates. @@ -270,7 +270,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" commandHash NOT found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" commandHash NOT found in hashtable."); } } @@ -279,7 +279,7 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) // After removal from hashtables, invalidate. foreach (SqlDependency dependency in dependencyList) { - SqlClientEventSource.Log.NotificationTraceEvent(" Dependency found in commandHash dependency ArrayList - calling invalidate."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Dependency found in commandHash dependency ArrayList - calling invalidate."); try { dependency.Invalidate(sqlNotification.Type, sqlNotification.Info, sqlNotification.Source); @@ -300,14 +300,14 @@ internal void InvalidateCommandID(SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is called when a connection goes down or other unknown error occurs in the ProcessDispatcher. internal void InvalidateServer(string server, SqlNotification sqlNotification) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, server: '{1}'", ObjectID, server); try { List dependencies = new List(); @@ -354,14 +354,14 @@ internal void InvalidateServer(string server, SqlNotification sqlNotification) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // This method is called by SqlCommand to enable ASP.NET scenarios - map from ID to Dependency. internal SqlDependency LookupDependencyEntry(string id) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, Key: '{1}'", ObjectID, id); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, Key: '{1}'", ObjectID, id); try { if (null == id) @@ -383,7 +383,7 @@ internal SqlDependency LookupDependencyEntry(string id) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" ERROR - dependency ID mismatch - not throwing."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - dependency ID mismatch - not throwing."); } } @@ -391,21 +391,21 @@ internal SqlDependency LookupDependencyEntry(string id) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // Remove the dependency from the hashtable with the passed id. private void LookupDependencyEntryWithRemove(string id) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, id: '{1}'", ObjectID, id); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, id: '{1}'", ObjectID, id); try { lock (this) { if (_dependencyIdToDependencyHash.ContainsKey(id)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Entry found in hashtable - removing."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entry found in hashtable - removing."); _dependencyIdToDependencyHash.Remove(id); // if there are no more dependencies then we can dispose the timer. @@ -417,20 +417,20 @@ private void LookupDependencyEntryWithRemove(string id) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Entry NOT found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entry NOT found in hashtable."); } } } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // Find and return arraylist, and remove passed hash value. private List LookupCommandEntryWithRemove(string notificationId) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, notificationId); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, commandHash: '{1}'", ObjectID, notificationId); try { DependencyList entry = null; @@ -439,7 +439,7 @@ private List LookupCommandEntryWithRemove(string notificationId) { if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Entries found in hashtable - removing."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entries found in hashtable - removing."); // update the tables - do it inside finally block to avoid ThreadAbort exception interrupt this operation try @@ -453,7 +453,7 @@ private List LookupCommandEntryWithRemove(string notificationId) } else { - SqlClientEventSource.Log.NotificationTraceEvent(" Entries NOT found in hashtable."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Entries NOT found in hashtable."); } Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in sync!"); @@ -463,14 +463,14 @@ private List LookupCommandEntryWithRemove(string notificationId) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } // Remove from commandToDependenciesHash all references to the passed dependency. private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency dependency) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dependency.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dependency.ObjectID); try { lock (this) @@ -483,7 +483,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende DependencyList dependencies = entry.Value; if (dependencies.Remove(dependency)) { - SqlClientEventSource.Log.NotificationTraceEvent(" Removed SqlDependency: {0}, with ID: '{1}'.", dependency.ObjectID, dependency.Id); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Removed SqlDependency: {0}, with ID: '{1}'.", dependency.ObjectID, dependency.Id); if (dependencies.Count == 0) { // this dependency was the last associated with this notification ID, remove the entry @@ -516,7 +516,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } @@ -526,7 +526,7 @@ private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency depende internal void StartTimer(SqlDependency dep) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" {0}, SqlDependency: {1}", ObjectID, dep.ObjectID); try { // If this dependency expires sooner than the current next timeout, change @@ -537,7 +537,7 @@ internal void StartTimer(SqlDependency dep) // Enable the timer if needed (disable when empty, enable on the first addition). if (!_SqlDependencyTimeOutTimerStarted) { - SqlClientEventSource.Log.NotificationTraceEvent(" Timer not yet started, starting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Timer not yet started, starting."); _timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */); // Save this as the earlier timeout to come. @@ -546,7 +546,7 @@ internal void StartTimer(SqlDependency dep) } else if (_nextTimeout > dep.ExpirationTime) { - SqlClientEventSource.Log.NotificationTraceEvent(" Timer already started, resetting time."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" Timer already started, resetting time."); // Save this as the earlier timeout to come. _nextTimeout = dep.ExpirationTime; @@ -555,13 +555,13 @@ internal void StartTimer(SqlDependency dep) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } private static void TimeoutTimerCallback(object state) { - long scopeID = SqlClientEventSource.Log.NotificationScopeEnterEvent(" AppDomainKey: '{0}'", SqlDependency.AppDomainKey); + long scopeID = SqlClientEventSource.Log.TryNotificationScopeEnterEvent(" AppDomainKey: '{0}'", SqlDependency.AppDomainKey); try { SqlDependency[] dependencies; @@ -574,12 +574,12 @@ private static void TimeoutTimerCallback(object state) if (0 == SingletonInstance._dependencyIdToDependencyHash.Count) { // Nothing to check. - SqlClientEventSource.Log.NotificationTraceEvent(" No dependencies, exiting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" No dependencies, exiting."); return; } if (SingletonInstance._nextTimeout > DateTime.UtcNow) { - SqlClientEventSource.Log.NotificationTraceEvent(" No timeouts expired, exiting."); + SqlClientEventSource.Log.TryNotificationTraceEvent(" No timeouts expired, exiting."); // No dependency timed-out yet. return; @@ -650,7 +650,7 @@ private static void TimeoutTimerCallback(object state) } finally { - SqlClientEventSource.Log.NotificationScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryNotificationScopeLeaveEvent(scopeID); } } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs index feec3a7438..1a50bbe2d5 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlError.cs @@ -40,7 +40,7 @@ internal SqlError(int infoNumber, byte errorState, byte errorClass, string serve _lineNumber = lineNumber; if (errorClass != 0) { - SqlClientEventSource.Log.TraceEvent(" infoNumber={0}, errorState={1}, errorClass={2}, errorMessage='{3}', procedure='{4}', lineNumber={5}", infoNumber, (int)errorState, (int)errorClass, errorMessage, procedure ?? "None", (int)lineNumber); + SqlClientEventSource.Log.TryTraceEvent(" infoNumber={0}, errorState={1}, errorClass={2}, errorMessage='{3}', procedure='{4}', lineNumber={5}", infoNumber, (int)errorState, (int)errorClass, errorMessage, procedure, (int)lineNumber); } _win32ErrorCode = 0; } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs index b39a0963e2..bb719f3f20 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnection.cs @@ -313,7 +313,7 @@ override protected DbReferenceCollection CreateReferenceCollection() override protected void Deactivate() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} deactivating", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} deactivating", ObjectID); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -435,12 +435,12 @@ protected void Enlist(SysTx.Transaction tx) private void EnlistNonNull(SysTx.Transaction tx) { Debug.Assert(null != tx, "null transaction?"); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transaction {1}.", ObjectID, tx.GetHashCode()); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transaction {1}.", ObjectID, tx.GetHashCode()); bool hasDelegatedTransaction = false; if (IsYukonOrNewer) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, attempting to delegate", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, attempting to delegate", ObjectID); // Promotable transactions are only supported on Yukon // servers or newer. @@ -507,7 +507,7 @@ private void EnlistNonNull(SysTx.Transaction tx) if (hasDelegatedTransaction) { this.DelegatedTransaction = delegatedTransaction; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, delegated to transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, delegated to transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); } } catch (SqlException e) @@ -540,7 +540,7 @@ private void EnlistNonNull(SysTx.Transaction tx) if (!hasDelegatedTransaction) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, delegation not possible, enlisting.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, delegation not possible, enlisting.", ObjectID); byte[] cookie = null; if (_isGlobalTransaction) @@ -570,7 +570,7 @@ private void EnlistNonNull(SysTx.Transaction tx) // send cookie to server to finish enlistment PropagateTransactionCookie(cookie); _isEnlistedInTransaction = true; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, enlisted with transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, enlisted with transaction {1} with transactionId=0x{2}", ObjectID, null != CurrentTransaction ? CurrentTransaction.ObjectID : 0, null != CurrentTransaction ? CurrentTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); } EnlistedTransaction = tx; // Tell the base class about our enlistment @@ -593,7 +593,7 @@ private void EnlistNonNull(SysTx.Transaction tx) internal void EnlistNull() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, unenlisting.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, unenlisting.", ObjectID); // We were in a transaction, but now we are not - so send // message to server with empty transaction - confirmed proper @@ -611,7 +611,7 @@ internal void EnlistNull() _isEnlistedInTransaction = false; EnlistedTransaction = null; // Tell the base class about our enlistment - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, unenlisted.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, unenlisted.", ObjectID); // The EnlistTransaction above will return an TransactionEnded event, // which causes the TdsParser or SmiEventSink should to clear the diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs index 5150a54dc8..e866b0c7ff 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionSmi.cs @@ -65,37 +65,37 @@ internal EventSink(SqlInternalConnectionSmi connection) internal override void DefaultDatabaseChanged(string databaseName) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, databaseName='{1}'.", _connection.ObjectID, databaseName); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, databaseName='{1}'.", _connection.ObjectID, databaseName); _connection.CurrentDatabase = databaseName; } internal override void TransactionCommitted(long transactionId) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionEnded(transactionId, TransactionState.Committed); } internal override void TransactionDefected(long transactionId) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionEnded(transactionId, TransactionState.Unknown); } internal override void TransactionEnlisted(long transactionId) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionStarted(transactionId, true); // distributed; } internal override void TransactionEnded(long transactionId) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionEndedByServer(transactionId, TransactionState.Unknown); } internal override void TransactionRolledBack(long transactionId) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); // Dev11 1066: ensure delegated transaction is rolled back _connection.TransactionEndedByServer(transactionId, TransactionState.Aborted); @@ -103,7 +103,7 @@ internal override void TransactionRolledBack(long transactionId) internal override void TransactionStarted(long transactionId) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionId=0x{1}.", _connection.ObjectID, transactionId); _connection.TransactionStarted(transactionId, false); // not distributed; } } @@ -119,7 +119,7 @@ internal SqlInternalConnectionSmi(SqlConnectionString connectionOptions, SmiCont Debug.Assert(null != _smiConnection, "null SmiContext.ContextConnection?"); _smiEventSink = new EventSink(this); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, constructed new SMI internal connection", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, constructed new SMI internal connection", ObjectID); } internal SmiContext InternalContext @@ -269,7 +269,7 @@ internal void AutomaticEnlistment() SysTx.Transaction currentSystemTransaction = ADP.GetCurrentTransaction(); // NOTE: Must be first to ensure _smiContext.ContextTransaction is set! SysTx.Transaction contextTransaction = _smiContext.ContextTransaction; // returns the transaction that was handed to SysTx that wraps the ContextTransactionId. long contextTransactionId = _smiContext.ContextTransactionId; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, contextTransactionId=0x{1}, contextTransaction={2}, currentSystemTransaction={3}.", ObjectID, contextTransactionId, (null != contextTransaction) ? contextTransaction.GetHashCode() : 0, (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, contextTransactionId=0x{1}, contextTransaction={2}, currentSystemTransaction={3}.", ObjectID, contextTransactionId, (null != contextTransaction) ? contextTransaction.GetHashCode() : 0, (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0); if (SqlInternalTransaction.NullTransactionId != contextTransactionId) { @@ -278,18 +278,18 @@ internal void AutomaticEnlistment() throw SQL.NestedTransactionScopesNotSupported(); // can't use TransactionScope(RequiresNew) inside a Sql Transaction. } - SqlClientEventSource.Log.TraceEvent(" {0}, using context transaction with transactionId=0x{1}", ObjectID, contextTransactionId); + SqlClientEventSource.Log.TryTraceEvent(" {0}, using context transaction with transactionId=0x{1}", ObjectID, contextTransactionId); _currentTransaction = new SqlInternalTransaction(this, TransactionType.Context, null, contextTransactionId); ContextTransaction = contextTransaction; } else if (null == currentSystemTransaction) { _currentTransaction = null; // there really isn't a transaction. - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, no transaction.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, no transaction.", ObjectID); } else { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, using current System.Transaction.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, using current System.Transaction.", ObjectID); base.Enlist(currentSystemTransaction); } } @@ -302,7 +302,7 @@ override protected void ChangeDatabaseInternal(string database) override protected void InternalDeactivate() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Deactivating.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Deactivating.", ObjectID); // When we put this to bed, we should not hold on to the transaction // or any activity (commit/rollback) may cause it to stop responding. @@ -331,13 +331,13 @@ override protected void InternalDeactivate() override internal void DelegatedTransactionEnded() { base.DelegatedTransactionEnded(); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, cleaning up after Delegated Transaction Completion", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, cleaning up after Delegated Transaction Completion", ObjectID); _currentTransaction = null; // clean up our current transaction too } override internal void DisconnectTransaction(SqlInternalTransaction internalTransaction) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Disconnecting Transaction {1}.", ObjectID, internalTransaction.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Disconnecting Transaction {1}.", ObjectID, internalTransaction.ObjectID); // VSTS 215465/15029: allow _currentTransaction to be null - it can be cleared before by server's callback Debug.Assert(_currentTransaction == null || _currentTransaction == internalTransaction, "disconnecting different transaction"); @@ -361,8 +361,8 @@ override internal void ExecuteTransaction( SqlInternalTransaction internalTransaction, bool isDelegateControlRequest) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, transactionRequest={1}, " + - "transactionName='{2}', isolationLevel={3}, internalTransaction=#{4} transactionId=0x{5}.", ObjectID, transactionRequest.ToString(), transactionName ?? "null", iso.ToString(), (null != internalTransaction) ? internalTransaction.ObjectID : 0, (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, transactionRequest={1}, " + + "transactionName='{2}', isolationLevel={3}, internalTransaction=#{4} transactionId=0x{5}.", ObjectID, transactionRequest, transactionName , iso, (null != internalTransaction) ? internalTransaction.ObjectID : 0, (null != internalTransaction) ? internalTransaction.TransactionId : SqlInternalTransaction.NullTransactionId); switch (transactionRequest) { @@ -419,11 +419,11 @@ override protected byte[] GetDTCAddress() if (null != whereAbouts) { - SqlClientEventSource.Log.AdvancedTraceEvent(" whereAbouts = {0}, Length = {1}", whereAbouts, (ushort)whereAbouts.Length); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" whereAbouts = {0}, Length = {1}", whereAbouts, (ushort)whereAbouts.Length); } else { - SqlClientEventSource.Log.AdvancedTraceEvent(" whereAbouts=null"); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" whereAbouts=null"); } return whereAbouts; @@ -449,7 +449,7 @@ private void OnOutOfScope(object s, EventArgs e) // Called whenever the context goes out of scope, we need to make // sure that we close the connection, or the next person that uses // the context may appear to have the connection in use. - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} context is out of scope", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} context is out of scope", ObjectID); // TODO: This is suspect to me -- if I go out of scope, who will commit the transaction? DelegatedTransaction = null; // we don't want to hold this over to the next usage; it will automatically be reused as the context transaction... @@ -480,11 +480,11 @@ override protected void PropagateTransactionCookie(byte[] transactionCookie) if (null != transactionCookie) { - SqlClientEventSource.Log.AdvancedTraceEvent(" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" transactionCookie", transactionCookie, (UInt16)transactionCookie.Length); } else { - SqlClientEventSource.Log.AdvancedTraceEvent(" null"); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" null"); } // Propagate the transaction cookie to the server diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs index 49f947acf2..2d90950cef 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs @@ -581,7 +581,7 @@ internal SqlInternalConnectionTds( ThreadHasParserLockForClose = false; _parserLock.Release(); } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, constructed new TDS internal connection", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, constructed new TDS internal connection", ObjectID); } // The erros in the transient error set are contained in @@ -849,7 +849,7 @@ override protected void ChangeDatabaseInternal(string database) override public void Dispose() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} disposing", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} disposing", ObjectID); try { TdsParser parser = Interlocked.Exchange(ref _parser, null); // guard against multiple concurrent dispose calls -- Delegated Transactions might cause this. @@ -1441,12 +1441,12 @@ private void CompleteLogin(bool enlistOK) // ROR should not affect state of connection recovery if (_federatedAuthenticationRequested && !_federatedAuthenticationAcknowledged) { - SqlClientEventSource.Log.TraceEvent(" {0}, Server did not acknowledge the federated authentication request", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Server did not acknowledge the federated authentication request", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged); } if (_federatedAuthenticationInfoRequested && !_federatedAuthenticationInfoReceived) { - SqlClientEventSource.Log.TraceEvent(" {0}, Server never sent the requested federated authentication info", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Server never sent the requested federated authentication info", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoNotReceived); } @@ -1484,7 +1484,7 @@ private void CompleteLogin(bool enlistOK) _parser.EnableMars(); _fConnectionOpen = true; // mark connection as open - SqlClientEventSource.Log.AdvancedTraceEvent(" Post-Login Phase: Server connection obtained."); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Post-Login Phase: Server connection obtained."); // for non-pooled connections, enlist in a distributed transaction // if present - and user specified to enlist @@ -1619,7 +1619,7 @@ private void Login(ServerInfo server, TimeoutTimer timeout, string newPassword, private void LoginFailure() { - SqlClientEventSource.Log.TraceEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}", ObjectID); // If the parser was allocated and we failed, then we must have failed on // either the Connect or Login, either way we should call Disconnect. @@ -1745,7 +1745,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt int routingAttempts = 0; ServerInfo originalServerInfo = serverInfo; // serverInfo may end up pointing to new object due to routing, original object is used to set CurrentDatasource - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, host={1}", ObjectID, serverInfo.UserServerName); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, host={1}", ObjectID, serverInfo.UserServerName); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. @@ -1851,7 +1851,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt if (_routingInfo != null) { - SqlClientEventSource.Log.TraceEvent(" Routed to {0}", serverInfo.ExtendedServerName); + SqlClientEventSource.Log.TryTraceEvent(" Routed to {0}", serverInfo.ExtendedServerName); if (routingAttempts > _maxNumberOfRedirectRoute) { @@ -1940,7 +1940,7 @@ private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureSt // Sleep for a bit to prevent clogging the network with requests, // then update sleep interval for next iteration (max 1 second interval) - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; @@ -2024,7 +2024,7 @@ TimeoutTimer timeout { Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used"); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, useFailover={1}[bool], primary={2}, failover={3}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName, failoverHost ?? "null"); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, useFailover={1}[bool], primary={2}, failover={3}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName, failoverHost); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. long timeoutUnitInterval; @@ -2092,7 +2092,7 @@ TimeoutTimer timeout // Primary server may give us a different failover partner than the connection string indicates. Update it if (null != ServerProvidedFailOverPartner && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); failoverServerInfo.SetDerivedNames(protocol, ServerProvidedFailOverPartner); } currentServerInfo = failoverServerInfo; @@ -2125,7 +2125,7 @@ TimeoutTimer timeout } routingAttempts++; - SqlClientEventSource.Log.TraceEvent(" Routed to {0}", _routingInfo.ServerName); + SqlClientEventSource.Log.TryTraceEvent(" Routed to {0}", _routingInfo.ServerName); if (_parser != null) _parser.Disconnect(); @@ -2194,7 +2194,7 @@ TimeoutTimer timeout // the network with requests, then update sleep interval for next iteration (max 1 second interval) if (1 == attemptNumber % 2) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } @@ -2269,7 +2269,7 @@ private void ResolveExtendedServerName(ServerInfo serverInfo, bool aliasLookup, // Common code path for making one attempt to establish a connection and log in to server. private void AttemptOneLogin(ServerInfo serverInfo, string newPassword, SecureString newSecurePassword, bool ignoreSniOpenTimeout, TimeoutTimer timeout, bool withFailover = false, bool isFirstTransparentAttempt = true, bool disableTnir = false) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); _routingInfo = null; // forget routing information @@ -2420,7 +2420,7 @@ internal bool GetSessionAndReconnectIfNeeded(SqlConnection parent, int timeout = internal void BreakConnection() { SqlConnection connection = Connection; - SqlClientEventSource.Log.TraceEvent(" {0}, Breaking connection.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Breaking connection.", ObjectID); DoomThisConnection(); // Mark connection as unusable, so it will be destroyed if (null != connection) @@ -2512,7 +2512,7 @@ internal void OnEnvChange(SqlEnvChange rec) break; case TdsEnums.ENV_ROUTING: - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received routing info", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received routing info", ObjectID); if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0) { throw SQL.ROR_InvalidRoutingInfo(this); @@ -2557,7 +2557,7 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) "Credentials aren't provided for calling MSAL"); Debug.Assert(fedAuthInfo != null, "info should not be null."); Debug.Assert(_dbConnectionPoolAuthenticationContextKey == null, "_dbConnectionPoolAuthenticationContextKey should be null."); - SqlClientEventSource.Log.TraceEvent(" {0}, Generating federated authentication token", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Generating federated authentication token", ObjectID); DbConnectionPoolAuthenticationContext dbConnectionPoolAuthenticationContext = null; // We want to refresh the token without taking a lock on the context, allowed when the access token is expiring within the next 10 mins. @@ -2585,10 +2585,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // And on successful login, try to update the cache with the new token. if (contextValidity <= _dbAuthenticationContextUnLockedRefreshTimeSpan) { - SqlClientEventSource.Log.TraceEvent(" {0}, " + - "The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + - "The expiration time is {1}. Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); - + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + SqlClientEventSource.Log.TraceEvent(" {0}, " + + "The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + + "The expiration time is {1}. Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + } attemptRefreshTokenUnLocked = true; } @@ -2608,9 +2610,12 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // If a thread is already doing the refresh, just use the existing token in the cache and proceed. else if (contextValidity <= _dbAuthenticationContextLockedRefreshTimeSpan) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, " + - "The authentication context needs a refresh.The expiration time is {1}. " + - "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, " + + "The authentication context needs a refresh.The expiration time is {1}. " + + "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + } // Call the function which tries to acquire a lock over the authentication context before trying to update. // If the lock could not be obtained, it will return false, without attempting to fetch a new token. @@ -2624,10 +2629,10 @@ internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) // Indicate in Bid Trace that we are successful with the update. if (attemptRefreshTokenLocked) { - SqlClientEventSource.Log.TraceEvent(" {0}, The attempt to get a new access token succeeded under the locked mode.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, The attempt to get a new access token succeeded under the locked mode.", ObjectID); } } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); } } @@ -2688,15 +2693,17 @@ internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionP // Else some other thread is already updating it, so just proceed forward with the existing token in the cache. if (dbConnectionPoolAuthenticationContext.LockToUpdate()) { - SqlClientEventSource.Log.TraceEvent(" {0}, " + - "Acquired the lock to update the authentication context.The expiration time is {1}. " + - "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); - + if (SqlClientEventSource.Log.IsTraceEnabled()) + { + SqlClientEventSource.Log.TraceEvent(" {0}, " + + "Acquired the lock to update the authentication context.The expiration time is {1}. " + + "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); + } authenticationContextLocked = true; } else { - SqlClientEventSource.Log.TraceEvent(" {0}, Refreshing the context is already in progress by another thread.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Refreshing the context is already in progress by another thread.", ObjectID); } if (authenticationContextLocked) @@ -2856,7 +2863,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) || _timeout.IsExpired || _timeout.MillisecondsRemaining <= sleepInterval) { - SqlClientEventSource.Log.TraceEvent(" {0}", msalException.ErrorCode); + SqlClientEventSource.Log.TryTraceEvent(" {0}", msalException.ErrorCode); // Error[0] SqlErrorCollection sqlErs = new SqlErrorCollection(); @@ -2875,8 +2882,8 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) throw exc; } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); Thread.Sleep(sleepInterval); sleepInterval *= 2; @@ -2892,7 +2899,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) DateTime expirationTime = DateTime.FromFileTimeUtc(fedAuthToken.expirationFileTime); _newDbConnectionPoolAuthenticationContext = new DbConnectionPoolAuthenticationContext(fedAuthToken.accessToken, expirationTime); } - SqlClientEventSource.Log.TraceEvent(" {0}, Finished generating federated authentication token.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Finished generating federated authentication token.", ObjectID); return fedAuthToken; } @@ -2959,11 +2966,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_FEDAUTH: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for federated authentication", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for federated authentication", ObjectID); if (!_federatedAuthenticationRequested) { - SqlClientEventSource.Log.TraceEvent(" {0}, Did not request federated authentication", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Did not request federated authentication", ObjectID); throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); } @@ -2976,7 +2983,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // The server shouldn't have sent any additional data with the ack (like a nonce) if (data.Length != 0) { - SqlClientEventSource.Log.TraceEvent(" {0}, Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthFeatureAckContainsExtraData); } break; @@ -2984,7 +2991,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) default: Debug.Fail("Unknown _fedAuthLibrary type"); - SqlClientEventSource.Log.TraceEvent(" {0}, Attempting to use unknown federated authentication library", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Attempting to use unknown federated authentication library", ObjectID); throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType); } _federatedAuthenticationAcknowledged = true; @@ -3003,11 +3010,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) { - SqlClientEventSource.Log.TraceEvent(" {0}, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); } else { - SqlClientEventSource.Log.TraceEvent(" {0}, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); } #endif } @@ -3016,17 +3023,17 @@ internal void OnFeatureExtAck(int featureId, byte[] data) } case TdsEnums.FEATUREEXT_TCE: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for TCE", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for TCE", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown version number for TCE", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown version number for TCE", ObjectID); throw SQL.ParsingError(ParsingErrorState.TceUnknownVersion); } byte supportedTceVersion = data[0]; if (0 == supportedTceVersion || supportedTceVersion > TdsEnums.MAX_SUPPORTED_TCE_VERSION) { - SqlClientEventSource.Log.TraceEvent(" {0}, Invalid version number for TCE", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Invalid version number for TCE", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidVersion, supportedTceVersion); } @@ -3045,11 +3052,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for GlobalTransactions", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for GlobalTransactions", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown version number for GlobalTransactions", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown version number for GlobalTransactions", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } @@ -3063,7 +3070,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_AZURESQLSUPPORT: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for AzureSQLSupport", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for AzureSQLSupport", ObjectID); if (data.Length < 1) { @@ -3075,31 +3082,31 @@ internal void OnFeatureExtAck(int featureId, byte[] data) // Bit 0 for RO/FP support if ((data[0] & 1) == 1 && SqlClientEventSource.Log.IsTraceEnabled()) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, FailoverPartner enabled with Readonly intent for AzureSQL DB", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, FailoverPartner enabled with Readonly intent for AzureSQL DB", ObjectID); } break; } case TdsEnums.FEATUREEXT_DATACLASSIFICATION: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte supportedDataClassificationVersion = data[0]; if ((0 == supportedDataClassificationVersion) || (supportedDataClassificationVersion > TdsEnums.DATA_CLASSIFICATION_VERSION_MAX_SUPPORTED)) { - SqlClientEventSource.Log.TraceEvent(" {0}, Invalid version number for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Invalid version number for DATACLASSIFICATION", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.DataClassificationInvalidVersion, supportedDataClassificationVersion); } if (data.Length != 2) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte enabled = data[1]; @@ -3109,11 +3116,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_UTF8SUPPORT: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for UTF8 support", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for UTF8 support", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown value for UTF8 support", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown value for UTF8 support", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } break; @@ -3121,11 +3128,11 @@ internal void OnFeatureExtAck(int featureId, byte[] data) case TdsEnums.FEATUREEXT_SQLDNSCACHING: { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Received feature extension acknowledgement for SQLDNSCACHING", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Received feature extension acknowledgement for SQLDNSCACHING", ObjectID); if (data.Length < 1) { - SqlClientEventSource.Log.TraceEvent(" {0}, Unknown token for SQLDNSCACHING", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" {0}, Unknown token for SQLDNSCACHING", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs index ed645a3d32..1017c8b789 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlTransaction.cs @@ -142,8 +142,8 @@ override public void Commit() ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -206,7 +206,7 @@ override public void Commit() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -268,7 +268,7 @@ override public void Rollback() if (IsYukonPartialZombie) { // Put something in the trace in case a customer has an issue - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} partial zombie no rollback required", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} partial zombie no rollback required", ObjectID); _internalTransaction = null; // yukon zombification } @@ -277,8 +277,8 @@ override public void Rollback() ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); - SqlClientEventSource.Log.CorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); + SqlClientEventSource.Log.TryCorrelationTraceEvent(" ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -329,7 +329,7 @@ override public void Rollback() _isFromAPI = false; SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } } @@ -342,7 +342,7 @@ public void Rollback(string transactionName) ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} transactionName='{1}'", ObjectID, transactionName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} transactionName='{1}'", ObjectID, transactionName); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); try @@ -392,7 +392,7 @@ public void Rollback(string transactionName) _isFromAPI = false; SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -404,7 +404,7 @@ public void Save(string savePointName) ZombieCheck(); SqlStatistics statistics = null; - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} savePointName='{1}'", ObjectID, savePointName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} savePointName='{1}'", ObjectID, savePointName); TdsParser bestEffortCleanupTarget = null; RuntimeHelpers.PrepareConstrainedRegions(); @@ -451,7 +451,7 @@ public void Save(string savePointName) finally { SqlStatistics.StopTimer(statistics); - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -470,7 +470,7 @@ internal void Zombie() if (null != internalConnection && internalConnection.IsYukonOrNewer && !_isFromAPI) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} yukon deferred zombie", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} yukon deferred zombie", ObjectID); } else { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index 03404784e0..9c7bdee4c4 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -526,7 +526,7 @@ internal void Connect(ServerInfo serverInfo, LoadSSPILibrary(); // now allocate proper length of buffer _sniSpnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength]; - SqlClientEventSource.Log.TraceEvent(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" SSPI or Active Directory Authentication Library for SQL Server based integrated authentication", "SEC"); } else { @@ -534,25 +534,25 @@ internal void Connect(ServerInfo serverInfo, switch (authType) { case SqlAuthenticationMethod.ActiveDirectoryPassword: - SqlClientEventSource.Log.TraceEvent(" Active Directory Password authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Password authentication", "SEC"); break; case SqlAuthenticationMethod.ActiveDirectoryIntegrated: - SqlClientEventSource.Log.TraceEvent(" Active Directory Integrated authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Integrated authentication", "SEC"); break; case SqlAuthenticationMethod.ActiveDirectoryInteractive: - SqlClientEventSource.Log.TraceEvent(" Active Directory Interactive authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Interactive authentication", "SEC"); break; case SqlAuthenticationMethod.ActiveDirectoryServicePrincipal: - SqlClientEventSource.Log.TraceEvent(" Active Directory Service Principal authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Service Principal authentication", "SEC"); break; case SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow: - SqlClientEventSource.Log.TraceEvent(" Active Directory Device Code Flow authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Active Directory Device Code Flow authentication", "SEC"); break; case SqlAuthenticationMethod.SqlPassword: - SqlClientEventSource.Log.TraceEvent(" SQL Password authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" SQL Password authentication", "SEC"); break; default: - SqlClientEventSource.Log.TraceEvent(" SQL authentication", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" SQL authentication", "SEC"); break; } } @@ -598,7 +598,7 @@ internal void Connect(ServerInfo serverInfo, // don't, the memory for the connection object might not be accurate and thus // a bad error could be returned (as it was when it was freed to early for me). _physicalStateObj.Dispose(); - SqlClientEventSource.Log.TraceEvent(" Login failure", "ERR|SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Login failure", "ERR|SEC"); ThrowExceptionAndWarning(_physicalStateObj); Debug.Fail("SNI returned status != success, but no error thrown?"); } @@ -631,21 +631,21 @@ internal void Connect(ServerInfo serverInfo, AssignPendingDNSInfo(serverInfo.UserProtocol, FQDNforDNSCahce); // UNDONE - send "" for instance now, need to fix later - SqlClientEventSource.Log.TraceEvent(" Sending prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending prelogin handshake", "SEC"); SendPreLoginHandshake(instanceName, encrypt, !string.IsNullOrEmpty(certificate), useOriginalAddressInfo); _connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake); _connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake); _physicalStateObj.SniContext = SniContext.Snix_PreLogin; - SqlClientEventSource.Log.TraceEvent(" Consuming prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Consuming prelogin handshake", "SEC"); PreLoginHandshakeStatus status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, serverCallback, clientCallback, out marsCapable, out _connHandler._fedAuthRequired); if (status == PreLoginHandshakeStatus.InstanceFailure) { - SqlClientEventSource.Log.TraceEvent(" Prelogin handshake unsuccessful. Reattempting prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Prelogin handshake unsuccessful. Reattempting prelogin handshake", "SEC"); _physicalStateObj.Dispose(); // Close previous connection // On Instance failure re-connect and flush SNI named instance cache. @@ -655,14 +655,14 @@ internal void Connect(ServerInfo serverInfo, if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); - SqlClientEventSource.Log.TraceEvent(" Login failure", "ERR|SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Login failure", "ERR|SEC"); ThrowExceptionAndWarning(_physicalStateObj); } UInt32 retCode = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId); Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId"); - SqlClientEventSource.Log.TraceEvent(" Sending prelogin handshake", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending prelogin handshake", "SEC"); // for DNS Caching phase 1 AssignPendingDNSInfo(serverInfo.UserProtocol, FQDNforDNSCahce); @@ -675,11 +675,11 @@ internal void Connect(ServerInfo serverInfo, // one pre-login packet and know we are connecting to Shiloh. if (status == PreLoginHandshakeStatus.InstanceFailure) { - SqlClientEventSource.Log.TraceEvent(" Prelogin handshake unsuccessful. Login failure", "ERR|SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Prelogin handshake unsuccessful. Login failure", "ERR|SEC"); throw SQL.InstanceFailure(); } } - SqlClientEventSource.Log.TraceEvent(" Prelogin handshake successful", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Prelogin handshake successful", "SEC"); if (_fMARS && marsCapable) { @@ -825,7 +825,7 @@ internal void EnableMars() internal TdsParserStateObject CreateSession() { TdsParserStateObject session = new TdsParserStateObject(this, (SNIHandle)_pMarsPhysicalConObj.Handle, true); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} created session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} created session {1}", ObjectID, session.ObjectID); return session; } @@ -840,12 +840,12 @@ internal TdsParserStateObject GetSession(object owner) session = _sessionPool.GetSession(owner); Debug.Assert(!session._pendingData, "pending data on a pooled MARS session"); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} getting session {1} from pool", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} getting session {1} from pool", ObjectID, session.ObjectID); } else { session = _physicalStateObj; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} getting physical session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} getting physical session {1}", ObjectID, session.ObjectID); } Debug.Assert(session._outputPacketNumber == 1, "The packet number is expected to be 1"); return session; @@ -1060,7 +1060,7 @@ private void SendPreLoginHandshake(byte[] instanceName, bool encrypt, bool clien offset += actIdSize; optionDataSize += actIdSize; - SqlClientEventSource.Log.TraceEvent(" ClientConnectionID {0}, ActivityID {1}", _connHandler._clientConnectionId.ToString(), actId.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" ClientConnectionID {0}, ActivityID {1}", _connHandler._clientConnectionId, actId); break; case (int)PreLoginOptions.FEDAUTHREQUIRED: @@ -1376,7 +1376,7 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod // Only 0x00 and 0x01 are accepted values from the server. if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01) { - SqlClientEventSource.Log.TraceEvent(" {0}, " + + SqlClientEventSource.Log.TryTraceEvent(" {0}, " + "Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {1}.", ObjectID, (int)payload[payloadOffset]); throw SQL.ParsingErrorValue(ParsingErrorState.FedAuthRequiredPreLoginResponseInvalidValue, (int)payload[payloadOffset]); @@ -1419,7 +1419,7 @@ internal void Deactivate(bool connectionIsDoomed) { // Called when the connection that owns us is deactivated. - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} deactivating", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} deactivating", ObjectID); if (SqlClientEventSource.Log.IsStateDumpEnabled()) { SqlClientEventSource.Log.StateDumpEvent(" {0}, {1}", ObjectID, TraceString()); @@ -1574,12 +1574,13 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle // be copied to the end of the error collection so that the user may see all the errors and also the // warnings that occurred. // can be deleted) + //_errorAndWarningsLock lock is implemented inside GetFullErrorAndWarningCollection SqlErrorCollection temp = stateObj.GetFullErrorAndWarningCollection(out breakConnection); Debug.Assert(temp.Count > 0, "TdsParser::ThrowExceptionAndWarning called with no exceptions or warnings!"); if (temp.Count == 0) { - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, unexpectedly empty warnings/errors under lock {0}", ObjectID); } Debug.Assert(_connHandler != null, "TdsParser::ThrowExceptionAndWarning called with null connectionHandler!"); @@ -1618,7 +1619,6 @@ internal void ThrowExceptionAndWarning(TdsParserStateObject stateObj, bool calle } } - // call OnError outside of _ErrorCollectionLock to avoid deadlock if (exception != null) { if (breakConnection) @@ -2152,7 +2152,7 @@ internal bool RunReliably(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDat { tdsReliabilitySection.Start(); #endif //DEBUG - return Run(runBehavior, cmdHandler, dataStream, bulkCopyHandler, stateObj); + return Run(runBehavior, cmdHandler, dataStream, bulkCopyHandler, stateObj); #if DEBUG } finally @@ -2298,7 +2298,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead Debug.Fail($"unexpected token; token = {token,-2:X2}"); _state = TdsParserState.Broken; _connHandler.BreakConnection(); - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, unexpected TDS token found {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, unexpected TDS token found {0}", ObjectID); throw SQL.ParsingErrorToken(ParsingErrorState.InvalidTdsTokenReceived, token); // MDAC 82443 } @@ -2620,7 +2620,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead } case TdsEnums.SQLLOGINACK: { - SqlClientEventSource.Log.TraceEvent(" Received login acknowledgement token", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Received login acknowledgement token", "SEC"); SqlLoginAck ack; if (!TryProcessLoginAck(stateObj, out ack)) @@ -2643,7 +2643,7 @@ internal bool TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataRead { _connHandler._federatedAuthenticationInfoReceived = true; SqlFedAuthInfo info; - SqlClientEventSource.Log.TraceEvent(" Received federated authentication info token", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Received federated authentication info token", "SEC"); if (!TryProcessFedAuthInfo(stateObj, tokenLength, out info)) { @@ -4114,12 +4114,12 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, SqlFedAuthInfo tempFedAuthInfo = new SqlFedAuthInfo(); // Skip reading token length, since it has already been read in caller - SqlClientEventSource.Log.AdvancedTraceEvent(" FEDAUTHINFO token stream length = {0}", tokenLen); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" FEDAUTHINFO token stream length = {0}", tokenLen); if (tokenLen < sizeof(uint)) { // the token must at least contain a DWORD indicating the number of info IDs - SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); + SqlClientEventSource.Log.TryTraceEvent(" FEDAUTHINFO token stream length too short for CountOfInfoIDs."); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForCountOfInfoIds, tokenLen); } @@ -4128,25 +4128,28 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, if (!stateObj.TryReadUInt32(out optionsCount)) { - SqlClientEventSource.Log.TraceEvent(" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" Failed to read CountOfInfoIDs in FEDAUTHINFO token stream.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadCountOfInfoIds); } tokenLen -= sizeof(uint); // remaining length is shortened since we read optCount - SqlClientEventSource.Log.AdvancedTraceEvent(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); - + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.TryAdvancedTraceEvent(" CountOfInfoIDs = {0}", optionsCount.ToString(CultureInfo.InvariantCulture)); + } if (tokenLen > 0) { // read the rest of the token byte[] tokenData = new byte[tokenLen]; int totalRead = 0; bool successfulRead = stateObj.TryReadByteArray(tokenData, 0, tokenLen, out totalRead); - - SqlClientEventSource.Log.AdvancedTraceEvent(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); - + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" Read rest of FEDAUTHINFO token stream: {0}", BitConverter.ToString(tokenData, 0, totalRead)); + } if (!successfulRead || totalRead != tokenLen) { - SqlClientEventSource.Log.TraceEvent(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}", tokenLen, totalRead); + SqlClientEventSource.Log.TryTraceEvent(" Failed to read FEDAUTHINFO token stream. Attempted to read {0} bytes, actually read {1}", tokenLen, totalRead); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadTokenStream); } @@ -4167,7 +4170,10 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, byte id = tokenData[currentOptionOffset]; uint dataLen = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 1))); uint dataOffset = BitConverter.ToUInt32(tokenData, checked((int)(currentOptionOffset + 5))); - SqlClientEventSource.Log.AdvancedTraceEvent(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture)); + if (SqlClientEventSource.Log.IsAdvancedTraceOn()) + { + SqlClientEventSource.Log.AdvancedTraceEvent(" FedAuthInfoOpt: ID={0}, DataLen={1}, Offset={2}", id, dataLen.ToString(CultureInfo.InvariantCulture), dataOffset.ToString(CultureInfo.InvariantCulture)); + } // offset is measured from optCount, so subtract to make offset measured // from the beginning of tokenData @@ -4179,7 +4185,7 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, // if dataOffset points to a region within FedAuthInfoOpt or after the end of the token, throw if (dataOffset < totalOptionsSize || dataOffset >= tokenLen) { - SqlClientEventSource.Log.TraceEvent(" FedAuthInfoDataOffset points to an invalid location.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FedAuthInfoDataOffset points to an invalid location.", "ERR"); throw SQL.ParsingErrorOffset(ParsingErrorState.FedAuthInfoInvalidOffset, unchecked((int)dataOffset)); } @@ -4191,15 +4197,15 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, } catch (ArgumentOutOfRangeException e) { - SqlClientEventSource.Log.TraceEvent(" Failed to read FedAuthInfoData.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" Failed to read FedAuthInfoData.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoFailedToReadData, e); } catch (ArgumentException e) { - SqlClientEventSource.Log.TraceEvent(" FedAuthInfoData is not in unicode format.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FedAuthInfoData is not in unicode format.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDataNotUnicode, e); } - SqlClientEventSource.Log.AdvancedTraceEvent(" FedAuthInfoData: {0}", data); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" FedAuthInfoData: {0}", data); // store data in tempFedAuthInfo switch ((TdsEnums.FedAuthInfoId)id) @@ -4211,22 +4217,22 @@ private bool TryProcessFedAuthInfo(TdsParserStateObject stateObj, int tokenLen, tempFedAuthInfo.stsurl = data; break; default: - SqlClientEventSource.Log.AdvancedTraceEvent(" Ignoring unknown federated authentication info option: {0}", id); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" Ignoring unknown federated authentication info option: {0}", id); break; } } } else { - SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream is not long enough to contain the data it claims to.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FEDAUTHINFO token stream is not long enough to contain the data it claims to.", "ERR"); throw SQL.ParsingErrorLength(ParsingErrorState.FedAuthInfoLengthTooShortForData, tokenLen); } - SqlClientEventSource.Log.TraceEvent(" Processed FEDAUTHINFO token stream: {0}", tempFedAuthInfo.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Processed FEDAUTHINFO token stream: {0}", tempFedAuthInfo); if (string.IsNullOrWhiteSpace(tempFedAuthInfo.stsurl) || string.IsNullOrWhiteSpace(tempFedAuthInfo.spn)) { // We should be receiving both stsurl and spn - SqlClientEventSource.Log.TraceEvent(" FEDAUTHINFO token stream does not contain both STSURL and SPN.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" FEDAUTHINFO token stream does not contain both STSURL and SPN.", "ERR"); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoDoesNotContainStsurlAndSpn); } @@ -4655,7 +4661,7 @@ internal bool TryProcessTceCryptoMetadata(TdsParserStateObject stateObj, // validate the index (ordinal passed) if (index >= cipherTable.Value.Size) { - SqlClientEventSource.Log.TraceEvent(" Incorrect ordinal received {0}, max tab size: {1}", index, cipherTable.Value.Size); + SqlClientEventSource.Log.TryTraceEvent(" Incorrect ordinal received {0}, max tab size: {1}", index, cipherTable.Value.Size); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidOrdinalIntoCipherInfoTable, index); } } @@ -8953,7 +8959,7 @@ internal void TdsLogin(SqlLogin rec, } WriteInt(log7Flags, _physicalStateObj); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, TDS Login7 flags = {1}:", ObjectID, log7Flags); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, TDS Login7 flags = {1}:", ObjectID, log7Flags); WriteInt(0, _physicalStateObj); // ClientTimeZone is not used WriteInt(0, _physicalStateObj); // LCID is unused by server @@ -9112,7 +9118,7 @@ internal void TdsLogin(SqlLogin rec, }; if ((requestedFeatures & TdsEnums.FeatureExtension.FedAuth) != 0) { - SqlClientEventSource.Log.TraceEvent(" Sending federated authentication feature request", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending federated authentication feature request", "SEC"); Debug.Assert(fedAuthFeatureExtensionData != null, "fedAuthFeatureExtensionData should not null."); WriteFedAuthFeatureRequest(fedAuthFeatureExtensionData.Value, write: true); }; @@ -9191,7 +9197,7 @@ internal void SendFedAuthToken(SqlFedAuthToken fedAuthToken) { Debug.Assert(fedAuthToken != null, "fedAuthToken cannot be null"); Debug.Assert(fedAuthToken.accessToken != null, "fedAuthToken.accessToken cannot be null"); - SqlClientEventSource.Log.TraceEvent(" Sending federated authentication token", "SEC"); + SqlClientEventSource.Log.TryTraceEvent(" Sending federated authentication token", "SEC"); _physicalStateObj._outputMessageType = TdsEnums.MT_FEDAUTH; @@ -9582,7 +9588,7 @@ internal SqlDataReader TdsExecuteTransactionManagerRequest( internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) { int old_outputPacketNumber = stateObj._outputPacketNumber; - SqlClientEventSource.Log.TraceEvent(" Exception caught on ExecuteXXX: '{0}'", e.ToString()); + SqlClientEventSource.Log.TryTraceEvent(" Exception caught on ExecuteXXX: '{0}'", e); if (stateObj.HasOpenResult) { // SQL BU DT 383773 - need to decrement openResultCount if operation failed. @@ -9615,7 +9621,7 @@ internal void FailureCleanup(TdsParserStateObject stateObj, Exception e) _connHandler.ThreadHasParserLockForClose = originalThreadHasParserLock; } } - SqlClientEventSource.Log.TraceEvent(" Exception rethrown.", "ERR"); + SqlClientEventSource.Log.TryTraceEvent(" Exception rethrown.", "ERR"); } internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, bool sync, bool callerHasConnectionLock = false, byte[] enclavePackage = null) @@ -9671,7 +9677,7 @@ internal Task TdsExecuteSQLBatch(string text, int timeout, SqlNotificationReques stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); } stateObj.SniContext = SniContext.Snix_Execute; @@ -9800,7 +9806,7 @@ internal Task TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, int timeout, boo stateObj.SetTimeoutSeconds(timeout); if ((!_fMARS) && (_physicalStateObj.HasOpenResult)) { - SqlClientEventSource.Log.TraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); + SqlClientEventSource.Log.TryTraceEvent(" Potential multi-threaded misuse of connection, non-MARs connection with an open result {0}", ObjectID); } stateObj.SniContext = SniContext.Snix_Execute; @@ -10666,7 +10672,7 @@ private void WriteSmiParameter(SqlParameter param, int paramIndex, bool sendDefa var sendDefaultValue = sendDefault ? 1 : 0; if (advancedTraceIsOn) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, Sending parameter '{1}', default flag={2}, metadata:{3}", ObjectID, param.ParameterName, sendDefaultValue, metaData.TraceString(3)); } // @@ -11723,7 +11729,7 @@ private void WriteQueryNotificationHeaderData(SqlNotificationRequest notificatio Debug.Assert(-1 <= timeout, "Timeout"); - SqlClientEventSource.Log.NotificationTraceEvent(" NotificationRequest: userData: '{0}', options: '{1}', timeout: '{2}'", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); + SqlClientEventSource.Log.TryNotificationTraceEvent(" NotificationRequest: userData: '{0}', options: '{1}', timeout: '{2}'", notificationRequest.UserData, notificationRequest.Options, notificationRequest.Timeout); WriteShort(TdsEnums.HEADERTYPE_QNOTIFICATION, stateObj); // Query notifications Type @@ -11750,7 +11756,7 @@ private void WriteTraceHeaderData(TdsParserStateObject stateObj) stateObj.WriteByteArray(actId.Id.ToByteArray(), GUID_SIZE, 0); // Id (Guid) WriteUnsignedInt(actId.Sequence, stateObj); // sequence number - SqlClientEventSource.Log.TraceEvent(" ActivityID {0}", actId); + SqlClientEventSource.Log.TryTraceEvent(" ActivityID {0}", actId); } private void WriteRPCBatchHeaders(TdsParserStateObject stateObj, SqlNotificationRequest notificationRequest) diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs index eb732e95bf..16754b0b7c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserSessionPool.cs @@ -36,7 +36,7 @@ internal TdsParserSessionPool(TdsParser parser) _cache = new List(); _freeStateObjects = new TdsParserStateObject[MaxInactiveCount]; _freeStateObjectCount = 0; - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} created session pool for parser {1}", ObjectID, parser.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} created session pool for parser {1}", ObjectID, parser.ObjectID); } private bool IsDisposed @@ -60,7 +60,7 @@ internal void Deactivate() // When being deactivated, we check all the sessions in the // cache to make sure they're cleaned up and then we dispose of // sessions that are past what we want to keep around. - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} deactivating cachedCount={1}", ObjectID, _cachedCount); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} deactivating cachedCount={1}", ObjectID, _cachedCount); try { lock (_cache) @@ -79,7 +79,7 @@ internal void Deactivate() if (session.IsOrphaned) { // TODO: consider adding a performance counter for the number of sessions we reclaim - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} reclaiming session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} reclaiming session {1}", ObjectID, session.ObjectID); PutSession(session); } } @@ -90,7 +90,7 @@ internal void Deactivate() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -113,7 +113,7 @@ internal void BestEffortCleanup() internal void Dispose() { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} disposing cachedCount={1}", ObjectID, _cachedCount); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} disposing cachedCount={1}", ObjectID, _cachedCount); lock (_cache) { // Dispose free sessions @@ -172,7 +172,7 @@ internal TdsParserStateObject GetSession(object owner) { // No free objects, create a new one session = _parser.CreateSession(); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} adding session {1} to pool", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} adding session {1} to pool", ObjectID, session.ObjectID); _cache.Add(session); _cachedCount = _cache.Count; @@ -180,7 +180,7 @@ internal TdsParserStateObject GetSession(object owner) session.Activate(owner); } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} using session {1}", ObjectID, session.ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} using session {1}", ObjectID, session.ObjectID); return session; } @@ -202,7 +202,7 @@ internal void PutSession(TdsParserStateObject session) else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount)) { // Session is good to re-use and our cache has space - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} keeping session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} keeping session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); Debug.Assert(!session._pendingData, "pending data on a pooled session?"); _freeStateObjects[_freeStateObjectCount] = session; @@ -211,7 +211,7 @@ internal void PutSession(TdsParserStateObject session) else { // Either the session is bad, or we have no cache space - so dispose the session and remove it - SqlClientEventSource.Log.AdvancedTraceEvent(" {0} disposing session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0} disposing session {1} cachedCount={2}", ObjectID, session.ObjectID, _cachedCount); bool removed = _cache.Remove(session); Debug.Assert(removed, "session not in pool?"); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index 62cc1b7be3..7e526ebd9c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -564,8 +564,8 @@ internal bool TryInitialize(TdsParserStateObject stateObj, int columnsCount) { return false; } - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount); - SqlClientEventSource.Log.AdvancedTraceBinEvent(" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, NBCROW bitmap received, column count = {1}", stateObj.ObjectID, columnsCount); + SqlClientEventSource.Log.TryAdvancedTraceBinEvent(" NBCROW bitmap data: ", _nullBitmap, (ushort)_nullBitmap.Length); return true; } @@ -924,11 +924,11 @@ internal void DecrementOpenResultCount() internal int DecrementPendingCallbacks(bool release) { int remaining = Interlocked.Decrement(ref _pendingCallbacks); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); if ((0 == remaining || release) && _gcHandle.IsAllocated) { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, FREEING HANDLE!", ObjectID); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, FREEING HANDLE!", ObjectID); _gcHandle.Free(); } @@ -1037,7 +1037,7 @@ internal int IncrementPendingCallbacks() { int remaining = Interlocked.Increment(ref _pendingCallbacks); - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks); Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}"); return remaining; } @@ -2174,7 +2174,7 @@ internal bool TryReadNetworkPacket() _snapshot.CheckStack(new StackTrace()); } #endif - SqlClientEventSource.Log.TraceEvent(" Async packet replay{0}", "INFO"); + SqlClientEventSource.Log.TryTraceEvent(" Async packet replay{0}", "INFO"); return true; } #if DEBUG @@ -2596,7 +2596,7 @@ internal bool IsConnectionAlive(bool throwOnException) if ((error != TdsEnums.SNI_SUCCESS) && (error != TdsEnums.SNI_WAIT_TIMEOUT)) { // Connection is dead - SqlClientEventSource.Log.TraceEvent(" received error {0} on idle connection", (int)error); + SqlClientEventSource.Log.TryTraceEvent(" received error {0} on idle connection", (int)error); isAlive = false; if (throwOnException) @@ -2811,7 +2811,7 @@ public void ProcessSniPacket(IntPtr packet, UInt32 error) } } SniReadStatisticsAndTracing(); - SqlClientEventSource.Log.AdvancedTraceBinEvent(" Packet read", _inBuff, (ushort)_inBytesRead); + SqlClientEventSource.Log.TryAdvancedTraceBinEvent(" Packet read", _inBuff, (ushort)_inBytesRead); AssertValidState(); } else @@ -2968,7 +2968,7 @@ public void WriteAsyncCallback(IntPtr key, IntPtr packet, UInt32 sniError) { if (sniError != TdsEnums.SNI_SUCCESS) { - SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)sniError); + SqlClientEventSource.Log.TryTraceEvent(" write async returned error code {0}", (int)sniError); try { AddError(_parser.ProcessSNIError(this)); @@ -3436,7 +3436,7 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr if (error != TdsEnums.SNI_SUCCESS) { - SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)error); + SqlClientEventSource.Log.TryTraceEvent(" write async returned error code {0}", (int)error); AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(); @@ -3474,7 +3474,7 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniEr } else { - SqlClientEventSource.Log.TraceEvent(" write async returned error code {0}", (int)sniError); + SqlClientEventSource.Log.TryTraceEvent(" write async returned error code {0}", (int)sniError); AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(callerHasConnectionLock); } @@ -3534,7 +3534,7 @@ internal void SendAttention(bool mustTakeWriteLock = false) UInt32 sniError; _parser._asyncWrite = false; // stop async write SNIWritePacket(Handle, attnPacket, out sniError, canAccumulate: false, callerHasConnectionLock: false); - SqlClientEventSource.Log.TraceEvent(" Send Attention ASync.", "Info"); + SqlClientEventSource.Log.TryTraceEvent(" Send Attention ASync.", "Info"); } finally { @@ -3557,8 +3557,8 @@ internal void SendAttention(bool mustTakeWriteLock = false) _attentionSending = false; } - SqlClientEventSource.Log.AdvancedTraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); - SqlClientEventSource.Log.TraceEvent(" Attention sent to the server.", "Info"); + SqlClientEventSource.Log.TryAdvancedTraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); + SqlClientEventSource.Log.TryTraceEvent(" Attention sent to the server.", "Info"); AssertValidState(); } @@ -3744,7 +3744,7 @@ private void SniWriteStatisticsAndTracing() _traceChangePasswordLength = 0; } } - SqlClientEventSource.Log.AdvancedTraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); + SqlClientEventSource.Log.TryAdvancedTraceBinEvent(" Packet sent", _outBuff, (ushort)_outBytesUsed); } [Conditional("DEBUG")] diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs index 650a1652a4..e7581774c9 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/sqlinternaltransaction.cs @@ -53,7 +53,7 @@ internal SqlInternalTransaction(SqlInternalConnection innerConnection, Transacti internal SqlInternalTransaction(SqlInternalConnection innerConnection, TransactionType type, SqlTransaction outerTransaction, long transactionId) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Created for connection {1}, outer transaction {2}, Type {3}", ObjectID, innerConnection.ObjectID, (null != outerTransaction) ? outerTransaction.ObjectID : -1, (int)type); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Created for connection {1}, outer transaction {2}, Type {3}", ObjectID, innerConnection.ObjectID, (null != outerTransaction) ? outerTransaction.ObjectID : -1, (int)type); _innerConnection = innerConnection; _transactionType = type; @@ -268,7 +268,7 @@ internal void CloseFromConnection() SqlInternalConnection innerConnection = _innerConnection; Debug.Assert(innerConnection != null, "How can we be here if the connection is null?"); - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Closing", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Closing", ObjectID); bool processFinallyBlock = true; try @@ -296,7 +296,7 @@ internal void CloseFromConnection() internal void Commit() { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { throw SQL.ConnectionLockedForBcpEvent(); @@ -340,7 +340,7 @@ internal void Commit() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -369,7 +369,7 @@ internal void Dispose() private /*protected override*/ void Dispose(bool disposing) { - SqlClientEventSource.Log.PoolerTraceEvent(" {0}, Disposing", ObjectID); + SqlClientEventSource.Log.TryPoolerTraceEvent(" {0}, Disposing", ObjectID); if (disposing) { @@ -425,7 +425,7 @@ internal void InitParent(SqlTransaction transaction) internal void Rollback() { - var scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}", ObjectID); + var scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}", ObjectID); if (_innerConnection.IsLockedForBulkCopy) { @@ -466,13 +466,13 @@ internal void Rollback() } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } internal void Rollback(string transactionName) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, transactionName='{1}'", ObjectID, transactionName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, transactionName='{1}'", ObjectID, transactionName); if (_innerConnection.IsLockedForBulkCopy) { @@ -515,13 +515,13 @@ internal void Rollback(string transactionName) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } internal void Save(string savePointName) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0}, savePointName='{1}'", ObjectID, savePointName); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0}, savePointName='{1}'", ObjectID, savePointName); _innerConnection.ValidateConnectionForExecute(null); try @@ -552,7 +552,7 @@ internal void Save(string savePointName) } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs index 3fb3ffe338..f459f32a25 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlTypes/SqlFileStream.cs @@ -65,7 +65,7 @@ public SqlFileStream Int64 allocationSize ) { - long scopeID = SqlClientEventSource.Log.ScopeEnterEvent(" {0} access={1} options={2} path='{3}'", ObjectID, (int)access, (int)options, path); + long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent(" {0} access={1} options={2} path='{3}'", ObjectID, (int)access, (int)options, path); try { //----------------------------------------------------------------- @@ -90,7 +90,7 @@ Int64 allocationSize } finally { - SqlClientEventSource.Log.ScopeLeaveEvent(scopeID); + SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID); } } @@ -713,7 +713,7 @@ Int64 allocationSize UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode); try { - SqlClientEventSource.Log.AdvancedTraceEvent(" {0}, desiredAccess=0x{1}, allocationSize={2}, " + + SqlClientEventSource.Log.TryAdvancedTraceEvent(" {0}, desiredAccess=0x{1}, allocationSize={2}, " + "fileAttributes=0x{3}, shareAccess=0x{4}, dwCreateDisposition=0x{5}, createOptions=0x{ dwCreateOptions}", ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition); retval = UnsafeNativeMethods.NtCreateFile(out hFile, nDesiredAccess, diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs index f9000f5d9f..a2d49e96c8 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEventSource.cs @@ -13,6 +13,8 @@ internal partial class SqlClientEventSource : EventSource // Defines the singleton instance for the Resources ETW provider internal static readonly SqlClientEventSource Log = new SqlClientEventSource(); + private const string NullStr = "null"; + #region Event IDs // Initialized static Scope IDs private static long s_nextScopeId = 0; @@ -268,8 +270,30 @@ public static class Tasks //Never use event writer directly as they are not checking for enabled/disabled situations. Always use overloads. #region Trace + + #region Traces without if statements + [NonEvent] + internal void TraceEvent(string message, T0 args0, T1 args1) + { + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); + } + + [NonEvent] + internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2) + { + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); + } + + [NonEvent] + internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); + } + #endregion + + #region Traces with if statements [NonEvent] - internal void TraceEvent(string message) + internal void TryTraceEvent(string message) { if (Log.IsTraceEnabled()) { @@ -278,54 +302,56 @@ internal void TraceEvent(string message) } [NonEvent] - internal void TraceEvent(string message, T0 args0) + internal void TryTraceEvent(string message, T0 args0) { if (Log.IsTraceEnabled()) { - Trace(string.Format(message, args0?.ToString() ?? "Null")); + Trace(string.Format(message, args0?.ToString() ?? NullStr)); } } [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1) + internal void TryTraceEvent(string message, T0 args0, T1 args1) { if (Log.IsTraceEnabled()) { - Trace(string.Format(message, args0?.ToString() ?? "Null", args1?.ToString() ?? "Null")); + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2) + internal void TryTraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsTraceEnabled()) { - Trace(string.Format(message, args0, args1, args2)); + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } } [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void TryTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsTraceEnabled()) { - Trace(string.Format(message, args0, args1, args2, args3)); + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } } [NonEvent] - internal void TraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) + internal void TryTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) { if (Log.IsTraceEnabled()) { - Trace(string.Format(message, args0, args1, args2, args3, args4, args5)); + Trace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr, args4?.ToString() ?? NullStr, args5?.ToString() ?? NullStr)); } } #endregion + #endregion + #region Scope [NonEvent] - internal long ScopeEnterEvent(string message) + internal long TryScopeEnterEvent(string message) { if (Log.IsScopeEnabled()) { @@ -335,47 +361,47 @@ internal long ScopeEnterEvent(string message) } [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0) + internal long TryScopeEnterEvent(string message, T0 args0) { if (Log.IsScopeEnabled()) { - return ScopeEnter(string.Format(message, args0)); + return ScopeEnter(string.Format(message, args0?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0, T1 args1) + internal long TryScopeEnterEvent(string message, T0 args0, T1 args1) { if (Log.IsScopeEnabled()) { - return ScopeEnter(string.Format(message, args0, args1)); + return ScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) + internal long TryScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsScopeEnabled()) { - return ScopeEnter(string.Format(message, args0, args1, args2)); + return ScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long ScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal long TryScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsScopeEnabled()) { - return ScopeEnter(string.Format(message, args0, args1, args2, args3)); + return ScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal void ScopeLeaveEvent(long scopeId) + internal void TryScopeLeaveEvent(long scopeId) { if (Log.IsScopeEnabled()) { @@ -385,8 +411,18 @@ internal void ScopeLeaveEvent(long scopeId) #endregion #region Notification Trace + + #region Notification Traces without if statements [NonEvent] - internal void NotificationTraceEvent(string message) + internal void NotificationTraceEvent(string message, T0 args0, T1 args1) + { + NotificationTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); + } + #endregion + + #region Notification Traces with if statements + [NonEvent] + internal void TryNotificationTraceEvent(string message) { if (Log.IsNotificationTraceEnabled()) { @@ -395,85 +431,87 @@ internal void NotificationTraceEvent(string message) } [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0) + internal void TryNotificationTraceEvent(string message, T0 args0) { if (Log.IsNotificationTraceEnabled()) { - NotificationTrace(string.Format(message, args0)); + NotificationTrace(string.Format(message, args0?.ToString() ?? NullStr)); } } [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0, T1 args1) + internal void TryNotificationTraceEvent(string message, T0 args0, T1 args1) { if (Log.IsNotificationTraceEnabled()) { - NotificationTrace(string.Format(message, args0, args1)); + NotificationTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0, T1 args1, T2 args2) + internal void TryNotificationTraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsNotificationTraceEnabled()) { - NotificationTrace(string.Format(message, args0, args1, args2)); + NotificationTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } } [NonEvent] - internal void NotificationTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void TryNotificationTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsNotificationTraceEnabled()) { - NotificationTrace(string.Format(message, args0, args1, args2, args3)); + NotificationTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } } #endregion + #endregion + #region Notification Scope [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0) + internal long TryNotificationScopeEnterEvent(string message, T0 args0) { if (Log.IsNotificationScopeEnabled()) { - return NotificationScopeEnter(string.Format(message, args0)); + return NotificationScopeEnter(string.Format(message, args0?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0, T1 args1) + internal long TryNotificationScopeEnterEvent(string message, T0 args0, T1 args1) { if (Log.IsNotificationScopeEnabled()) { - return NotificationScopeEnter(string.Format(message, args0, args1)); + return NotificationScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) + internal long TryNotificationScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsNotificationScopeEnabled()) { - return NotificationScopeEnter(string.Format(message, args0, args1, args2)); + return NotificationScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long NotificationScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal long TryNotificationScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsNotificationScopeEnabled()) { - return NotificationScopeEnter(string.Format(message, args0, args1, args2, args3)); + return NotificationScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal void NotificationScopeLeaveEvent(long scopeId) + internal void TryNotificationScopeLeaveEvent(long scopeId) { if (Log.IsNotificationScopeEnabled()) { @@ -484,55 +522,55 @@ internal void NotificationScopeLeaveEvent(long scopeId) #region Pooler Trace [NonEvent] - internal void PoolerTraceEvent(string message, T0 args0) + internal void TryPoolerTraceEvent(string message, T0 args0) { if (Log.IsPoolerTraceEnabled()) { - PoolerTrace(string.Format(message, args0)); + PoolerTrace(string.Format(message, args0?.ToString() ?? NullStr)); } } [NonEvent] - internal void PoolerTraceEvent(string message, T0 args0, T1 args1) + internal void TryPoolerTraceEvent(string message, T0 args0, T1 args1) { if (Log.IsPoolerTraceEnabled()) { - PoolerTrace(string.Format(message, args0, args1)); + PoolerTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2) + internal void TryPoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsPoolerTraceEnabled()) { - PoolerTrace(string.Format(message, args0, args1, args2)); + PoolerTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } } [NonEvent] - internal void PoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void TryPoolerTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsPoolerTraceEnabled()) { - PoolerTrace(string.Format(message, args0, args1, args2, args3)); + PoolerTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } } #endregion #region Pooler Scope [NonEvent] - internal long PoolerScopeEnterEvent(string message, T0 args0) + internal long TryPoolerScopeEnterEvent(string message, T0 args0) { if (Log.IsPoolerScopeEnabled()) { - return PoolerScopeEnter(string.Format(message, args0)); + return PoolerScopeEnter(string.Format(message, args0?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal void PoolerScopeLeaveEvent(long scopeId) + internal void TryPoolerScopeLeaveEvent(long scopeId) { if (Log.IsPoolerScopeEnabled()) { @@ -542,8 +580,36 @@ internal void PoolerScopeLeaveEvent(long scopeId) #endregion #region AdvancedTrace + + #region AdvancedTraces without if statements + [NonEvent] + internal void AdvancedTraceEvent(string message, T0 args0) + { + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr)); + } + + [NonEvent] + internal void AdvancedTraceEvent(string message, T0 args0, T1 args1) + { + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); + } + [NonEvent] - internal void AdvancedTraceEvent(string message) + internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2) + { + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); + } + + [NonEvent] + internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + { + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); + } + #endregion + + #region AdvancedTraces with if statements + [NonEvent] + internal void TryAdvancedTraceEvent(string message) { if (Log.IsAdvancedTraceOn()) { @@ -552,71 +618,71 @@ internal void AdvancedTraceEvent(string message) } [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0) + internal void TryAdvancedTraceEvent(string message, T0 args0) { if (Log.IsAdvancedTraceOn()) { - AdvancedTrace(string.Format(message, args0)); + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr)); } } [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1) + internal void TryAdvancedTraceEvent(string message, T0 args0, T1 args1) { if (Log.IsAdvancedTraceOn()) { - AdvancedTrace(string.Format(message, args0, args1)); + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2) + internal void TryAdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsAdvancedTraceOn()) { - AdvancedTrace(string.Format(message, args0, args1, args2)); + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } } [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void TryAdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsAdvancedTraceOn()) { - AdvancedTrace(string.Format(message, args0, args1, args2, args3)); + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } } [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) + internal void TryAdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5) { if (Log.IsAdvancedTraceOn()) { - AdvancedTrace(string.Format(message, args0, args1, args2, args3, args4, args5)); + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr, args4?.ToString() ?? NullStr, args5?.ToString() ?? NullStr)); } } [NonEvent] - internal void AdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5, T6 args6, T7 args7) + internal void TryAdvancedTraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4, T5 args5, T6 args6, T7 args7) { if (Log.IsAdvancedTraceOn()) { - AdvancedTrace(string.Format(message, args0, args1, args2, args3, args4, args5, args6, args7)); + AdvancedTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr, args4?.ToString() ?? NullStr, args5?.ToString() ?? NullStr, args6?.ToString() ?? NullStr, args7?.ToString() ?? NullStr)); } } [NonEvent] - internal long AdvancedScopeEnterEvent(string message, T0 args0) + internal long TryAdvancedScopeEnterEvent(string message, T0 args0) { if (Log.IsAdvancedTraceOn()) { - return AdvancedScopeEnter(string.Format(message, args0)); + return AdvancedScopeEnter(string.Format(message, args0?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal void AdvanceScopeLeave(long scopeId) + internal void TryAdvanceScopeLeave(long scopeId) { if (Log.IsAdvancedTraceOn()) { @@ -625,67 +691,66 @@ internal void AdvanceScopeLeave(long scopeId) } [NonEvent] - internal void AdvancedTraceBinEvent(string message, T0 args0, T1 args1) + internal void TryAdvancedTraceBinEvent(string message, T0 args0, T1 args1) { if (Log.IsAdvancedTraceOn()) { - AdvancedTraceBin(string.Format(message, args0, args1)); + AdvancedTraceBin(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void AdvancedTraceErrorEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4) + internal void TryAdvancedTraceErrorEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4) { if (Log.IsAdvancedTraceOn()) { - AdvancedTraceError(string.Format(message, args0, args1, args2, args3, args4)); + AdvancedTraceError(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr, args4?.ToString() ?? NullStr)); } } #endregion + #endregion + #region Correlation Trace [NonEvent] - internal void CorrelationTraceEvent(string message, T0 args0) + internal void TryCorrelationTraceEvent(string message, T0 args0) { if (Log.IsCorrelationEnabled()) { - CorrelationTrace(string.Format(message, args0?.ToString() ?? "Null")); + CorrelationTrace(string.Format(message, args0?.ToString() ?? NullStr)); } } [NonEvent] - internal void CorrelationTraceEvent(string message, T0 args0, T1 args1) + internal void TryCorrelationTraceEvent(string message, T0 args0, T1 args1) { if (Log.IsCorrelationEnabled()) { - CorrelationTrace(string.Format(message, args0?.ToString() ?? "Null", args1?.ToString() ?? "Null")); + CorrelationTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void CorrelationTraceEvent(string message, T0 args0, T1 args1, T2 args2) + internal void TryCorrelationTraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsCorrelationEnabled()) { - CorrelationTrace(string.Format(message, args0?.ToString() ?? "Null", args1?.ToString() ?? "Null", args2?.ToString() ?? "Null")); + CorrelationTrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } } #endregion - #region State Dump + #region State Dump without if statements [NonEvent] internal void StateDumpEvent(string message, T0 args0, T1 args1) { - if (Log.IsStateDumpEnabled()) - { - StateDump(string.Format(message, args0, args1)); - } + StateDump(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } #endregion #region SNI Trace [NonEvent] - internal void SNITraceEvent(string message) + internal void TrySNITraceEvent(string message) { if (Log.IsSNITraceEnabled()) { @@ -694,54 +759,54 @@ internal void SNITraceEvent(string message) } [NonEvent] - internal void SNITraceEvent(string message, T0 args0) + internal void TrySNITraceEvent(string message, T0 args0) { if (Log.IsSNITraceEnabled()) { - SNITrace(string.Format(message, args0)); + SNITrace(string.Format(message, args0?.ToString() ?? NullStr)); } } [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1) + internal void TrySNITraceEvent(string message, T0 args0, T1 args1) { if (Log.IsSNITraceEnabled()) { - SNITrace(string.Format(message, args0, args1)); + SNITrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } } [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1, T2 args2) + internal void TrySNITraceEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsSNITraceEnabled()) { - SNITrace(string.Format(message, args0, args1, args2)); + SNITrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } } [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal void TrySNITraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsSNITraceEnabled()) { - SNITrace(string.Format(message, args0, args1, args2, args3)); + SNITrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } } [NonEvent] - internal void SNITraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4) + internal void TrySNITraceEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3, T4 args4) { if (Log.IsSNITraceEnabled()) { - SNITrace(string.Format(message, args0, args1, args2, args3, args4)); + SNITrace(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr, args4?.ToString() ?? NullStr)); } } #endregion #region SNI Scope [NonEvent] - internal long SNIScopeEnterEvent(string message) + internal long TrySNIScopeEnterEvent(string message) { if (Log.IsSNIScopeEnabled()) { @@ -751,47 +816,47 @@ internal long SNIScopeEnterEvent(string message) } [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0) + internal long TrySNIScopeEnterEvent(string message, T0 args0) { if (Log.IsSNIScopeEnabled()) { - return SNIScopeEnter(string.Format(message, args0)); + return SNIScopeEnter(string.Format(message, args0?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0, T1 args1) + internal long TrySNIScopeEnterEvent(string message, T0 args0, T1 args1) { if (Log.IsSNIScopeEnabled()) { - return SNIScopeEnter(string.Format(message, args0, args1)); + return SNIScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) + internal long TrySNIScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2) { if (Log.IsSNIScopeEnabled()) { - return SNIScopeEnter(string.Format(message, args0, args1, args2)); + return SNIScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal long SNIScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) + internal long TrySNIScopeEnterEvent(string message, T0 args0, T1 args1, T2 args2, T3 args3) { if (Log.IsSNIScopeEnabled()) { - return SNIScopeEnter(string.Format(message, args0, args1, args2, args3)); + return SNIScopeEnter(string.Format(message, args0?.ToString() ?? NullStr, args1?.ToString() ?? NullStr, args2?.ToString() ?? NullStr, args3?.ToString() ?? NullStr)); } return 0; } [NonEvent] - internal void SNIScopeLeaveEvent(long scopeId) + internal void TrySNIScopeLeaveEvent(long scopeId) { if (Log.IsSNIScopeEnabled()) { diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientLogger.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientLogger.cs index 5150862224..aaec458db8 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientLogger.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientLogger.cs @@ -13,26 +13,26 @@ internal enum LogLevel { Info = 0, Warning, - Error + Error } /// public void LogInfo(string type, string method, string message) { - SqlClientEventSource.Log.TraceEvent("{3}", type, method, LogLevel.Info, message); + SqlClientEventSource.Log.TryTraceEvent("{3}", type, method, LogLevel.Info, message); } /// public void LogWarning(string type, string method, string message) { Console.Out.WriteLine(message); - SqlClientEventSource.Log.TraceEvent("{3}", type, method, LogLevel.Warning, message); + SqlClientEventSource.Log.TryTraceEvent("{3}", type, method, LogLevel.Warning, message); } /// public void LogError(string type, string method, string message) { - SqlClientEventSource.Log.TraceEvent("{3}", type, method, LogLevel.Error, message); + SqlClientEventSource.Log.TryTraceEvent("{3}", type, method, LogLevel.Error, message); } /// From 2b30d77bc1866e4cce06d80778788d01613c3a14 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Fri, 21 Aug 2020 16:05:11 -0700 Subject: [PATCH 12/24] Last Changes for preview release (#705) --- .../netcore/ref/Microsoft.Data.SqlClient.cs | 2 + .../netcore/src/Resources/Strings.Designer.cs | 54 +++++++++---------- .../netfx/ref/Microsoft.Data.SqlClient.cs | 2 + .../Microsoft.Data.SqlClient.Tests.csproj | 1 + tools/props/Versions.props | 4 +- tools/specs/Microsoft.Data.SqlClient.nuspec | 8 +-- 6 files changed, 38 insertions(+), 33 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs index c34dcddab7..47c806d387 100644 --- a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs +++ b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs @@ -619,6 +619,8 @@ public SqlConnection(string connectionString, Microsoft.Data.SqlClient.SqlCreden [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(0)] public override string ServerVersion { get { throw null; } } + /// + public int ServerProcessId { get { throw null; } } /// [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(0)] diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Resources/Strings.Designer.cs b/src/Microsoft.Data.SqlClient/netcore/src/Resources/Strings.Designer.cs index aa3f051d37..438423fa71 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Resources/Strings.Designer.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Resources/Strings.Designer.cs @@ -2499,6 +2499,15 @@ internal static string SQL_DbTypeNotSupportedOnThisPlatform { } } + /// + /// Looks up a localized string similar to Cannot use 'Authentication=Active Directory Device Code Flow' with 'User ID', 'UID', 'Password' or 'PWD' connection string keywords.. + /// + internal static string SQL_DeviceFlowWithUsernamePassword { + get { + return ResourceManager.GetString("SQL_DeviceFlowWithUsernamePassword", resourceCulture); + } + } + /// /// Looks up a localized string similar to The duration spent while attempting to connect to this server was - [Pre-Login] initialization={0}; handshake={1}; [Login] initialization={2}; . /// @@ -2652,15 +2661,6 @@ internal static string SQL_InteractiveWithPassword { } } - /// - /// Looks up a localized string similar to Cannot use 'Authentication=Active Directory Device Code Flow' with 'User ID', 'UID', 'Password' or 'PWD' connection string keywords.. - /// - internal static string SQL_DeviceFlowWithUsernamePassword { - get { - return ResourceManager.GetString("SQL_DeviceFlowWithUsernamePassword", resourceCulture); - } - } - /// /// Looks up a localized string similar to Internal Error. /// @@ -3048,6 +3048,15 @@ internal static string SQL_ScaleValueOutOfRange { } } + /// + /// Looks up a localized string similar to Cannot set the Credential property if 'Authentication=Active Directory Device Code Flow' has been specified in the connection string.. + /// + internal static string SQL_SettingCredentialWithDeviceFlow { + get { + return ResourceManager.GetString("SQL_SettingCredentialWithDeviceFlow", resourceCulture); + } + } + /// /// Looks up a localized string similar to Cannot set the Credential property if 'Authentication=Active Directory Integrated' has been specified in the connection string.. /// @@ -3067,11 +3076,11 @@ internal static string SQL_SettingCredentialWithInteractive { } /// - /// Looks up a localized string similar to Cannot set the Credential property if 'Authentication=Active Directory Device Code Flow' has been specified in the connection string.. + /// Looks up a localized string similar to Cannot use 'Authentication=Active Directory Device Code Flow', if the Credential property has been set.. /// - internal static string SQL_SettingCredentialWithDeviceFlow { + internal static string SQL_SettingDeviceFlowWithCredential { get { - return ResourceManager.GetString("SQL_SettingCredentialWithDeviceFlow", resourceCulture); + return ResourceManager.GetString("SQL_SettingDeviceFlowWithCredential", resourceCulture); } } @@ -3093,15 +3102,6 @@ internal static string SQL_SettingInteractiveWithCredential { } } - /// - /// Looks up a localized string similar to Cannot use 'Authentication=Active Directory Device Code Flow', if the Credential property has been set.. - /// - internal static string SQL_SettingDeviceFlowWithCredential { - get { - return ResourceManager.GetString("SQL_SettingDeviceFlowWithCredential", resourceCulture); - } - } - /// /// Looks up a localized string similar to A severe error occurred on the current command. The results, if any, should be discarded.. /// @@ -3229,20 +3229,20 @@ internal static string SQL_Timeout { } /// - /// Looks up a localized string similar to Active Directory Interactive authentication timed out. The user took too long to respond to the authentication request.. + /// Looks up a localized string similar to Active Directory Device Code Flow authentication timed out. The user took too long to respond to the authentication request.. /// - internal static string SQL_Timeout_Active_Directory_Interactive_Authentication { + internal static string SQL_Timeout_Active_Directory_DeviceFlow_Authentication { get { - return ResourceManager.GetString("SQL_Timeout_Active_Directory_Interactive_Authentication", resourceCulture); + return ResourceManager.GetString("SQL_Timeout_Active_Directory_DeviceFlow_Authentication", resourceCulture); } } /// - /// Looks up a localized string similar to Active Directory Device Code Flow authentication timed out. The user took too long to respond to the authentication request.. + /// Looks up a localized string similar to Active Directory Interactive authentication timed out. The user took too long to respond to the authentication request.. /// - internal static string SQL_Timeout_Active_Directory_DeviceFlow_Authentication { + internal static string SQL_Timeout_Active_Directory_Interactive_Authentication { get { - return ResourceManager.GetString("SQL_Timeout_Active_Directory_DeviceFlow_Authentication", resourceCulture); + return ResourceManager.GetString("SQL_Timeout_Active_Directory_Interactive_Authentication", resourceCulture); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs b/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs index 76d4f44fbb..1fe8a00ea2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs +++ b/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs @@ -775,6 +775,8 @@ public SqlConnection(string connectionString, Microsoft.Data.SqlClient.SqlCreden [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(0)] public override string ServerVersion { get { throw null; } } + /// + public int ServerProcessId { get { throw null; } } /// [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(0)] diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj index cbaa4a9520..f812a47cd0 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj @@ -94,5 +94,6 @@ + diff --git a/tools/props/Versions.props b/tools/props/Versions.props index 16c550dfd6..34ccbbaf0a 100644 --- a/tools/props/Versions.props +++ b/tools/props/Versions.props @@ -12,7 +12,7 @@ - 2.0.0 + 2.1.0 4.3.1 4.3.0 @@ -27,7 +27,7 @@ 4.7.0 - 2.0.0 + 2.1.0 4.7.0 4.7.0 4.7.0 diff --git a/tools/specs/Microsoft.Data.SqlClient.nuspec b/tools/specs/Microsoft.Data.SqlClient.nuspec index 362ffdd7c8..4bed4c4330 100644 --- a/tools/specs/Microsoft.Data.SqlClient.nuspec +++ b/tools/specs/Microsoft.Data.SqlClient.nuspec @@ -27,13 +27,13 @@ When using NuGet 3.x this package requires at least version 3.4. sqlclient microsoft.data.sqlclient - + - + @@ -45,7 +45,7 @@ When using NuGet 3.x this package requires at least version 3.4. - + @@ -57,7 +57,7 @@ When using NuGet 3.x this package requires at least version 3.4. - + From 0e715441e3c735ccb9410745d6b8ea505b03058b Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Fri, 21 Aug 2020 17:05:21 -0700 Subject: [PATCH 13/24] Update SNI version --- tools/specs/Microsoft.Data.SqlClient.nuspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/specs/Microsoft.Data.SqlClient.nuspec b/tools/specs/Microsoft.Data.SqlClient.nuspec index 4bed4c4330..1637214a69 100644 --- a/tools/specs/Microsoft.Data.SqlClient.nuspec +++ b/tools/specs/Microsoft.Data.SqlClient.nuspec @@ -68,7 +68,7 @@ When using NuGet 3.x this package requires at least version 3.4. - + From 11b94803c38ffc6d2349fb27b8d801329252f370 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Fri, 21 Aug 2020 17:53:23 -0700 Subject: [PATCH 14/24] Release notes for v2.1.0-preview1 (#706) Co-authored-by: Karina Zhou Co-authored-by: Johnny Pham <23270162+johnnypham@users.noreply.github.com> Co-authored-by: David Engel --- CHANGELOG.md | 36 ++++- release-notes/2.1/2.1.0-preview1.md | 202 ++++++++++++++++++++++++++++ release-notes/2.1/2.1.md | 7 + release-notes/2.1/README.md | 7 + release-notes/README.md | 1 + 5 files changed, 250 insertions(+), 3 deletions(-) create mode 100644 release-notes/2.1/2.1.0-preview1.md create mode 100644 release-notes/2.1/2.1.md create mode 100644 release-notes/2.1/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 409e175eed..c68ea7a7a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,36 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +## [Preview Release 2.1.0-preview1.20235.1] - 2020-08-21 + +### Added +- Added support for Always Encrypted with secure enclaves on Unix for .NET Core 2.1+ and on all supported platforms for .NET Standard 2.1+ [#676](https://github.com/dotnet/SqlClient/pull/676) +- Added support for Azure Active Directory Device Code Flow authentication [#597](https://github.com/dotnet/SqlClient/pull/597) +- Added Sensitivity Rank support in Sensitivity Classification information [#626](https://github.com/dotnet/SqlClient/pull/626) +- Added support to obtain `ServerProcessId` (SPID) information on an active `SqlConnection` instance [#660](https://github.com/dotnet/SqlClient/pull/660) +- Added support for a new Configuration Section, `SqlClientAuthenticationProviders` (duplicate of existing `SqlAuthenticationProviders`), to allow co-existence of configurations for both drivers, "System.Data.SqlClient" and "Microsoft.Data.SqlClient" [#702](https://github.com/dotnet/SqlClient/pull/702) +- Added TraceLogging in Native SNI to extend `SqlClientEventSource` support [#650](https://github.com/dotnet/SqlClient/pull/650) +- Updated Microsoft.Data.SqlClient.SNI (.NET Framework dependency) and Microsoft.Data.SqlClient.SNI.runtime (.NET Core/Standard dependency) version to v2.1.0 with trace logging implementation [#705](https://github.com/dotnet/SqlClient/pull/705) + +### Fixed +- Fixed Enclave session cache issue with Azure Database [#686](https://github.com/dotnet/SqlClient/pull/686) +- Fixed pooled connection re-use on access token expiry issue when using Active Directory authentication modes [#635](https://github.com/dotnet/SqlClient/pull/635) +- Fixed transient fault handling for Pooled connections [#637](https://github.com/dotnet/SqlClient/pull/637) +- Fixed SPN generation issue when no port is provided [#629](https://github.com/dotnet/SqlClient/pull/629) +- Fixed missing null checks for `SqlErrors` in `SqlException` for .NET Framework implementation [#698](https://github.com/dotnet/SqlClient/pull/698) + +### Changes +- Performance improvements by fixing unnecessary allocations with EventSource implementation [#684](https://github.com/dotnet/SqlClient/pull/684) +- Reverted changes to return empty DataTable from GetSchemaTable to return null as before. [#696](https://github.com/dotnet/SqlClient/pull/696) +- Removed multiple `CacheConnectionStringProperties` calls when setting `ConnectionString` properties [#683](https://github.com/dotnet/SqlClient/pull/683) +- Code Improvements by only checking inexact match when no exact match is found for an embedded resource [#668](https://github.com/dotnet/SqlClient/pull/668) +- Changed `_SqlMetaData` to lazy initialize hidden column map [#521](https://github.com/dotnet/SqlClient/pull/521) +- Renamed internal string resource file and helpers for .NET Core implementation [#671](https://github.com/dotnet/SqlClient/pull/671) +- Performance improvements by reworking `ExecuteReaderAsync` to minimize allocations [#528](https://github.com/dotnet/SqlClient/pull/528) +- Performance improvements by moving `DataReader` caches to internal connection [#499](https://github.com/dotnet/SqlClient/pull/499) +- Moved common files to shared folder between .NET Framework and .NET Core implementation [#618](https://github.com/dotnet/SqlClient/pull/618) [#625](https://github.com/dotnet/SqlClient/pull/625) + + ## [Stable Release 2.0.0] - 2020-06-16 ### Added @@ -37,7 +67,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ### Fixed - Fixed `SqlBulkCopy` to work with database columns containing metadata about data classification [#568](https://github.com/dotnet/SqlClient/pull/568) -- Fixed unsafe cast in `SqlException` for `SerializationEntry.Value` +- Fixed unsafe cast in `SqlException` for `SerializationEntry.Value` - Fixed null reference exceptions in `SqlDelegatedTransaction` methods [#563](https://github.com/dotnet/SqlClient/pull/563) ### Changes @@ -59,7 +89,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) ### Added - Allow passing username with Active Directory Interactive Authentication in .NET Framework [#492](https://github.com/dotnet/SqlClient/pull/492) -- Allow large UDT buffers for .NET Framework [#456](https://github.com/dotnet/SqlClient/pull/456) +- Allow large UDT buffers for .NET Framework [#456](https://github.com/dotnet/SqlClient/pull/456) - Added "Transaction Id" and "Client Version" in Diagnostic Source traces [#515](https://github.com/dotnet/SqlClient/pull/515) - Added new `SqlConnectionOverrides` APIs to perform `SqlConnection.Open()` with fail fast option [#463](https://github.com/dotnet/SqlClient/pull/463) @@ -114,7 +144,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) - Updated error messages for "Always Encrypted - Secure Enclaves" to handle 'Attestation Protocol' and fixed typos [#421](https://github.com/dotnet/SqlClient/pull/421) [#397](https://github.com/dotnet/SqlClient/pull/397) - Removed sync over async in `SNINpHandle.EnableSsl` [#474](https://github.com/dotnet/SqlClient/pull/474) - Changed non-generic `ArrayList` to `List` in `SqlBulkCopy` [#457](https://github.com/dotnet/SqlClient/pull/457) -- Multiple performance improvements [#377](https://github.com/dotnet/SqlClient/pull/377) [#378](https://github.com/dotnet/SqlClient/pull/378) [#379](https://github.com/dotnet/SqlClient/pull/379) +- Multiple performance improvements [#377](https://github.com/dotnet/SqlClient/pull/377) [#378](https://github.com/dotnet/SqlClient/pull/378) [#379](https://github.com/dotnet/SqlClient/pull/379) ### Breaking Changes - The driver will now perform Server Certificate validation when TLS encryption is enforced by the target Server, which is the default for Azure connections [#391](https://github.com/dotnet/SqlClient/pull/391) diff --git a/release-notes/2.1/2.1.0-preview1.md b/release-notes/2.1/2.1.0-preview1.md new file mode 100644 index 0000000000..0c9710c99c --- /dev/null +++ b/release-notes/2.1/2.1.0-preview1.md @@ -0,0 +1,202 @@ +# Release Notes + +## Microsoft.Data.SqlClient 2.1.0-preview1.20235.1 released 21 August 2020 + +This update brings the below changes over the previous release: + +### Added +- Added support for Always Encrypted with secure enclaves on Unix for .NET Core 2.1+ and on all supported platforms for .NET Standard 2.1+ [#676](https://github.com/dotnet/SqlClient/pull/676) [[Read more](#Cross-Platform-support-for-Always-Encrypted-and-Secure-Enclaves)] +- Added support for Azure Active Directory Device Code Flow authentication [#597](https://github.com/dotnet/SqlClient/pull/597) [[Read more](#Azure-Active-Directory-Device-Code-Flow-authentication)] +- Added new APIs to enable customizations for "Active Directory Interactive" authentication experience [#597](https://github.com/dotnet/SqlClient/pull/597) [Read more](#Azure-Active-Directory-Interactive-authentication-enhancements) +- Added Sensitivity Rank support in Sensitivity Classification information [#626](https://github.com/dotnet/SqlClient/pull/626) [[Read more](#Data-Classification-v2-support)] +- Added support to obtain `ServerProcessId()` (SPID) information on an active `SqlConnection` instance [#660](https://github.com/dotnet/SqlClient/pull/660) [[Read more](#Server-Process-Id-for-active-SqlConnection)] +- Added support for a new Configuration Section, `SqlClientAuthenticationProviders` (duplicate of existing `SqlAuthenticationProviders`), to allow co-existence of configurations for both drivers, "System.Data.SqlClient" and "Microsoft.Data.SqlClient" [#702](https://github.com/dotnet/SqlClient/pull/702) [[Read more](#SqlClientAuthenticationProviders-configuration-section)] +- Added TraceLogging in Native SNI to extend `SqlClientEventSource` support [#650](https://github.com/dotnet/SqlClient/pull/650) [[Read more](#Trace-Logging-support-in-Native-SNI)] +- Updated Microsoft.Data.SqlClient.SNI (.NET Framework dependency) and Microsoft.Data.SqlClient.SNI.runtime (.NET Core/Standard dependency) version to v2.1.0 with trace logging implementation [#705](https://github.com/dotnet/SqlClient/pull/705) + +### Fixed +- Fixed Enclave session cache issue with Azure Database [#686](https://github.com/dotnet/SqlClient/pull/686) +- Fixed pooled connection re-use on access token expiry issue when using Active Directory authentication modes [#635](https://github.com/dotnet/SqlClient/pull/635) +- Fixed transient fault handling for Pooled connections [#637](https://github.com/dotnet/SqlClient/pull/637) +- Fixed SPN generation issue when no port is provided [#629](https://github.com/dotnet/SqlClient/pull/629) +- Fixed missing null checks for `SqlErrors` in `SqlException` for .NET Framework implementation [#698](https://github.com/dotnet/SqlClient/pull/698) + +### Changes +- Performance improvements by fixing unnecessary allocations with EventSource implementation [#684](https://github.com/dotnet/SqlClient/pull/684) +- Reverted changes to return empty DataTable from GetSchemaTable to return null as before. [#696](https://github.com/dotnet/SqlClient/pull/696) +- Removed multiple `CacheConnectionStringProperties` calls when setting `ConnectionString` properties [#683](https://github.com/dotnet/SqlClient/pull/683) +- Code Improvements by only checking inexact match when no exact match is found for an embedded resource [#668](https://github.com/dotnet/SqlClient/pull/668) +- Changed `_SqlMetaData` to lazy initialize hidden column map [#521](https://github.com/dotnet/SqlClient/pull/521) +- Renamed internal string resource file and helpers for .NET Core implementation [#671](https://github.com/dotnet/SqlClient/pull/671) +- Performance improvements by reworking `ExecuteReaderAsync` to minimize allocations [#528](https://github.com/dotnet/SqlClient/pull/528) +- Performance improvements by moving `DataReader` caches to internal connection [#499](https://github.com/dotnet/SqlClient/pull/499) +- Moved common files to shared folder between .NET Framework and .NET Core implementation [#618](https://github.com/dotnet/SqlClient/pull/618) [#625](https://github.com/dotnet/SqlClient/pull/625) + +## New features over Stable release v2.0 + +### Cross-Platform support for Always Encrypted and Secure Enclaves +Microsoft.Data.SqlClient v2.1 extends support for Always Encrypted (including with secure enclaves) on the following platforms: + +| Target Framework | Platform | New Feature support | +|------------------|----------|----| +| .NET Framework v4.6+ | Windows | *No changes* | +| .NET Core 2.1+ | All Operating Systems | **Yes, Support on Linux/MacOS** | +| .NET Standard 2.1+ | All Operating Systems | **Yes, Support on All Operating Systems** | + +### Azure Active Directory Device Code Flow authentication +Microsoft.Data.SqlClient v2.1 provides support for "Device Code Flow" authentication with MSAL.NET. +Reference documentation: [OAuth2.0 Device Authorization Grant flow](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code) + +Connection string example: + +`Server=.database.windows.net; Authentication=Active Directory Device Code Flow; Database=Northwind;` + +The following API enables customization of the Device Code Flow callback mechanism: + +```csharp +public class ActiveDirectoryAuthenticationProvider +{ + // For .NET Framework, .NET Core and .NET Standard targeted applications + public void SetDeviceCodeFlowCallback(Func deviceCodeFlowCallbackMethod) +} +``` + +### Azure Active Directory Interactive authentication enhancements +Microsoft.Data.SqlClient v2.1 provides the following new APIs to enable customizations for the "Active Directory Interactive" authentication experience: + +```csharp +public class ActiveDirectoryAuthenticationProvider +{ + // For .NET Framework targeted applications only + public void SetIWin32WindowFunc(Func iWin32WindowFunc); + + // For .NET Standard targeted applications only + public void SetParentActivityOrWindowFunc(Func parentActivityOrWindowFunc); + + // For .NET Framework, .NET Core and .NET Standard targeted applications + public void SetCustomWebUi(ICustomWebUi customWebUi); +} +``` + +### Data Classification v2 support +Microsoft.Data.SqlClient v2.1 introduces support for Data Classification's "Sensitivity Rank" information. The following new APIs are now available: + +```csharp +public class SensitivityClassification +{ + public SensitivityRank SensitivityRank; +} + +public class SensitivityProperty +{ + public SensitivityRank SensitivityRank; +} + +public enum SensitivityRank +{ + NOT_DEFINED = -1, + NONE = 0, + LOW = 10, + MEDIUM = 20, + HIGH = 30, + CRITICAL = 40 +} +``` + +### Server Process Id for an active SqlConnection +Microsoft.Data.SqlClient v2.1 introduces a new `SqlConnection` property, `ServerProcessId`, on an active connection. + +```csharp +public class SqlConnection +{ + // Returns the server process Id (SPID) of the active connection. + public int ServerProcessId; +} +``` + +### Trace Logging support in Native SNI +Microsoft.Data.SqlClient v2.1 extends the existing `SqlClientEventSource` implementation to enable event tracing in SNI.dll. Events must be captured using a tool like Xperf. + +Tracing can be enabled by sending a command to `SqlClientEventSource` as illustrated below: + +```csharp +// Enables trace events: +EventSource.SendCommand(eventSource, (EventCommand)8192, null); + +// Enables flow events: +EventSource.SendCommand(eventSource, (EventCommand)16384, null); + +// Enables both trace and flow events: +EventSource.SendCommand(eventSource, (EventCommand)(8192 | 16384), null); +``` + +### SqlClientAuthenticationProviders configuration section +Microsoft.Data.SqlClient v2.1 introduces a new configuration section, `SqlClientAuthenticationProviders` (a clone of the existing `SqlAuthenticationProviders`). The existing configuration section, `SqlAuthenticationProviders`, is still supported for backwards compatibility when the appropriate type is defined. + +The new section allows application config files to contain both a SqlAuthenticationProviders section for System.Data.SqlClient and a SqlClientAuthenticationProviders section for Microsoft.Data.SqlClient. + + +## Target Platform Support + +- .NET Framework 4.6+ (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 + +- Microsoft.Data.SqlClient.SNI 2.1.0 +- Microsoft.Identity.Client 4.14.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 5.6.0 +- Microsoft.IdentityModel.JsonWebTokens 5.6.0 + +#### .NET Core 2.1 + +- Microsoft.Data.SqlClient.SNI.runtime 2.1.0 +- Microsoft.Win32.Registry 4.7.0 +- System.Security.Principal.Windows 4.7.0 +- System.Text.Encoding.CodePages 4.7.0 +- System.Diagnostics.DiagnosticSource 4.7.0 +- System.Configuration.ConfigurationManager 4.7.0 +- System.Runtime.Caching 4.7.0 +- Microsoft.Identity.Client 4.14.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 5.6.0 +- Microsoft.IdentityModel.JsonWebTokens 5.6.0 + +#### .NET Core 3.1 + +- Microsoft.Data.SqlClient.SNI.runtime 2.1.0 +- Microsoft.Win32.Registry 4.7.0 +- System.Security.Principal.Windows 4.7.0 +- System.Text.Encoding.CodePages 4.7.0 +- System.Diagnostics.DiagnosticSource 4.7.0 +- System.Configuration.ConfigurationManager 4.7.0 +- System.Runtime.Caching 4.7.0 +- Microsoft.Identity.Client 4.14.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 5.6.0 +- Microsoft.IdentityModel.JsonWebTokens 5.6.0 + +#### .NET Standard 2.0 + +- Microsoft.Data.SqlClient.SNI.runtime 2.1.0 +- 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 +- Microsoft.Identity.Client 4.14.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 5.6.0 +- Microsoft.IdentityModel.JsonWebTokens 5.6.0 + +#### .NET Standard 2.1 + +- Microsoft.Data.SqlClient.SNI.runtime 2.1.0 +- 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 +- Microsoft.Identity.Client 4.14.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 5.6.0 +- Microsoft.IdentityModel.JsonWebTokens 5.6.0 diff --git a/release-notes/2.1/2.1.md b/release-notes/2.1/2.1.md new file mode 100644 index 0000000000..67805fbbfa --- /dev/null +++ b/release-notes/2.1/2.1.md @@ -0,0 +1,7 @@ +# Microsoft.Data.SqlClient 2.1 Releases + +The following Microsoft.Data.SqlClient 2.1 preview releases have been shipped: + +| Release Date | Version | Notes | +| :-- | :-- | :--: | +| 2020/08/21 | 2.1.0-preview1.20235.1 | [release notes](2.1.0-preview1.md) | diff --git a/release-notes/2.1/README.md b/release-notes/2.1/README.md new file mode 100644 index 0000000000..67805fbbfa --- /dev/null +++ b/release-notes/2.1/README.md @@ -0,0 +1,7 @@ +# Microsoft.Data.SqlClient 2.1 Releases + +The following Microsoft.Data.SqlClient 2.1 preview releases have been shipped: + +| Release Date | Version | Notes | +| :-- | :-- | :--: | +| 2020/08/21 | 2.1.0-preview1.20235.1 | [release notes](2.1.0-preview1.md) | diff --git a/release-notes/README.md b/release-notes/README.md index 1986a536cb..43621a5da7 100644 --- a/release-notes/README.md +++ b/release-notes/README.md @@ -4,6 +4,7 @@ The latest stable release is [Microsoft.Data.SqlClient 2.0](2.0). ## Release Information +- [Microsoft.Data.SqlClient 2.1](2.1) - [Microsoft.Data.SqlClient 2.0](2.0) - [Microsoft.Data.SqlClient 1.1](1.1) - [Microsoft.Data.SqlClient 1.0](1.0) From 07ee9dbf3c2e6d0cafe23342768ba2f17f1f1930 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Tue, 25 Aug 2020 16:50:17 -0700 Subject: [PATCH 15/24] Release notes for v2.0.1 (#710) --- CHANGELOG.md | 14 ++++++++ release-notes/2.0/2.0.1.md | 70 +++++++++++++++++++++++++++++++++++++ release-notes/2.0/2.0.md | 1 + release-notes/2.0/README.md | 1 + 4 files changed, 86 insertions(+) create mode 100644 release-notes/2.0/2.0.1.md diff --git a/CHANGELOG.md b/CHANGELOG.md index c68ea7a7a6..5f11549b0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +## [Stable Release 2.0.1] - 2020-08-25 + +### Added +- Added support for a new Configuration Section, `SqlClientAuthenticationProviders` (duplicate of existing `SqlAuthenticationProviders`), to allow co-existence of configurations for both drivers, "System.Data.SqlClient" and "Microsoft.Data.SqlClient" [#701](https://github.com/dotnet/SqlClient/pull/701) + +### Fixed +- Fixed pooled connection re-use on access token expiry issue when using Active Directory authentication modes [#639](https://github.com/dotnet/SqlClient/pull/639) +- Fixed transient fault handling for Pooled connections [#638](https://github.com/dotnet/SqlClient/pull/638) +- Fixed Enclave session cache issue with Azure Database [#628](https://github.com/dotnet/SqlClient/pull/628) +- Reverted changes to return empty DataTable from GetSchemaTable to return null as before. [#697](https://github.com/dotnet/SqlClient/pull/697) +- Fixed configuration section collision issue with System.Data.SqlClient type [#701](https://github.com/dotnet/SqlClient/pull/701) +- Fixed blank error message [HTTP Provider] issues due to unexpected pre-login failures when using Native SNI. Fixed with Microsoft.Data.SqlClient.SNI v2.0.1 and Microsoft.Data.SqlClient.SNI.runtime v2.0.1 release versions. + + ## [Preview Release 2.1.0-preview1.20235.1] - 2020-08-21 ### Added diff --git a/release-notes/2.0/2.0.1.md b/release-notes/2.0/2.0.1.md new file mode 100644 index 0000000000..ce339c57fb --- /dev/null +++ b/release-notes/2.0/2.0.1.md @@ -0,0 +1,70 @@ +# Release Notes + +## Microsoft.Data.SqlClient 2.0.1 released 25 August 2020 + +This update brings the below changes over the previous stable release: + +### Added +- Added support for a new Configuration Section, `SqlClientAuthenticationProviders` (duplicate of existing `SqlAuthenticationProviders`), to allow co-existence of configurations for both drivers, "System.Data.SqlClient" and "Microsoft.Data.SqlClient" [#701](https://github.com/dotnet/SqlClient/pull/701) + +### Fixed +- Fixed pooled connection re-use on access token expiry issue when using Active Directory authentication modes [#639](https://github.com/dotnet/SqlClient/pull/639) +- Fixed transient fault handling for Pooled connections [#638](https://github.com/dotnet/SqlClient/pull/638) +- Fixed Enclave session cache issue with Azure Database [#628](https://github.com/dotnet/SqlClient/pull/628) +- Reverted changes to return empty DataTable from GetSchemaTable to return null as before. [#697](https://github.com/dotnet/SqlClient/pull/697) +- Fixed configuration section collision issue with System.Data.SqlClient type [#701](https://github.com/dotnet/SqlClient/pull/701) +- Fixed blank error message [HTTP Provider] issues due to unexpected pre-login failures when using Native SNI. Fixed with Microsoft.Data.SqlClient.SNI v2.0.1 and Microsoft.Data.SqlClient.SNI.runtime v2.0.1 release versions. + + +## Target Platform Support + +- .NET Framework 4.6+ (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 + +- Microsoft.Data.SqlClient.SNI 2.0.1 +- Microsoft.Identity.Client 4.14.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 5.6.0 +- Microsoft.IdentityModel.JsonWebTokens 5.6.0 + +#### .NET Core 2.1 + +- Microsoft.Data.SqlClient.SNI.runtime 2.0.1 +- Microsoft.Win32.Registry 4.7.0 +- System.Security.Principal.Windows 4.7.0 +- System.Text.Encoding.CodePages 4.7.0 +- System.Diagnostics.DiagnosticSource 4.7.0 +- System.Configuration.ConfigurationManager 4.7.0 +- System.Runtime.Caching 4.7.0 +- Microsoft.Identity.Client 4.14.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 5.6.0 +- Microsoft.IdentityModel.JsonWebTokens 5.6.0 + +#### .NET Core 3.1 + +- Microsoft.Data.SqlClient.SNI.runtime 2.0.1 +- Microsoft.Win32.Registry 4.7.0 +- System.Security.Principal.Windows 4.7.0 +- System.Text.Encoding.CodePages 4.7.0 +- System.Diagnostics.DiagnosticSource 4.7.0 +- System.Configuration.ConfigurationManager 4.7.0 +- System.Runtime.Caching 4.7.0 +- Microsoft.Identity.Client 4.14.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 5.6.0 +- Microsoft.IdentityModel.JsonWebTokens 5.6.0 + +#### .NET Standard + +- Microsoft.Data.SqlClient.SNI.runtime 2.0.1 +- 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 +- Microsoft.Identity.Client 4.14.0 +- Microsoft.IdentityModel.Protocols.OpenIdConnect 5.6.0 +- Microsoft.IdentityModel.JsonWebTokens 5.6.0 diff --git a/release-notes/2.0/2.0.md b/release-notes/2.0/2.0.md index 57ab9b4f80..5bde012d6a 100644 --- a/release-notes/2.0/2.0.md +++ b/release-notes/2.0/2.0.md @@ -4,6 +4,7 @@ The following Microsoft.Data.SqlClient 2.0 stable releases have been shipped: | Release Date | Version | Notes | | :-- | :-- | :--: | +| 2020/08/25 | 2.0.1 | [release notes](2.0.1.md) | | 2020/06/16 | 2.0.0 | [release notes](2.0.0.md) | The following Microsoft.Data.SqlClient 2.0 preview releases have been shipped: diff --git a/release-notes/2.0/README.md b/release-notes/2.0/README.md index 57ab9b4f80..5bde012d6a 100644 --- a/release-notes/2.0/README.md +++ b/release-notes/2.0/README.md @@ -4,6 +4,7 @@ The following Microsoft.Data.SqlClient 2.0 stable releases have been shipped: | Release Date | Version | Notes | | :-- | :-- | :--: | +| 2020/08/25 | 2.0.1 | [release notes](2.0.1.md) | | 2020/06/16 | 2.0.0 | [release notes](2.0.0.md) | The following Microsoft.Data.SqlClient 2.0 preview releases have been shipped: From 22d1467ab64f19e73f115e11552e25a67a4e4506 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Thu, 27 Aug 2020 10:45:44 -0700 Subject: [PATCH 16/24] [Cleanup] Remove unused algorithm classes. (#699) --- .../src/Microsoft.Data.SqlClient.csproj | 6 -- .../Data/SqlClient/SqlSecurityUtility.cs | 8 +- .../src/Microsoft/Data/SqlClient/TdsEnums.cs | 9 +-- .../netfx/src/Microsoft.Data.SqlClient.csproj | 6 -- .../Data/SqlClient/SqlSecurityUtility.cs | 4 - .../src/Microsoft/Data/SqlClient/TdsEnums.cs | 19 +++-- .../SqlAeadAes256CbcHmac256EncryptionKey.cs | 2 +- .../Data/SqlClient/SqlAes256CbcAlgorithm.cs | 56 ------------- .../Data/SqlClient/SqlAes256CbcFactory.cs | 81 ------------------- ...SqlClientEncryptionAlgorithmFactoryList.cs | 3 +- .../Data/SqlClient/SqlClientSymmetricKey.cs | 7 -- 11 files changed, 17 insertions(+), 184 deletions(-) delete mode 100644 src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAes256CbcAlgorithm.cs delete mode 100644 src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAes256CbcFactory.cs diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj index ca0ae11448..4bd8bb5c1d 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj @@ -150,12 +150,6 @@ Microsoft\Data\SqlClient\SqlAeadAes256CbcHmac256Factory.cs - - Microsoft\Data\SqlClient\SqlAes256CbcAlgorithm.cs - - - Microsoft\Data\SqlClient\SqlAes256CbcFactory.cs - Microsoft\Data\SqlClient\SqlAuthenticationParameters.cs diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs index a17a2dea1e..6df67b9b98 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs @@ -150,10 +150,6 @@ private static string ValidateAndGetEncryptionAlgorithmName(byte cipherAlgorithm { return SqlAeadAes256CbcHmac256Algorithm.AlgorithmName; } - else if (TdsEnums.AES_256_CBC == cipherAlgorithmId) - { - return SqlAes256CbcAlgorithm.AlgorithmName; - } else { throw SQL.UnknownColumnEncryptionAlgorithmId(cipherAlgorithmId, GetRegisteredCipherAlgorithmIds()); @@ -241,7 +237,7 @@ internal static byte[] DecryptWithKey(byte[] cipherText, SqlCipherMetadata md, s } /// - /// Decrypts the symmetric key and saves it in metadata. In addition, initializes + /// Decrypts the symmetric key and saves it in metadata. In addition, initializes /// the SqlClientEncryptionAlgorithm for rapid decryption. /// internal static void DecryptSymmetricKey(SqlCipherMetadata md, string serverName) @@ -253,7 +249,7 @@ internal static void DecryptSymmetricKey(SqlCipherMetadata md, string serverName DecryptSymmetricKey(md.EncryptionInfo, serverName, out symKey, out encryptionkeyInfoChosen); - // Given the symmetric key instantiate a SqlClientEncryptionAlgorithm object and cache it in metadata + // Given the symmetric key instantiate a SqlClientEncryptionAlgorithm object and cache it in metadata md.CipherAlgorithm = null; SqlClientEncryptionAlgorithm cipherAlgorithm = null; string algorithmName = ValidateAndGetEncryptionAlgorithmName(md.CipherAlgorithmId, md.CipherAlgorithmName); // may throw diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsEnums.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsEnums.cs index 83005d7a03..7325755d26 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsEnums.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsEnums.cs @@ -134,7 +134,7 @@ internal static class TdsEnums public const byte SQLDEBUG_CMD = 0x60; public const byte SQLLOGINACK = 0xad; public const byte SQLFEATUREEXTACK = 0xae; // TDS 7.4 - feature ack - public const byte SQLSESSIONSTATE = 0xe4; // TDS 7.4 - connection resiliency session state + public const byte SQLSESSIONSTATE = 0xe4; // TDS 7.4 - connection resiliency session state public const byte SQLENVCHANGE = 0xe3; // Environment change notification public const byte SQLSECLEVEL = 0xed; // Security level token ??? public const byte SQLROWCRC = 0x39; // ROWCRC datastream??? @@ -210,8 +210,8 @@ public enum EnvChangeType : byte public const byte FEATUREEXT_FEDAUTH = 0x02; public const byte FEATUREEXT_TCE = 0x04; public const byte FEATUREEXT_GLOBALTRANSACTIONS = 0x05; - // 0x06 is for x_eFeatureExtensionId_LoginToken - // 0x07 is for x_eFeatureExtensionId_ClientSideTelemetry + // 0x06 is for x_eFeatureExtensionId_LoginToken + // 0x07 is for x_eFeatureExtensionId_ClientSideTelemetry public const byte FEATUREEXT_AZURESQLSUPPORT = 0x08; public const byte FEATUREEXT_DATACLASSIFICATION = 0x09; public const byte FEATUREEXT_UTF8SUPPORT = 0x0A; @@ -272,7 +272,7 @@ public enum ActiveDirectoryWorkflow : byte public const byte MAX_NIC_SIZE = 6; // The size of a MAC or client address public const byte SQLVARIANT_SIZE = 2; // size of the fixed portion of a sql variant (type, cbPropBytes) public const byte VERSION_SIZE = 4; // size of the tds version (4 unsigned bytes) - public const int CLIENT_PROG_VER = 0x06000000; // Client interface version + public const int CLIENT_PROG_VER = 0x06000000; // Client interface version public const int YUKON_LOG_REC_FIXED_LEN = 0x5e; // misc public const int TEXT_TIME_STAMP_LEN = 8; @@ -987,7 +987,6 @@ internal static string GetSniContextEnumName(SniContext sniContext) internal const long MAX_TCE_CIPHERTEXT_SIZE = 2147483648; // max size of encrypted blob- currently 2GB. internal const byte CustomCipherAlgorithmId = 0; // Id used for custom encryption algorithm. - internal const int AES_256_CBC = 1; internal const int AEAD_AES_256_CBC_HMAC_SHA256 = 2; internal const string ENCLAVE_TYPE_VBS = "VBS"; internal const string ENCLAVE_TYPE_SGX = "SGX"; diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj index 6d60225a6d..a63ed87bce 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft.Data.SqlClient.csproj @@ -202,12 +202,6 @@ Microsoft\Data\SqlClient\SqlAeadAes256CbcHmac256Factory.cs - - Microsoft\Data\SqlClient\SqlAes256CbcAlgorithm.cs - - - Microsoft\Data\SqlClient\SqlAes256CbcFactory.cs - Microsoft\Data\SqlClient\SqlAuthenticationParameters.cs diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs index a20a506b52..a86ae7100e 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlSecurityUtility.cs @@ -149,10 +149,6 @@ private static string ValidateAndGetEncryptionAlgorithmName(byte cipherAlgorithm { return SqlAeadAes256CbcHmac256Algorithm.AlgorithmName; } - else if (TdsEnums.AES_256_CBC == cipherAlgorithmId) - { - return SqlAes256CbcAlgorithm.AlgorithmName; - } else { throw SQL.UnknownColumnEncryptionAlgorithmId(cipherAlgorithmId, GetRegisteredCipherAlgorithmIds()); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsEnums.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsEnums.cs index c6ad7fea14..2ea1ce25c7 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsEnums.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsEnums.cs @@ -148,7 +148,7 @@ internal static class TdsEnums public const byte SQLDEBUG_CMD = 0x60; public const byte SQLLOGINACK = 0xad; public const byte SQLFEATUREEXTACK = 0xae; // TDS 7.4 - feature ack - public const byte SQLSESSIONSTATE = 0xe4; // TDS 7.4 - connection resiliency session state + public const byte SQLSESSIONSTATE = 0xe4; // TDS 7.4 - connection resiliency session state public const byte SQLENVCHANGE = 0xe3; // Environment change notification public const byte SQLSECLEVEL = 0xed; // Security level token ??? public const byte SQLROWCRC = 0x39; // ROWCRC datastream??? @@ -199,11 +199,11 @@ internal static class TdsEnums public const byte FEATUREEXT_TERMINATOR = 0xFF; public const byte FEATUREEXT_SRECOVERY = 0x01; public const byte FEATUREEXT_FEDAUTH = 0x02; - // 0x03 is for x_eFeatureExtensionId_Rcs + // 0x03 is for x_eFeatureExtensionId_Rcs public const byte FEATUREEXT_TCE = 0x04; public const byte FEATUREEXT_GLOBALTRANSACTIONS = 0x05; - // 0x06 is for x_eFeatureExtensionId_LoginToken - // 0x07 is for x_eFeatureExtensionId_ClientSideTelemetry + // 0x06 is for x_eFeatureExtensionId_LoginToken + // 0x07 is for x_eFeatureExtensionId_ClientSideTelemetry public const byte FEATUREEXT_AZURESQLSUPPORT = 0x08; public const byte FEATUREEXT_DATACLASSIFICATION = 0x09; public const byte FEATUREEXT_UTF8SUPPORT = 0x0A; @@ -219,7 +219,7 @@ public enum FeatureExtension : uint GlobalTransactions = 1 << (TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS - 1), AzureSQLSupport = 1 << (TdsEnums.FEATUREEXT_AZURESQLSUPPORT - 1), DataClassification = 1 << (TdsEnums.FEATUREEXT_DATACLASSIFICATION - 1), - UTF8Support = 1 << (TdsEnums.FEATUREEXT_UTF8SUPPORT - 1), + UTF8Support = 1 << (TdsEnums.FEATUREEXT_UTF8SUPPORT - 1), SQLDNSCaching = 1 << (TdsEnums.FEATUREEXT_SQLDNSCACHING - 1) } @@ -264,7 +264,7 @@ public enum ActiveDirectoryWorkflow : byte public const byte MAX_NIC_SIZE = 6; // The size of a MAC or client address public const byte SQLVARIANT_SIZE = 2; // size of the fixed portion of a sql variant (type, cbPropBytes) public const byte VERSION_SIZE = 4; // size of the tds version (4 unsigned bytes) - public const int CLIENT_PROG_VER = 0x06000000; // Client interface version + public const int CLIENT_PROG_VER = 0x06000000; // Client interface version public const int YUKON_LOG_REC_FIXED_LEN = 0x5e; // misc public const int TEXT_TIME_STAMP_LEN = 8; @@ -610,8 +610,8 @@ public enum ActiveDirectoryWorkflow : byte // Login data validation Rules // internal const ushort MAXLEN_HOSTNAME = 128; // the client machine name - internal const ushort MAXLEN_CLIENTID = 128; - internal const ushort MAXLEN_CLIENTSECRET = 128; + internal const ushort MAXLEN_CLIENTID = 128; + internal const ushort MAXLEN_CLIENTSECRET = 128; internal const ushort MAXLEN_APPNAME = 128; // the client application name internal const ushort MAXLEN_SERVERNAME = 128; // the server name internal const ushort MAXLEN_CLIENTINTERFACE = 128; // the interface library name @@ -951,7 +951,6 @@ internal enum FedAuthInfoId : byte internal const long MAX_TCE_CIPHERTEXT_SIZE = 2147483648; // max size of encrypted blob- currently 2GB. internal const byte CustomCipherAlgorithmId = 0; // Id used for custom encryption algorithm. - internal const int AES_256_CBC = 1; internal const int AEAD_AES_256_CBC_HMAC_SHA256 = 2; internal const string ENCLAVE_TYPE_VBS = "VBS"; internal const string ENCLAVE_TYPE_SGX = "SGX"; @@ -1100,7 +1099,7 @@ public enum SqlAuthenticationMethod ActiveDirectoryDeviceCodeFlow, #if ADONET_CERT_AUTH SqlCertificate -#endif +#endif } // This enum indicates the state of TransparentNetworkIPResolution // The first attempt when TNIR is on should be sequential. If the first attempt failes next attempts should be parallel. diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAeadAes256CbcHmac256EncryptionKey.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAeadAes256CbcHmac256EncryptionKey.cs index a02247834e..b0109902c6 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAeadAes256CbcHmac256EncryptionKey.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAeadAes256CbcHmac256EncryptionKey.cs @@ -7,7 +7,7 @@ namespace Microsoft.Data.SqlClient { /// - /// Encryption key class containing 4 keys. This class is used by SqlAeadAes256CbcHmac256Algorithm and SqlAes256CbcAlgorithm + /// Encryption key class containing 4 keys. This class is used by SqlAeadAes256CbcHmac256Algorithm /// 1) root key - Main key that is used to derive the keys used in the encryption algorithm /// 2) encryption key - A derived key that is used to encrypt the plain text and generate cipher text /// 3) mac_key - A derived key that is used to compute HMAC of the cipher text diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAes256CbcAlgorithm.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAes256CbcAlgorithm.cs deleted file mode 100644 index 6e8f34172f..0000000000 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAes256CbcAlgorithm.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace Microsoft.Data.SqlClient -{ - /// - /// This class implements AES_256_CBC algorithm. - /// - internal class SqlAes256CbcAlgorithm : SqlAeadAes256CbcHmac256Algorithm - { - /// - /// Algorithm Name - /// - internal new const string AlgorithmName = @"AES_256_CBC"; - - /// - /// Initializes a new instance of SqlAes256CbcAlgorithm algorithm with a given key and encryption type - /// - /// - /// Root encryption key from which three other keys will be derived - /// - /// Encryption Type, accepted values are Deterministic and Randomized. - /// For Deterministic encryption, a synthetic IV will be generated during encryption - /// For Randomized encryption, a random IV will be generated during encryption. - /// - /// - /// Algorithm version - /// - internal SqlAes256CbcAlgorithm(SqlAeadAes256CbcHmac256EncryptionKey encryptionKey, SqlClientEncryptionType encryptionType, byte algorithmVersion) - : base(encryptionKey, encryptionType, algorithmVersion) - { } - - /// - /// Encryption Algorithm - /// Simply call the base class, indicating we don't need an authentication tag. - /// - /// Plaintext data to be encrypted - /// Returns the ciphertext corresponding to the plaintext. - internal override byte[] EncryptData(byte[] plainText) - { - return EncryptData(plainText, hasAuthenticationTag: false); - } - - /// - /// Decryption Algorithm - /// Simply call the base class, indicating we don't have an authentication tag. - /// - /// - /// - internal override byte[] DecryptData(byte[] cipherText) - { - return base.DecryptData(cipherText, hasAuthenticationTag: false); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAes256CbcFactory.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAes256CbcFactory.cs deleted file mode 100644 index 1b6c7ef9bf..0000000000 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlAes256CbcFactory.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Concurrent; -using System.Diagnostics; -using System.Text; - -namespace Microsoft.Data.SqlClient -{ - /// - /// This is a factory class for AES_256_CBC. - /// - internal class SqlAes256CbcFactory : SqlAeadAes256CbcHmac256Factory - { - /// - /// Factory classes caches the SqlAeadAes256CbcHmac256EncryptionKey objects to avoid computation of the derived keys - /// - private readonly ConcurrentDictionary _encryptionAlgorithms = - new ConcurrentDictionary(concurrencyLevel: 4 * Environment.ProcessorCount /* default value in ConcurrentDictionary*/, capacity: 2); - - /// - /// Creates an instance of SqlAes256CbcAlgorithm class with a given key - /// - /// Root key - /// Encryption Type. Expected values are either Deterministic or Randomized. - /// Encryption Algorithm. - /// - internal override SqlClientEncryptionAlgorithm Create(SqlClientSymmetricKey encryptionKey, SqlClientEncryptionType encryptionType, string encryptionAlgorithm) - { - // Callers should have validated the encryption algorithm and the encryption key - Debug.Assert(encryptionKey != null); - Debug.Assert(string.Equals(encryptionAlgorithm, SqlAes256CbcAlgorithm.AlgorithmName, StringComparison.OrdinalIgnoreCase) == true); - - // Validate encryption type - if (!((encryptionType == SqlClientEncryptionType.Deterministic) || (encryptionType == SqlClientEncryptionType.Randomized))) - { - throw SQL.InvalidEncryptionType(SqlAes256CbcAlgorithm.AlgorithmName, - encryptionType, - SqlClientEncryptionType.Deterministic, - SqlClientEncryptionType.Randomized); - } - - // Get the cached encryption algorithm if one exists or create a new one, add it to cache and use it - // - // For now, we only have one version. In future, we may need to parse the algorithm names to derive the version byte. - const byte algorithmVersion = 0x1; - - StringBuilder algorithmKeyBuilder = new StringBuilder(Convert.ToBase64String(encryptionKey.RootKey), SqlSecurityUtility.GetBase64LengthFromByteLength(encryptionKey.RootKey.Length) + 4/*separators, type and version*/); - -#if DEBUG - int capacity = algorithmKeyBuilder.Capacity; -#endif //DEBUG - - algorithmKeyBuilder.Append(":"); - algorithmKeyBuilder.Append((int)encryptionType); - algorithmKeyBuilder.Append(":"); - algorithmKeyBuilder.Append(algorithmVersion); - - string algorithmKey = algorithmKeyBuilder.ToString(); - -#if DEBUG - Debug.Assert(algorithmKey.Length <= capacity, "We needed to allocate a larger array"); -#endif //DEBUG - - SqlAes256CbcAlgorithm aesAlgorithm; - if (!_encryptionAlgorithms.TryGetValue(algorithmKey, out aesAlgorithm)) - { - SqlAeadAes256CbcHmac256EncryptionKey encryptedKey = new SqlAeadAes256CbcHmac256EncryptionKey(encryptionKey.RootKey, SqlAes256CbcAlgorithm.AlgorithmName); - aesAlgorithm = new SqlAes256CbcAlgorithm(encryptedKey, encryptionType, algorithmVersion); - - // In case multiple threads reach here at the same time, the first one adds the value - // the second one will be a no-op, the allocated memory will be claimed by Garbage Collector. - _encryptionAlgorithms.TryAdd(algorithmKey, aesAlgorithm); - } - - return aesAlgorithm; - } - } -} 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 b6ebf913ed..78c3c2f698 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEncryptionAlgorithmFactoryList.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientEncryptionAlgorithmFactoryList.cs @@ -21,9 +21,8 @@ private SqlClientEncryptionAlgorithmFactoryList() { _encryptionAlgoFactoryList = new ConcurrentDictionary(concurrencyLevel: 4 * Environment.ProcessorCount /* default value in ConcurrentDictionary*/, capacity: 2); - // Add wellknown algorithms + // Add wellknown algorithm _encryptionAlgoFactoryList.TryAdd(SqlAeadAes256CbcHmac256Algorithm.AlgorithmName, new SqlAeadAes256CbcHmac256Factory()); - _encryptionAlgoFactoryList.TryAdd(SqlAes256CbcAlgorithm.AlgorithmName, new SqlAes256CbcFactory()); } internal static SqlClientEncryptionAlgorithmFactoryList GetInstance() diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientSymmetricKey.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientSymmetricKey.cs index cb9ab65471..af96d947f0 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientSymmetricKey.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlClientSymmetricKey.cs @@ -30,13 +30,6 @@ internal SqlClientSymmetricKey(byte[] rootKey) _rootKey = rootKey; } - /// - /// Empty destructor for binary back compat. - /// - ~SqlClientSymmetricKey() - { - } - /// /// Returns a copy of the plain text key /// This is needed for actual encryption/decryption. From 00a33640179c8d3b186a0834ee09836e6b47d7f2 Mon Sep 17 00:00:00 2001 From: Wraith Date: Thu, 27 Aug 2020 18:46:04 +0100 Subject: [PATCH 17/24] Small spanifications (#667) --- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 40 ++++++----- .../Data/SqlClient/TdsParserStateObject.cs | 70 ++++++------------- 2 files changed, 42 insertions(+), 68 deletions(-) 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 230509be7f..b0b25d2e09 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 @@ -1619,47 +1619,49 @@ internal byte[] SerializeInt(int v, TdsParserStateObject stateObj) { if (null == stateObj._bIntBytes) { - stateObj._bIntBytes = new byte[4]; + stateObj._bIntBytes = new byte[sizeof(int)]; } else { - Debug.Assert(4 == stateObj._bIntBytes.Length); + Debug.Assert(sizeof(int) == stateObj._bIntBytes.Length); } - int current = 0; - byte[] bytes = stateObj._bIntBytes; - bytes[current++] = (byte)(v & 0xff); - bytes[current++] = (byte)((v >> 8) & 0xff); - bytes[current++] = (byte)((v >> 16) & 0xff); - bytes[current++] = (byte)((v >> 24) & 0xff); - return bytes; + WriteInt(stateObj._bIntBytes.AsSpan(), v); + return stateObj._bIntBytes; } - // - // Takes an int and writes it as an int. - // internal void WriteInt(int v, TdsParserStateObject stateObj) { + Span buffer = stackalloc byte[sizeof(int)]; + WriteInt(buffer, v); if ((stateObj._outBytesUsed + 4) > stateObj._outBuff.Length) { // if all of the int doesn't fit into the buffer - for (int shiftValue = 0; shiftValue < sizeof(int) * 8; shiftValue += 8) + for (int index = 0; index < sizeof(int); index++) { - stateObj.WriteByte((byte)((v >> shiftValue) & 0xff)); + stateObj.WriteByte(buffer[index]); } } else { // all of the int fits into the buffer - // NOTE: We don't use a loop here for performance - stateObj._outBuff[stateObj._outBytesUsed] = (byte)(v & 0xff); - stateObj._outBuff[stateObj._outBytesUsed + 1] = (byte)((v >> 8) & 0xff); - stateObj._outBuff[stateObj._outBytesUsed + 2] = (byte)((v >> 16) & 0xff); - stateObj._outBuff[stateObj._outBytesUsed + 3] = (byte)((v >> 24) & 0xff); + buffer.CopyTo(stateObj._outBuff.AsSpan(stateObj._outBytesUsed, sizeof(int))); stateObj._outBytesUsed += 4; } } + internal static void WriteInt(Span buffer, int value) + { +#if netcoreapp + BitConverter.TryWriteBytes(buffer, value); +#else + buffer[0] = (byte)(value & 0xff); + buffer[1] = (byte)((value >> 8) & 0xff); + buffer[2] = (byte)((value >> 16) & 0xff); + buffer[3] = (byte)((value >> 24) & 0xff); +#endif + } + // // Takes a float and writes it as a 32 bit float. // diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs index a5e84c2a6a..7e9f5a6d67 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObject.cs @@ -1403,36 +1403,28 @@ internal bool TryReadChar(out char value) { Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async"); - byte[] buffer; - int offset; + Span buffer = stackalloc byte[2]; if (((_inBytesUsed + 2) > _inBytesRead) || (_inBytesPacket < 2)) { // If the char isn't fully in the buffer, or if it isn't fully in the packet, // then use ReadByteArray since the logic is there to take care of that. - - if (!TryReadByteArray(_bTmp, 2)) + if (!TryReadByteArray(buffer, 2)) { value = '\0'; return false; } - - buffer = _bTmp; - offset = 0; } else { // The entire char is in the packet and in the buffer, so just return it // and take care of the counters. - - buffer = _inBuff; - offset = _inBytesUsed; - + buffer = _inBuff.AsSpan(_inBytesUsed, 2); _inBytesUsed += 2; _inBytesPacket -= 2; } AssertValidState(); - value = (char)((buffer[offset + 1] << 8) + buffer[offset]); + value = (char)((buffer[1] << 8) + buffer[0]); return true; } @@ -1440,70 +1432,58 @@ internal bool TryReadInt16(out short value) { Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async"); - byte[] buffer; - int offset; + Span buffer = stackalloc byte[2]; if (((_inBytesUsed + 2) > _inBytesRead) || (_inBytesPacket < 2)) { // If the int16 isn't fully in the buffer, or if it isn't fully in the packet, // then use ReadByteArray since the logic is there to take care of that. - - if (!TryReadByteArray(_bTmp, 2)) + if (!TryReadByteArray(buffer, 2)) { value = default; return false; } - - buffer = _bTmp; - offset = 0; } else { // The entire int16 is in the packet and in the buffer, so just return it // and take care of the counters. - - buffer = _inBuff; - offset = _inBytesUsed; - + buffer = _inBuff.AsSpan(_inBytesUsed,2); _inBytesUsed += 2; _inBytesPacket -= 2; } AssertValidState(); - value = (short)((buffer[offset + 1] << 8) + buffer[offset]); + value = (short)((buffer[1] << 8) + buffer[0]); return true; } internal bool TryReadInt32(out int value) { Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async"); + Span buffer = stackalloc byte[4]; if (((_inBytesUsed + 4) > _inBytesRead) || (_inBytesPacket < 4)) { // If the int isn't fully in the buffer, or if it isn't fully in the packet, // then use ReadByteArray since the logic is there to take care of that. - - if (!TryReadByteArray(_bTmp, 4)) + if (!TryReadByteArray(buffer, 4)) { value = 0; return false; } - - AssertValidState(); - value = BitConverter.ToInt32(_bTmp, 0); - return true; } else { // The entire int is in the packet and in the buffer, so just return it // and take care of the counters. - - value = BitConverter.ToInt32(_inBuff, _inBytesUsed); - + buffer = _inBuff.AsSpan(_inBytesUsed, 4); _inBytesUsed += 4; _inBytesPacket -= 4; - - AssertValidState(); - return true; } + + AssertValidState(); + value = (buffer[3] << 24) + (buffer[2] <<16) + (buffer[1] << 8) + buffer[0]; + return true; + } // This method is safe to call when doing async without snapshot @@ -1559,36 +1539,28 @@ internal bool TryReadUInt16(out ushort value) { Debug.Assert(_syncOverAsync || !_asyncReadWithoutSnapshot, "This method is not safe to call when doing sync over async"); - byte[] buffer; - int offset; + Span buffer = stackalloc byte[2]; if (((_inBytesUsed + 2) > _inBytesRead) || (_inBytesPacket < 2)) { // If the uint16 isn't fully in the buffer, or if it isn't fully in the packet, // then use ReadByteArray since the logic is there to take care of that. - - if (!TryReadByteArray(_bTmp, 2)) + if (!TryReadByteArray(buffer, 2)) { value = default; return false; } - - buffer = _bTmp; - offset = 0; } else { // The entire uint16 is in the packet and in the buffer, so just return it // and take care of the counters. - - buffer = _inBuff; - offset = _inBytesUsed; - + buffer = _inBuff.AsSpan(_inBytesUsed, 2); _inBytesUsed += 2; _inBytesPacket -= 2; } AssertValidState(); - value = (ushort)((buffer[offset + 1] << 8) + buffer[offset]); + value = (ushort)((buffer[1] << 8) + buffer[0]); return true; } @@ -3627,8 +3599,8 @@ private void SniWriteStatisticsAndTracing() statistics.RequestNetworkServerTimer(); } } - [Conditional("DEBUG")] + [Conditional("DEBUG")] private void AssertValidState() { if (_inBytesUsed < 0 || _inBytesRead < 0) From fab0fba63b206318e8f6b133072db108a6da1e42 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Thu, 27 Aug 2020 12:12:57 -0700 Subject: [PATCH 18/24] Interop Changes Part 1 - Cleanup Interop source (#665) --- src/Microsoft.Data.SqlClient.sln | 54 -- .../CoreLib/Interop/Unix/Interop.Errors.cs | 209 ------- .../CoreLib/Interop/Unix/Interop.IOErrors.cs | 172 ------ .../CoreLib/Interop/Unix/Interop.Libraries.cs | 12 - .../Interop.Calendar.cs | 33 -- .../Interop.Casing.cs | 23 - .../Interop.Collation.cs | 79 --- .../Interop.ICU.cs | 16 - .../Interop.Idna.cs | 21 - .../Interop.Locale.cs | 40 -- .../Interop.Normalization.cs | 19 - .../Interop.ResultCode.cs | 18 - .../Interop.TimeZoneInfo.cs | 28 - .../Interop.Utils.cs | 52 -- .../Unix/System.Native/Interop.Close.cs | 15 - .../Unix/System.Native/Interop.FLock.cs | 31 - .../Unix/System.Native/Interop.FSync.cs | 15 - .../Unix/System.Native/Interop.FTruncate.cs | 15 - .../Unix/System.Native/Interop.GetCwd.cs | 74 --- .../System.Native/Interop.GetRandomBytes.cs | 21 - .../Unix/System.Native/Interop.LSeek.cs | 22 - .../System.Native/Interop.LockFileRegion.cs | 21 - .../Unix/System.Native/Interop.MksTemps.cs | 17 - .../Unix/System.Native/Interop.Open.cs | 15 - .../Unix/System.Native/Interop.OpenFlags.cs | 27 - .../Unix/System.Native/Interop.PathConf.cs | 28 - .../Unix/System.Native/Interop.Permissions.cs | 32 - .../System.Native/Interop.PosixFAdvise.cs | 36 -- .../Unix/System.Native/Interop.Read.cs | 25 - .../Unix/System.Native/Interop.ReadDir.cs | 102 ---- .../Unix/System.Native/Interop.ReadLink.cs | 63 -- .../Unix/System.Native/Interop.Stat.cs | 65 -- .../Unix/System.Native/Interop.SysLog.cs | 58 -- .../Unix/System.Native/Interop.Unlink.cs | 15 - .../Unix/System.Native/Interop.Write.cs | 27 - .../src/Interop/Unix/Interop.Libraries.cs | 6 - .../Unix/System.Native/Interop.Accept.cs | 15 - .../Unix/System.Native/Interop.Access.cs | 23 - .../Unix/System.Native/Interop.Bind.cs | 16 - .../Unix/System.Native/Interop.ChDir.cs | 15 - .../Unix/System.Native/Interop.ChMod.cs | 15 - .../Unix/System.Native/Interop.Connect.cs | 15 - .../Unix/System.Native/Interop.CopyFile.cs | 16 - .../Interop/Unix/System.Native/Interop.Dup.cs | 16 - .../Interop.EnumerateInterfaceAddresses.cs | 45 -- .../Unix/System.Native/Interop.FChMod.cs | 16 - .../Unix/System.Native/Interop.Fcntl.Pipe.cs | 27 - .../Interop.Fcntl.SetCloseOnExec.cs | 19 - .../Unix/System.Native/Interop.Fcntl.cs | 21 - .../System.Native/Interop.FileDescriptors.cs | 24 - .../Interop.ForkAndExecProcess.cs | 111 ---- .../Interop.GetBytesAvailable.cs | 18 - .../Interop.GetControlCharacters.cs | 37 -- .../System.Native/Interop.GetDomainName.cs | 39 -- .../Interop.GetDomainSocketSizes.cs | 15 - .../Unix/System.Native/Interop.GetEGid.cs | 15 - .../Unix/System.Native/Interop.GetEUid.cs | 15 - .../Unix/System.Native/Interop.GetHostName.cs | 40 -- .../Unix/System.Native/Interop.GetLine.cs | 15 - .../Unix/System.Native/Interop.GetNameInfo.cs | 30 - .../Unix/System.Native/Interop.GetNodeName.cs | 35 -- .../Interop.GetOSArchitecture.cs | 15 - .../Unix/System.Native/Interop.GetPeerID.cs | 15 - .../Unix/System.Native/Interop.GetPeerName.cs | 15 - .../System.Native/Interop.GetPeerUserName.cs | 16 - .../Unix/System.Native/Interop.GetPid.cs | 15 - .../Interop.GetProcessArchitecture.cs | 15 - .../Unix/System.Native/Interop.GetPwUid.cs | 31 - .../System.Native/Interop.GetSetPriority.cs | 63 -- .../Unix/System.Native/Interop.GetSockName.cs | 15 - .../Unix/System.Native/Interop.GetSockOpt.cs | 16 - .../Interop.GetSocketErrorOption.cs | 16 - .../System.Native/Interop.GetTimestamp.cs | 23 - .../Unix/System.Native/Interop.GetUnixName.cs | 21 - .../System.Native/Interop.GetUnixRelease.cs | 14 - .../System.Native/Interop.GetUnixVersion.cs | 36 -- .../System.Native/Interop.GetWindowWidth.cs | 24 - .../Unix/System.Native/Interop.HostEntry.cs | 59 -- .../Unix/System.Native/Interop.IPAddress.cs | 78 --- .../Interop.IPPacketInformation.cs | 24 - .../Interop.InitializeConsole.cs | 17 - .../Unix/System.Native/Interop.IsATty.cs | 16 - .../Unix/System.Native/Interop.Kill.cs | 21 - .../System.Native/Interop.LingerOption.cs | 28 - .../Unix/System.Native/Interop.Link.cs | 15 - .../Unix/System.Native/Interop.Listen.cs | 15 - .../Unix/System.Native/Interop.MAdvise.cs | 20 - .../Unix/System.Native/Interop.MMap.cs | 38 -- .../Unix/System.Native/Interop.MSync.cs | 23 - .../Unix/System.Native/Interop.MUnmap.cs | 15 - .../Unix/System.Native/Interop.MapTcpState.cs | 15 - .../Unix/System.Native/Interop.MemSet.cs | 15 - .../System.Native/Interop.MessageHeader.cs | 29 - .../Unix/System.Native/Interop.MkDir.cs | 15 - .../Interop.MountPoints.FormatInfo.cs | 440 -------------- .../Unix/System.Native/Interop.MountPoints.cs | 40 -- .../System.Native/Interop.MulticastOption.cs | 47 -- .../Unix/System.Native/Interop.POpen.cs | 18 - .../Unix/System.Native/Interop.Pipe.cs | 31 - .../Interop.PlatformSocketSupport.cs | 14 - .../Unix/System.Native/Interop.Poll.cs | 78 --- .../Unix/System.Native/Interop.PrintF.cs | 19 - .../Interop.ProcessorArchitecture.cs | 20 - .../Unix/System.Native/Interop.Read.Pipe.cs | 25 - .../Unix/System.Native/Interop.ReadDir.cs | 86 --- .../Interop.ReadStdinUnbuffered.cs | 21 - .../Unix/System.Native/Interop.RealPath.cs | 20 - .../System.Native/Interop.ReceiveMessage.cs | 16 - .../System.Native/Interop.RegisterForCtrlC.cs | 25 - .../Interop.RegisterForSigChld.cs | 16 - .../Unix/System.Native/Interop.Rename.cs | 23 - .../System.Native/Interop.ResourceLimits.cs | 40 -- .../Interop.RestoreAndHandleCtrl.cs | 14 - .../Unix/System.Native/Interop.RmDir.cs | 22 - .../Unix/System.Native/Interop.SNPrintF.cs | 54 -- .../Interop.SchedGetSetAffinity.cs | 18 - .../Unix/System.Native/Interop.SendFile.cs | 14 - .../Unix/System.Native/Interop.SendMessage.cs | 16 - .../Unix/System.Native/Interop.SetEUid.cs | 15 - .../Interop.SetReceiveTimeout.cs | 16 - .../System.Native/Interop.SetSendTimeout.cs | 16 - .../Interop.SetSignalForBreak.cs | 17 - .../Unix/System.Native/Interop.SetSockOpt.cs | 19 - .../Unix/System.Native/Interop.ShmOpen.cs | 18 - .../Unix/System.Native/Interop.Shutdown.cs | 16 - .../Unix/System.Native/Interop.Socket.cs | 18 - .../System.Native/Interop.SocketAddress.cs | 40 -- .../Unix/System.Native/Interop.SocketEvent.cs | 52 -- .../Unix/System.Native/Interop.Stat.Pipe.cs | 16 - .../Unix/System.Native/Interop.Stat.Span.cs | 41 -- .../Unix/System.Native/Interop.StdinReady.cs | 14 - .../Unix/System.Native/Interop.Sync.cs | 18 - .../Unix/System.Native/Interop.SysConf.cs | 20 - .../Unix/System.Native/Interop.UTimensat.cs | 29 - .../Unix/System.Native/Interop.WaitId.cs | 23 - .../Unix/System.Native/Interop.WaitPid.cs | 24 - .../Unix/System.Native/Interop.Write.Pipe.cs | 24 - .../Interop.CURLcode.cs | 25 - .../System.Net.Http.Native/Interop.Easy.cs | 268 --------- .../Interop.Initialization.cs | 52 -- .../System.Net.Http.Native/Interop.Multi.cs | 104 ---- .../System.Net.Http.Native/Interop.SList.cs | 63 -- .../Interop.VersionInfo.cs | 54 -- .../Interop.GssApiException.cs | 26 +- .../Interop.GssBuffer.cs | 5 +- .../Interop.NetSecurityNative.cs | 81 +-- .../Interop.ASN1.GetIntegerBytes.cs | 45 -- .../Interop.ASN1.Nid.cs | 16 - .../Interop.ASN1.cs | 113 ---- .../Interop.BIO.cs | 39 -- .../Interop.Bignum.cs | 91 --- .../Interop.Crypto.cs | 183 ------ .../Interop.Dsa.cs | 176 ------ .../Interop.ERR.cs | 123 ---- .../Interop.EVP.Cipher.cs | 85 --- .../Interop.EVP.cs | 56 -- .../Interop.EcDsa.ImportExport.cs | 338 ----------- .../Interop.EcDsa.cs | 62 -- .../Interop.EcKey.cs | 87 --- .../Interop.Encode.cs | 46 -- .../Interop.EvpPkey.Dsa.cs | 20 - .../Interop.EvpPkey.EcKey.cs | 20 - .../Interop.EvpPkey.Ecdh.cs | 43 -- .../Interop.EvpPkey.Rsa.cs | 20 - .../Interop.EvpPkey.cs | 22 - .../Interop.Hmac.cs | 31 - .../Interop.Initialization.cs | 47 -- .../Interop.LookupFriendlyNameByOid.cs | 15 - .../Interop.OpenSsl.cs | 558 ------------------ .../Interop.OpenSslVersion.cs | 31 - .../Interop.Pkcs12.cs | 45 -- .../Interop.Pkcs7.cs | 61 -- .../Interop.RAND.cs | 23 - .../Interop.Rsa.cs | 217 ------- .../Interop.SetProtocolOptions.cs | 17 - .../Interop.Ssl.cs | 341 ----------- .../Interop.SslCtx.cs | 100 ---- .../Interop.SslCtxOptions.cs | 36 -- .../Interop.X509.cs | 214 ------- .../Interop.X509Ext.cs | 41 -- .../Interop.X509Name.cs | 71 --- .../Interop.X509Stack.cs | 76 --- .../Interop.X509StoreCtx.cs | 63 -- .../src/Interop/Unix/libdl/Interop.dlopen.cs | 17 - .../src/Interop/Unix/libdl/Interop.dlsym.cs | 15 - .../src/Interop/Windows/Interop.Errors.cs | 71 --- .../src/Interop/Windows/Interop.Libraries.cs | 26 - .../Interop.GetTokenInformation_void.cs | 21 - .../Interop.OpenProcessToken_IntPtr.cs | 20 - ....OpenProcessToken_SafeAccessTokenHandle.cs | 17 - .../advapi32/Interop.TOKEN_ELEVATION.cs | 15 - .../Interop.TOKEN_INFORMATION_CLASS.cs | 57 -- .../kernel32/Interop.FileOperations.cs | 28 - .../Interop/Windows/sspicli/Interop.SSPI.cs | 50 +- .../Win32/SafeHandles/GssSafeHandles.cs | 58 +- .../Net/Security/NegotiateStreamPal.Unix.cs | 192 +----- .../Security/Unix/SafeDeleteNegoContext.cs | 3 - .../Net/Security/Unix/SafeFreeCredentials.cs | 11 +- .../Security/Unix/SafeFreeNegoCredentials.cs | 3 - .../src/Microsoft.Data.SqlClient.csproj | 3 - .../Microsoft/Data/SqlClient/SNI/SNIProxy.cs | 129 ++-- .../Data/SqlClient/TdsParser.Unix.cs | 2 +- .../Data/SqlClient/TdsParser.Windows.cs | 5 +- .../SqlClient/TdsParserStateObjectManaged.cs | 29 +- .../Microsoft.Data.SqlClient.Tests.csproj | 3 - .../SqlConnectionBasicTests.cs | 2 +- .../DataCommon/AssemblyResourceManager.cs | 28 +- ....Data.SqlClient.ManualTesting.Tests.csproj | 3 - .../ExceptionTest/ConnectionExceptionTest.cs | 7 +- .../CoreFx.Private.TestUtilities.csproj | 121 ---- .../CoreFx.Private.TestUtilities.rd.xml | 7 - .../System/AdminHelpers.Unix.cs | 24 - .../System/AdminHelpers.Windows.cs | 44 -- .../System/AdminHelpers.cs | 33 -- .../Net/PlatformDetection.Networking.cs | 14 - .../System/PlatformDetection.NetFx.cs | 68 --- .../System/PlatformDetection.NonNetFx.cs | 62 -- .../System/PlatformDetection.Unix.cs | 244 -------- .../System/PlatformDetection.Windows.cs | 272 --------- .../System/PlatformDetection.cs | 133 ----- .../System/TestEnvironment.cs | 22 - .../System/TheoryExtensions.cs | 38 -- .../Extensions}/AssertExtensions.cs | 0 .../Extensions/PlatformDetection.cs} | 8 +- .../Microsoft.DotNet.XUnitExtensions.csproj | 3 + tools/props/Versions.props | 1 + 226 files changed, 177 insertions(+), 10487 deletions(-) delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.Errors.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.IOErrors.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.Libraries.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Casing.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Collation.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ICU.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Idna.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Locale.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Utils.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Close.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FLock.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FSync.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FTruncate.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetCwd.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetRandomBytes.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LSeek.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LockFileRegion.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.MksTemps.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Open.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.OpenFlags.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PathConf.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Permissions.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PosixFAdvise.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Read.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadDir.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadLink.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Stat.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.SysLog.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Unlink.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Write.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Accept.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Access.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Bind.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ChDir.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ChMod.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Connect.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.CopyFile.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Dup.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.EnumerateInterfaceAddresses.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.FChMod.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Fcntl.Pipe.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Fcntl.SetCloseOnExec.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Fcntl.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.FileDescriptors.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ForkAndExecProcess.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetBytesAvailable.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetControlCharacters.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetDomainName.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetDomainSocketSizes.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetEGid.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetEUid.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetHostName.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetLine.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetNameInfo.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetNodeName.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetOSArchitecture.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerID.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerName.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerUserName.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPid.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetProcessArchitecture.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPwUid.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSetPriority.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSockName.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSockOpt.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSocketErrorOption.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetTimestamp.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetUnixName.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetUnixRelease.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetUnixVersion.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetWindowWidth.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.HostEntry.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.IPAddress.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.IPPacketInformation.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.InitializeConsole.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.IsATty.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Kill.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.LingerOption.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Link.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Listen.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MAdvise.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MMap.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MSync.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MUnmap.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MapTcpState.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MemSet.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MessageHeader.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MkDir.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MulticastOption.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.POpen.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Pipe.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.PlatformSocketSupport.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Poll.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.PrintF.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ProcessorArchitecture.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Read.Pipe.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ReadDir.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ReadStdinUnbuffered.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RealPath.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ReceiveMessage.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RegisterForCtrlC.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RegisterForSigChld.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Rename.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ResourceLimits.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RestoreAndHandleCtrl.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RmDir.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SNPrintF.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SchedGetSetAffinity.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SendFile.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SendMessage.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetEUid.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetReceiveTimeout.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetSendTimeout.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetSignalForBreak.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetSockOpt.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ShmOpen.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Shutdown.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Socket.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SocketAddress.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SocketEvent.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Stat.Pipe.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Stat.Span.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.StdinReady.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Sync.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SysConf.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.UTimensat.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.WaitId.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.WaitPid.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Write.Pipe.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.CURLcode.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.Easy.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.Initialization.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.Multi.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.SList.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.VersionInfo.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.GetIntegerBytes.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.Nid.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.BIO.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Bignum.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Crypto.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Dsa.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ERR.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EVP.Cipher.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EVP.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcKey.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Encode.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Dsa.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.EcKey.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Ecdh.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Rsa.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Hmac.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Initialization.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.LookupFriendlyNameByOid.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSslVersion.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Pkcs12.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Pkcs7.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.RAND.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Rsa.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SetProtocolOptions.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtxOptions.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509Ext.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509Name.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509Stack.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509StoreCtx.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/libdl/Interop.dlopen.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/libdl/Interop.dlsym.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.GetTokenInformation_void.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.OpenProcessToken_IntPtr.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.OpenProcessToken_SafeAccessTokenHandle.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.TOKEN_ELEVATION.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.TOKEN_INFORMATION_CLASS.cs delete mode 100644 src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/kernel32/Interop.FileOperations.cs delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/CoreFx.Private.TestUtilities.csproj delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/Resources/CoreFx.Private.TestUtilities.rd.xml delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AdminHelpers.Unix.cs delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AdminHelpers.Windows.cs delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AdminHelpers.cs delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/Net/PlatformDetection.Networking.cs delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.NetFx.cs delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.NonNetFx.cs delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.Unix.cs delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.Windows.cs delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.cs delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/TestEnvironment.cs delete mode 100644 src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/TheoryExtensions.cs rename src/Microsoft.Data.SqlClient/tests/tools/{CoreFx.Private.TestUtilities/System => Microsoft.DotNet.XUnitExtensions/Extensions}/AssertExtensions.cs (100%) rename src/Microsoft.Data.SqlClient/{netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSid.cs => tests/tools/Microsoft.DotNet.XUnitExtensions/Extensions/PlatformDetection.cs} (52%) diff --git a/src/Microsoft.Data.SqlClient.sln b/src/Microsoft.Data.SqlClient.sln index eea16852c3..3b709a16cf 100644 --- a/src/Microsoft.Data.SqlClient.sln +++ b/src/Microsoft.Data.SqlClient.sln @@ -15,11 +15,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TDS", "Microsoft.Data.SqlCl {FDA6971D-9F57-4DA4-B10A-261C91684CFC} = {FDA6971D-9F57-4DA4-B10A-261C91684CFC} EndProjectSection EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CoreFx.Private.TestUtilities", "Microsoft.Data.SqlClient\tests\tools\CoreFx.Private.TestUtilities\CoreFx.Private.TestUtilities.csproj", "{EBDB0247-CA43-4226-B7A1-8FEF21061D09}" - ProjectSection(ProjectDependencies) = postProject - {FDA6971D-9F57-4DA4-B10A-261C91684CFC} = {FDA6971D-9F57-4DA4-B10A-261C91684CFC} - EndProjectSection -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Data.SqlClient.Tests", "Microsoft.Data.SqlClient\tests\FunctionalTests\Microsoft.Data.SqlClient.Tests.csproj", "{D2D1E2D1-B6E0-489F-A36D-1F3047AB87B9}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Data.SqlClient", "Microsoft.Data.SqlClient\netcore\src\Microsoft.Data.SqlClient.csproj", "{37431336-5307-4184-9356-C4B7E47DC714}" @@ -387,54 +382,6 @@ Global {8DC9D1A0-351B-47BC-A90F-B9DA542550E9}.Release|x64.Build.0 = Release|Any CPU {8DC9D1A0-351B-47BC-A90F-B9DA542550E9}.Release|x86.ActiveCfg = Release|Any CPU {8DC9D1A0-351B-47BC-A90F-B9DA542550E9}.Release|x86.Build.0 = Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.Debug|x64.ActiveCfg = Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.Debug|x64.Build.0 = Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.Debug|x86.ActiveCfg = Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.Debug|x86.Build.0 = Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.net46-Debug|Any CPU.ActiveCfg = net46-Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.net46-Debug|Any CPU.Build.0 = net46-Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.net46-Debug|x64.ActiveCfg = net46-Debug|x64 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.net46-Debug|x64.Build.0 = net46-Debug|x64 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.net46-Debug|x86.ActiveCfg = net46-Debug|x86 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.net46-Debug|x86.Build.0 = net46-Debug|x86 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.net46-Release|Any CPU.ActiveCfg = net46-Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.net46-Release|Any CPU.Build.0 = net46-Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.net46-Release|x64.ActiveCfg = net46-Release|x64 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.net46-Release|x64.Build.0 = net46-Release|x64 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.net46-Release|x86.ActiveCfg = net46-Release|x86 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.net46-Release|x86.Build.0 = net46-Release|x86 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp2.1-Debug|Any CPU.ActiveCfg = netcoreapp2.1-Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp2.1-Debug|Any CPU.Build.0 = netcoreapp2.1-Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp2.1-Debug|x64.ActiveCfg = netcoreapp2.1-Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp2.1-Debug|x64.Build.0 = netcoreapp2.1-Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp2.1-Debug|x86.ActiveCfg = netcoreapp2.1-Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp2.1-Debug|x86.Build.0 = netcoreapp2.1-Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp2.1-Release|Any CPU.ActiveCfg = netcoreapp2.1-Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp2.1-Release|Any CPU.Build.0 = netcoreapp2.1-Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp2.1-Release|x64.ActiveCfg = netcoreapp2.1-Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp2.1-Release|x64.Build.0 = netcoreapp2.1-Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp2.1-Release|x86.ActiveCfg = netcoreapp2.1-Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp2.1-Release|x86.Build.0 = netcoreapp2.1-Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp3.1-Debug|Any CPU.ActiveCfg = netcoreapp3.1-Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp3.1-Debug|Any CPU.Build.0 = netcoreapp3.1-Debug|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp3.1-Debug|x64.ActiveCfg = netcoreapp3.1-Debug|x64 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp3.1-Debug|x64.Build.0 = netcoreapp3.1-Debug|x64 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp3.1-Debug|x86.ActiveCfg = netcoreapp3.1-Debug|x86 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp3.1-Debug|x86.Build.0 = netcoreapp3.1-Debug|x86 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp3.1-Release|Any CPU.ActiveCfg = netcoreapp3.1-Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp3.1-Release|Any CPU.Build.0 = netcoreapp3.1-Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp3.1-Release|x64.ActiveCfg = netcoreapp3.1-Release|x64 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp3.1-Release|x64.Build.0 = netcoreapp3.1-Release|x64 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp3.1-Release|x86.ActiveCfg = netcoreapp3.1-Release|x86 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.netcoreapp3.1-Release|x86.Build.0 = netcoreapp3.1-Release|x86 - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.Release|Any CPU.Build.0 = Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.Release|x64.ActiveCfg = Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.Release|x64.Build.0 = Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.Release|x86.ActiveCfg = Release|Any CPU - {EBDB0247-CA43-4226-B7A1-8FEF21061D09}.Release|x86.Build.0 = Release|Any CPU {D2D1E2D1-B6E0-489F-A36D-1F3047AB87B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D2D1E2D1-B6E0-489F-A36D-1F3047AB87B9}.Debug|Any CPU.Build.0 = Debug|Any CPU {D2D1E2D1-B6E0-489F-A36D-1F3047AB87B9}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -1094,7 +1041,6 @@ Global {1FF891B4-D3DE-4CCE-887C-CB48F5351A45} = {0CC4817A-12F3-4357-912C-09315FAAD008} {978063D3-FBB5-4E10-8C45-67C90BE1B931} = {0CC4817A-12F3-4357-912C-09315FAAD008} {8DC9D1A0-351B-47BC-A90F-B9DA542550E9} = {0CC4817A-12F3-4357-912C-09315FAAD008} - {EBDB0247-CA43-4226-B7A1-8FEF21061D09} = {0CC4817A-12F3-4357-912C-09315FAAD008} {D2D1E2D1-B6E0-489F-A36D-1F3047AB87B9} = {0CC4817A-12F3-4357-912C-09315FAAD008} {37431336-5307-4184-9356-C4B7E47DC714} = {28E5EFE6-C9DD-4FF9-9FEC-532F72DFFA6E} {D1392B54-998A-4F27-BC17-4CE149117BCC} = {0CC4817A-12F3-4357-912C-09315FAAD008} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.Errors.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.Errors.cs deleted file mode 100644 index 9cb05809db..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.Errors.cs +++ /dev/null @@ -1,209 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - /// Common Unix errno error codes. - internal enum Error - { - // These values were defined in src/Native/System.Native/fxerrno.h - // - // They compare against values obtained via Interop.Sys.GetLastError() not Marshal.GetLastWin32Error() - // which obtains the raw errno that varies between unixes. The strong typing as an enum is meant to - // prevent confusing the two. Casting to or from int is suspect. Use GetLastErrorInfo() if you need to - // correlate these to the underlying platform values or obtain the corresponding error message. - // - - SUCCESS = 0, - - E2BIG = 0x10001, // Argument list too long. - EACCES = 0x10002, // Permission denied. - EADDRINUSE = 0x10003, // Address in use. - EADDRNOTAVAIL = 0x10004, // Address not available. - EAFNOSUPPORT = 0x10005, // Address family not supported. - EAGAIN = 0x10006, // Resource unavailable, try again (same value as EWOULDBLOCK), - EALREADY = 0x10007, // Connection already in progress. - EBADF = 0x10008, // Bad file descriptor. - EBADMSG = 0x10009, // Bad message. - EBUSY = 0x1000A, // Device or resource busy. - ECANCELED = 0x1000B, // Operation canceled. - ECHILD = 0x1000C, // No child processes. - ECONNABORTED = 0x1000D, // Connection aborted. - ECONNREFUSED = 0x1000E, // Connection refused. - ECONNRESET = 0x1000F, // Connection reset. - EDEADLK = 0x10010, // Resource deadlock would occur. - EDESTADDRREQ = 0x10011, // Destination address required. - EDOM = 0x10012, // Mathematics argument out of domain of function. - EDQUOT = 0x10013, // Reserved. - EEXIST = 0x10014, // File exists. - EFAULT = 0x10015, // Bad address. - EFBIG = 0x10016, // File too large. - EHOSTUNREACH = 0x10017, // Host is unreachable. - EIDRM = 0x10018, // Identifier removed. - EILSEQ = 0x10019, // Illegal byte sequence. - EINPROGRESS = 0x1001A, // Operation in progress. - EINTR = 0x1001B, // Interrupted function. - EINVAL = 0x1001C, // Invalid argument. - EIO = 0x1001D, // I/O error. - EISCONN = 0x1001E, // Socket is connected. - EISDIR = 0x1001F, // Is a directory. - ELOOP = 0x10020, // Too many levels of symbolic links. - EMFILE = 0x10021, // File descriptor value too large. - EMLINK = 0x10022, // Too many links. - EMSGSIZE = 0x10023, // Message too large. - EMULTIHOP = 0x10024, // Reserved. - ENAMETOOLONG = 0x10025, // Filename too long. - ENETDOWN = 0x10026, // Network is down. - ENETRESET = 0x10027, // Connection aborted by network. - ENETUNREACH = 0x10028, // Network unreachable. - ENFILE = 0x10029, // Too many files open in system. - ENOBUFS = 0x1002A, // No buffer space available. - ENODEV = 0x1002C, // No such device. - ENOENT = 0x1002D, // No such file or directory. - ENOEXEC = 0x1002E, // Executable file format error. - ENOLCK = 0x1002F, // No locks available. - ENOLINK = 0x10030, // Reserved. - ENOMEM = 0x10031, // Not enough space. - ENOMSG = 0x10032, // No message of the desired type. - ENOPROTOOPT = 0x10033, // Protocol not available. - ENOSPC = 0x10034, // No space left on device. - ENOSYS = 0x10037, // Function not supported. - ENOTCONN = 0x10038, // The socket is not connected. - ENOTDIR = 0x10039, // Not a directory or a symbolic link to a directory. - ENOTEMPTY = 0x1003A, // Directory not empty. - ENOTRECOVERABLE = 0x1003B, // State not recoverable. - ENOTSOCK = 0x1003C, // Not a socket. - ENOTSUP = 0x1003D, // Not supported (same value as EOPNOTSUP). - ENOTTY = 0x1003E, // Inappropriate I/O control operation. - ENXIO = 0x1003F, // No such device or address. - EOVERFLOW = 0x10040, // Value too large to be stored in data type. - EOWNERDEAD = 0x10041, // Previous owner died. - EPERM = 0x10042, // Operation not permitted. - EPIPE = 0x10043, // Broken pipe. - EPROTO = 0x10044, // Protocol error. - EPROTONOSUPPORT = 0x10045, // Protocol not supported. - EPROTOTYPE = 0x10046, // Protocol wrong type for socket. - ERANGE = 0x10047, // Result too large. - EROFS = 0x10048, // Read-only file system. - ESPIPE = 0x10049, // Invalid seek. - ESRCH = 0x1004A, // No such process. - ESTALE = 0x1004B, // Reserved. - ETIMEDOUT = 0x1004D, // Connection timed out. - ETXTBSY = 0x1004E, // Text file busy. - EXDEV = 0x1004F, // Cross-device link. - ESOCKTNOSUPPORT = 0x1005E, // Socket type not supported. - EPFNOSUPPORT = 0x10060, // Protocol family not supported. - ESHUTDOWN = 0x1006C, // Socket shutdown. - EHOSTDOWN = 0x10070, // Host is down. - ENODATA = 0x10071, // No data available. - - // POSIX permits these to have the same value and we make them always equal so - // that CoreFX cannot introduce a dependency on distinguishing between them that - // would not work on all platforms. - EOPNOTSUPP = ENOTSUP, // Operation not supported on socket. - EWOULDBLOCK = EAGAIN, // Operation would block. - } - - - // Represents a platform-agnostic Error and underlying platform-specific errno - internal struct ErrorInfo - { - private Error _error; - private int _rawErrno; - - internal ErrorInfo(int errno) - { - _error = Interop.Sys.ConvertErrorPlatformToPal(errno); - _rawErrno = errno; - } - - internal ErrorInfo(Error error) - { - _error = error; - _rawErrno = -1; - } - - internal Error Error - { - get { return _error; } - } - - internal int RawErrno - { - get { return _rawErrno == -1 ? (_rawErrno = Interop.Sys.ConvertErrorPalToPlatform(_error)) : _rawErrno; } - } - - internal string GetErrorMessage() - { - return Interop.Sys.StrError(RawErrno); - } - - public override string ToString() - { - return string.Format( - "RawErrno: {0} Error: {1} GetErrorMessage: {2}", // No localization required; text is member names used for debugging purposes - RawErrno, Error, GetErrorMessage()); - } - } - - internal partial class Sys - { - internal static Error GetLastError() - { - return ConvertErrorPlatformToPal(Marshal.GetLastWin32Error()); - } - - internal static ErrorInfo GetLastErrorInfo() - { - return new ErrorInfo(Marshal.GetLastWin32Error()); - } - - internal static unsafe string StrError(int platformErrno) - { - int maxBufferLength = 1024; // should be long enough for most any UNIX error - byte* buffer = stackalloc byte[maxBufferLength]; - byte* message = StrErrorR(platformErrno, buffer, maxBufferLength); - - if (message == null) - { - // This means the buffer was not large enough, but still contains - // as much of the error message as possible and is guaranteed to - // be null-terminated. We're not currently resizing/retrying because - // maxBufferLength is large enough in practice, but we could do - // so here in the future if necessary. - message = buffer; - } - - return Marshal.PtrToStringAnsi((IntPtr)message); - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPlatformToPal")] - internal static extern Error ConvertErrorPlatformToPal(int platformErrno); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPalToPlatform")] - internal static extern int ConvertErrorPalToPlatform(Error error); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_StrErrorR")] - private static extern unsafe byte* StrErrorR(int platformErrno, byte* buffer, int bufferSize); - } -} - -// NOTE: extension method can't be nested inside Interop class. -internal static class InteropErrorExtensions -{ - // Intended usage is e.g. Interop.Error.EFAIL.Info() for brevity - // vs. new Interop.ErrorInfo(Interop.Error.EFAIL) for synthesizing - // errors. Errors originated from the system should be obtained - // via GetLastErrorInfo(), not GetLastError().Info() as that will - // convert twice, which is not only inefficient but also lossy if - // we ever encounter a raw errno that no equivalent in the Error - // enum. - public static Interop.ErrorInfo Info(this Interop.Error error) - { - return new Interop.ErrorInfo(error); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.IOErrors.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.IOErrors.cs deleted file mode 100644 index d23744fba2..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.IOErrors.cs +++ /dev/null @@ -1,172 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.IO; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - private static void ThrowExceptionForIoErrno(ErrorInfo errorInfo, string path, bool isDirectory, Func errorRewriter) - { - Debug.Assert(errorInfo.Error != Error.SUCCESS); - Debug.Assert(errorInfo.Error != Error.EINTR, "EINTR errors should be handled by the native shim and never bubble up to managed code"); - - if (errorRewriter != null) - { - errorInfo = errorRewriter(errorInfo); - } - - throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory); - } - - internal static void CheckIo(Error error, string path = null, bool isDirectory = false, Func errorRewriter = null) - { - if (error != Interop.Error.SUCCESS) - { - ThrowExceptionForIoErrno(error.Info(), path, isDirectory, errorRewriter); - } - } - - /// - /// Validates the result of system call that returns greater than or equal to 0 on success - /// and less than 0 on failure, with errno set to the error code. - /// If the system call failed for any reason, an exception is thrown. Otherwise, the system call succeeded. - /// - /// The result of the system call. - /// The path with which this error is associated. This may be null. - /// true if the is known to be a directory; otherwise, false. - /// Optional function to change an error code prior to processing it. - /// - /// On success, returns the non-negative result long that was validated. - /// - internal static long CheckIo(long result, string path = null, bool isDirectory = false, Func errorRewriter = null) - { - if (result < 0) - { - ThrowExceptionForIoErrno(Sys.GetLastErrorInfo(), path, isDirectory, errorRewriter); - } - - return result; - } - - /// - /// Validates the result of system call that returns greater than or equal to 0 on success - /// and less than 0 on failure, with errno set to the error code. - /// If the system call failed for any reason, an exception is thrown. Otherwise, the system call succeeded. - /// - /// - /// On success, returns the non-negative result int that was validated. - /// - internal static int CheckIo(int result, string path = null, bool isDirectory = false, Func errorRewriter = null) - { - CheckIo((long)result, path, isDirectory, errorRewriter); - - return result; - } - - /// - /// Validates the result of system call that returns greater than or equal to 0 on success - /// and less than 0 on failure, with errno set to the error code. - /// If the system call failed for any reason, an exception is thrown. Otherwise, the system call succeeded. - /// - /// - /// On success, returns the non-negative result IntPtr that was validated. - /// - internal static IntPtr CheckIo(IntPtr result, string path = null, bool isDirectory = false, Func errorRewriter = null) - { - CheckIo((long)result, path, isDirectory, errorRewriter); - - return result; - } - - /// - /// Validates the result of system call that returns greater than or equal to 0 on success - /// and less than 0 on failure, with errno set to the error code. - /// If the system call failed for any reason, an exception is thrown. Otherwise, the system call succeeded. - /// - /// - /// On success, returns the valid SafeFileHandle that was validated. - /// - internal static TSafeHandle CheckIo(TSafeHandle handle, string path = null, bool isDirectory = false, Func errorRewriter = null) - where TSafeHandle : SafeHandle - { - if (handle.IsInvalid) - { - ThrowExceptionForIoErrno(Sys.GetLastErrorInfo(), path, isDirectory, errorRewriter); - } - - return handle; - } - - /// - /// Gets an Exception to represent the supplied error info. - /// - /// The error info - /// The path with which this error is associated. This may be null. - /// true if the is known to be a directory; otherwise, false. - /// - internal static Exception GetExceptionForIoErrno(ErrorInfo errorInfo, string path = null, bool isDirectory = false) - { - // Translate the errno into a known set of exception types. For cases where multiple errnos map - // to the same exception type, include an inner exception with the details. - switch (errorInfo.Error) - { - case Error.ENOENT: - if (isDirectory) - { - return !string.IsNullOrEmpty(path) ? - new DirectoryNotFoundException(Strings.Format(Strings.IO_PathNotFound_Path, path)) : - new DirectoryNotFoundException(Strings.IO_PathNotFound_NoPathName); - } - else - { - return !string.IsNullOrEmpty(path) ? - new FileNotFoundException(Strings.Format(Strings.IO_FileNotFound_FileName, path), path) : - new FileNotFoundException(Strings.IO_FileNotFound); - } - - case Error.EACCES: - case Error.EBADF: - case Error.EPERM: - Exception inner = GetIOException(errorInfo); - return !string.IsNullOrEmpty(path) ? - new UnauthorizedAccessException(Strings.Format(Strings.UnauthorizedAccess_IODenied_Path, path), inner) : - new UnauthorizedAccessException(Strings.UnauthorizedAccess_IODenied_NoPathName, inner); - - case Error.ENAMETOOLONG: - return !string.IsNullOrEmpty(path) ? - new PathTooLongException(Strings.Format(Strings.IO_PathTooLong_Path, path)) : - new PathTooLongException(Strings.IO_PathTooLong); - - case Error.EWOULDBLOCK: - return !string.IsNullOrEmpty(path) ? - new IOException(Strings.Format(Strings.IO_SharingViolation_File, path), errorInfo.RawErrno) : - new IOException(Strings.IO_SharingViolation_NoFileName, errorInfo.RawErrno); - - case Error.ECANCELED: - return new OperationCanceledException(); - - case Error.EFBIG: - return new ArgumentOutOfRangeException("value", Strings.ArgumentOutOfRange_FileLengthTooBig); - - case Error.EEXIST: - if (!string.IsNullOrEmpty(path)) - { - return new IOException(Strings.Format(Strings.IO_FileExists_Name, path), errorInfo.RawErrno); - } - goto default; - - default: - return GetIOException(errorInfo); - } - } - - internal static Exception GetIOException(Interop.ErrorInfo errorInfo) - { - return new IOException(errorInfo.GetErrorMessage(), errorInfo.RawErrno); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.Libraries.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.Libraries.cs deleted file mode 100644 index 02d0092445..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/Interop.Libraries.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -internal static partial class Interop -{ - internal static partial class Libraries - { - internal const string GlobalizationNative = "System.Globalization.Native"; - internal const string SystemNative = "System.Native"; - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs deleted file mode 100644 index 55553cc7ea..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Globalization - { - internal delegate void EnumCalendarInfoCallback( - [MarshalAs(UnmanagedType.LPWStr)] string calendarString, - IntPtr context); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetCalendars")] - internal static extern int GetCalendars(string localeName, CalendarId[] calendars, int calendarsCapacity); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetCalendarInfo")] - internal static extern ResultCode GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType calendarDataType, [Out] StringBuilder result, int resultCapacity); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_EnumCalendarInfo")] - internal static extern bool EnumCalendarInfo(EnumCalendarInfoCallback callback, string localeName, CalendarId calendarId, CalendarDataType calendarDataType, IntPtr context); - - [DllImport(Libraries.GlobalizationNative, EntryPoint = "GlobalizationNative_GetLatestJapaneseEra")] - internal static extern int GetLatestJapaneseEra(); - - [DllImport(Libraries.GlobalizationNative, EntryPoint = "GlobalizationNative_GetJapaneseEraStartDate")] - internal static extern bool GetJapaneseEraStartDate(int era, out int startYear, out int startMonth, out int startDay); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Casing.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Casing.cs deleted file mode 100644 index 503a864d69..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Casing.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Security; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Globalization - { - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ChangeCase")] - internal static extern unsafe void ChangeCase(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ChangeCaseInvariant")] - internal static extern unsafe void ChangeCaseInvariant(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ChangeCaseTurkish")] - internal static extern unsafe void ChangeCaseTurkish(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Collation.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Collation.cs deleted file mode 100644 index aeeb60ff77..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Collation.cs +++ /dev/null @@ -1,79 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Security; - -internal static partial class Interop -{ - internal static partial class Globalization - { - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetSortHandle")] - internal static extern unsafe ResultCode GetSortHandle(byte[] localeName, out SafeSortHandle sortHandle); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CloseSortHandle")] - internal static extern unsafe void CloseSortHandle(IntPtr handle); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CompareString")] - internal static extern unsafe int CompareString(SafeSortHandle sortHandle, char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len, CompareOptions options); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOf")] - internal static extern unsafe int IndexOf(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options, int* matchLengthPtr); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_LastIndexOf")] - internal static extern unsafe int LastIndexOf(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOfOrdinalIgnoreCase")] - internal static extern unsafe int IndexOfOrdinalIgnoreCase(string target, int cwTargetLength, char* pSource, int cwSourceLength, bool findLast); - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOfOrdinalIgnoreCase")] - internal static extern unsafe int IndexOfOrdinalIgnoreCase(char* target, int cwTargetLength, char* pSource, int cwSourceLength, bool findLast); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_StartsWith")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool StartsWith(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* source, int cwSourceLength, CompareOptions options); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_EndsWith")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool EndsWith(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* source, int cwSourceLength, CompareOptions options); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_StartsWith")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool StartsWith(SafeSortHandle sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_EndsWith")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool EndsWith(SafeSortHandle sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetSortKey")] - internal static extern unsafe int GetSortKey(SafeSortHandle sortHandle, string str, int strLength, byte* sortKey, int sortKeyLength, CompareOptions options); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CompareStringOrdinalIgnoreCase")] - internal static extern unsafe int CompareStringOrdinalIgnoreCase(char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len); - - [DllImport(Libraries.GlobalizationNative, EntryPoint = "GlobalizationNative_GetSortVersion")] - internal static extern int GetSortVersion(SafeSortHandle sortHandle); - - internal class SafeSortHandle : SafeHandle - { - private SafeSortHandle() : - base(IntPtr.Zero, true) - { - } - - public override bool IsInvalid - { - get { return handle == IntPtr.Zero; } - } - - protected override bool ReleaseHandle() - { - CloseSortHandle(handle); - SetHandle(IntPtr.Zero); - return true; - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ICU.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ICU.cs deleted file mode 100644 index a16c813b2f..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ICU.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; - -internal static partial class Interop -{ - internal static partial class Globalization - { - [DllImport(Libraries.GlobalizationNative, EntryPoint = "GlobalizationNative_LoadICU")] - internal static extern int LoadICU(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Idna.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Idna.cs deleted file mode 100644 index 89b6c3cebe..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Idna.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Globalization - { - internal const int AllowUnassigned = 0x1; - internal const int UseStd3AsciiRules = 0x2; - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ToAscii")] - internal static extern unsafe int ToAscii(uint flags, char* src, int srcLen, char* dstBuffer, int dstBufferCapacity); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ToUnicode")] - internal static extern unsafe int ToUnicode(uint flags, char* src, int srcLen, char* dstBuffer, int dstBufferCapacity); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Locale.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Locale.cs deleted file mode 100644 index b6f5fbec1c..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Locale.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Globalization - { - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleName")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool GetLocaleName(string localeName, [Out] StringBuilder value, int valueLength); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleInfoString")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool GetLocaleInfoString(string localeName, uint localeStringData, [Out] StringBuilder value, int valueLength); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetDefaultLocaleName")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool GetDefaultLocaleName([Out] StringBuilder value, int valueLength); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleTimeFormat")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool GetLocaleTimeFormat(string localeName, bool shortFormat, [Out] StringBuilder value, int valueLength); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleInfoInt")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool GetLocaleInfoInt(string localeName, uint localeNumberData, ref int value); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleInfoGroupingSizes")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool GetLocaleInfoGroupingSizes(string localeName, uint localeGroupingData, ref int primaryGroupSize, ref int secondaryGroupSize); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocales")] - internal static extern unsafe int GetLocales([Out] char[] value, int valueLength); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs deleted file mode 100644 index d442da0ea1..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Globalization - { - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IsNormalized")] - internal static extern int IsNormalized(NormalizationForm normalizationForm, string src, int srcLen); - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_NormalizeString")] - internal static extern int NormalizeString(NormalizationForm normalizationForm, string src, int srcLen, [Out] char[] dstBuffer, int dstBufferCapacity); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs deleted file mode 100644 index 4a9933f929..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -internal static partial class Interop -{ - internal static partial class Globalization - { - // needs to be kept in sync with ResultCode in System.Globalization.Native - internal enum ResultCode - { - Success = 0, - UnknownError = 1, - InsufficentBuffer = 2, - OutOfMemory = 3 - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs deleted file mode 100644 index 47cf26662b..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Globalization - { - // needs to be kept in sync with TimeZoneDisplayNameType in System.Globalization.Native - internal enum TimeZoneDisplayNameType - { - Generic = 0, - Standard = 1, - DaylightSavings = 2, - } - - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetTimeZoneDisplayName")] - internal static extern ResultCode GetTimeZoneDisplayName( - string localeName, - string timeZoneId, - TimeZoneDisplayNameType type, - [Out] StringBuilder result, - int resultLength); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Utils.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Utils.cs deleted file mode 100644 index 9887bd4f0b..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Globalization.Native/Interop.Utils.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Text; - -internal static partial class Interop -{ - /// - /// Helper for making interop calls that return a string, but we don't know - /// the correct size of buffer to make. So invoke the interop call with an - /// increasing buffer until the size is big enough. - /// - internal static bool CallStringMethod( - Func interopCall, - TArg1 arg1, - TArg2 arg2, - TArg3 arg3, - out string result) - { - const int initialStringSize = 80; - const int maxDoubleAttempts = 5; - - StringBuilder stringBuilder = StringBuilderCache.Acquire(initialStringSize); - - for (int i = 0; i < maxDoubleAttempts; i++) - { - Interop.Globalization.ResultCode resultCode = interopCall(arg1, arg2, arg3, stringBuilder); - - if (resultCode == Interop.Globalization.ResultCode.Success) - { - result = StringBuilderCache.GetStringAndRelease(stringBuilder); - return true; - } - else if (resultCode == Interop.Globalization.ResultCode.InsufficentBuffer) - { - // increase the string size and loop - stringBuilder.EnsureCapacity(stringBuilder.Capacity * 2); - } - else - { - // if there is an unknown error, don't proceed - break; - } - } - - StringBuilderCache.Release(stringBuilder); - result = null; - return false; - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Close.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Close.cs deleted file mode 100644 index 8d192398a0..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Close.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Close", SetLastError = true)] - internal static extern int Close(IntPtr fd); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FLock.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FLock.cs deleted file mode 100644 index 22934a3e77..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FLock.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal enum LockOperations : int - { - LOCK_SH = 1, /* shared lock */ - LOCK_EX = 2, /* exclusive lock */ - LOCK_NB = 4, /* don't block when locking*/ - LOCK_UN = 8, /* unlock */ - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FLock", SetLastError = true)] - internal static extern int FLock(SafeFileHandle fd, LockOperations operation); - - /// - /// Exposing this for SafeFileHandle.ReleaseHandle() to call. - /// Normal callers should use FLock(SafeFileHandle fd). - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FLock", SetLastError = true)] - internal static extern int FLock(IntPtr fd, LockOperations operation); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FSync.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FSync.cs deleted file mode 100644 index e3ab970931..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FSync.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FSync", SetLastError = true)] - internal static extern int FSync(SafeFileHandle fd); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FTruncate.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FTruncate.cs deleted file mode 100644 index 5dad650362..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.FTruncate.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FTruncate", SetLastError = true)] - internal static extern int FTruncate(SafeFileHandle fd, long length); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetCwd.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetCwd.cs deleted file mode 100644 index a8bef6bde8..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetCwd.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Buffers; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetCwd", SetLastError = true)] - private static extern unsafe byte* GetCwd(byte* buffer, int bufferLength); - - internal static unsafe string GetCwd() - { - const int StackLimit = 256; - - // First try to get the path into a buffer on the stack - byte* stackBuf = stackalloc byte[StackLimit]; - string result = GetCwdHelper(stackBuf, StackLimit); - if (result != null) - { - return result; - } - - // If that was too small, try increasing large buffer sizes - int bufferSize = StackLimit; - do - { - checked { bufferSize *= 2; } - byte[] buf = ArrayPool.Shared.Rent(bufferSize); - try - { - fixed (byte* ptr = &buf[0]) - { - result = GetCwdHelper(ptr, buf.Length); - if (result != null) - { - return result; - } - } - } - finally - { - ArrayPool.Shared.Return(buf); - } - } - while (true); - } - - private static unsafe string GetCwdHelper(byte* ptr, int bufferSize) - { - // Call the real getcwd - byte* result = GetCwd(ptr, bufferSize); - - // If it returned non-null, the null-terminated path is in the buffer - if (result != null) - { - return Marshal.PtrToStringAnsi((IntPtr)ptr); - } - - // Otherwise, if it failed due to the buffer being too small, return null; - // for anything else, throw. - ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); - if (errorInfo.Error == Interop.Error.ERANGE) - { - return null; - } - throw Interop.GetExceptionForIoErrno(errorInfo); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetRandomBytes.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetRandomBytes.cs deleted file mode 100644 index e911b13583..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.GetRandomBytes.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; - -internal partial class Interop -{ - internal unsafe partial class Sys - { - [DllImport(Interop.Libraries.SystemNative, EntryPoint = "SystemNative_GetNonCryptographicallySecureRandomBytes")] - internal static extern unsafe void GetNonCryptographicallySecureRandomBytes(byte* buffer, int length); - } - - internal static unsafe void GetRandomBytes(byte* buffer, int length) - { - Sys.GetNonCryptographicallySecureRandomBytes(buffer, length); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LSeek.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LSeek.cs deleted file mode 100644 index 7f8df7c6bf..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LSeek.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal enum SeekWhence - { - SEEK_SET = 0, - SEEK_CUR = 1, - SEEK_END = 2 - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LSeek", SetLastError = true)] - internal static extern long LSeek(SafeFileHandle fd, long offset, SeekWhence whence); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LockFileRegion.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LockFileRegion.cs deleted file mode 100644 index 23b48a4f5d..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.LockFileRegion.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal enum LockType : short - { - F_WRLCK = 1, // exclusive or write lock - F_UNLCK = 2 // unlock - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LockFileRegion", SetLastError=true)] - internal static extern int LockFileRegion(SafeHandle fd, long offset, long length, LockType lockType); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.MksTemps.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.MksTemps.cs deleted file mode 100644 index b8694d9007..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.MksTemps.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_MksTemps", SetLastError = true)] - internal static extern IntPtr MksTemps( - byte[] template, - int suffixlen); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Open.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Open.cs deleted file mode 100644 index a9a994c78c..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Open.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Open", SetLastError = true)] - internal static extern SafeFileHandle Open(string filename, OpenFlags flags, int mode); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.OpenFlags.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.OpenFlags.cs deleted file mode 100644 index f9e54c3cbc..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.OpenFlags.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; - -internal static partial class Interop -{ - internal static partial class Sys - { - [Flags] - internal enum OpenFlags - { - // Access modes (mutually exclusive) - O_RDONLY = 0x0000, - O_WRONLY = 0x0001, - O_RDWR = 0x0002, - - // Flags (combinable) - O_CLOEXEC = 0x0010, - O_CREAT = 0x0020, - O_EXCL = 0x0040, - O_TRUNC = 0x0080, - O_SYNC = 0x0100, - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PathConf.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PathConf.cs deleted file mode 100644 index 7213cb0264..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PathConf.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal enum PathConfName : int - { - PC_LINK_MAX = 1, - PC_MAX_CANON = 2, - PC_MAX_INPUT = 3, - PC_NAME_MAX = 4, - PC_PATH_MAX = 5, - PC_PIPE_BUF = 6, - PC_CHOWN_RESTRICTED = 7, - PC_NO_TRUNC = 8, - PC_VDISABLE = 9, - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_PathConf", SetLastError = true)] - private static extern int PathConf(string path, PathConfName name); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Permissions.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Permissions.cs deleted file mode 100644 index f1d13787d2..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Permissions.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; - -internal static partial class Interop -{ - internal static partial class Sys - { - [Flags] - internal enum Permissions - { - Mask = S_IRWXU | S_IRWXG | S_IRWXO, - - S_IRWXU = S_IRUSR | S_IWUSR | S_IXUSR, - S_IRUSR = 0x100, - S_IWUSR = 0x80, - S_IXUSR = 0x40, - - S_IRWXG = S_IRGRP | S_IWGRP | S_IXGRP, - S_IRGRP = 0x20, - S_IWGRP = 0x10, - S_IXGRP = 0x8, - - S_IRWXO = S_IROTH | S_IWOTH | S_IXOTH, - S_IROTH = 0x4, - S_IWOTH = 0x2, - S_IXOTH = 0x1, - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PosixFAdvise.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PosixFAdvise.cs deleted file mode 100644 index ad8b73aed2..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.PosixFAdvise.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal enum FileAdvice : int - { - POSIX_FADV_NORMAL = 0, /* no special advice, the default value */ - POSIX_FADV_RANDOM = 1, /* random I/O access */ - POSIX_FADV_SEQUENTIAL = 2, /* sequential I/O access */ - POSIX_FADV_WILLNEED = 3, /* will need specified pages */ - POSIX_FADV_DONTNEED = 4, /* don't need the specified pages */ - POSIX_FADV_NOREUSE = 5, /* data will only be accessed once */ - } - - /// - /// Notifies the OS kernel that the specified file will be accessed in a particular way soon; this allows the kernel to - /// potentially optimize the access pattern of the file. - /// - /// The file descriptor of the file - /// The start of the region to advise about - /// The number of bytes of the region (until the end of the file if 0) - /// The type of advice to give the kernel about the specified region - /// - /// Returns 0 on success; otherwise, the error code is returned - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_PosixFAdvise", SetLastError = false /* this is explicitly called out in the man page */)] - internal static extern int PosixFAdvise(SafeFileHandle fd, long offset, long length, FileAdvice advice); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Read.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Read.cs deleted file mode 100644 index 1be5e789c2..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Read.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - /// - /// Reads a number of bytes from an open file descriptor into a specified buffer. - /// - /// The open file descriptor to try to read from - /// The buffer to read info into - /// The size of the buffer - /// - /// Returns the number of bytes read on success; otherwise, -1 is returned - /// Note - on fail. the position of the stream may change depending on the platform; consult man 2 read for more info - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Read", SetLastError = true)] - internal static extern unsafe int Read(SafeFileHandle fd, byte* buffer, int count); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadDir.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadDir.cs deleted file mode 100644 index d98c4285c0..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadDir.cs +++ /dev/null @@ -1,102 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Threading; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - private static readonly int s_readBufferSize = GetReadDirRBufferSize(); - - internal enum NodeType : int - { - DT_UNKNOWN = 0, - DT_FIFO = 1, - DT_CHR = 2, - DT_DIR = 4, - DT_BLK = 6, - DT_REG = 8, - DT_LNK = 10, - DT_SOCK = 12, - DT_WHT = 14 - } - - [StructLayout(LayoutKind.Sequential)] - private unsafe struct InternalDirectoryEntry - { - internal IntPtr Name; - internal int NameLength; - internal NodeType InodeType; - } - - internal struct DirectoryEntry - { - internal NodeType InodeType; - internal string InodeName; - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_OpenDir", SetLastError = true)] - internal static extern Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDir(string path); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetReadDirRBufferSize", SetLastError = false)] - internal static extern int GetReadDirRBufferSize(); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ReadDirR", SetLastError = false)] - private static extern unsafe int ReadDirR(IntPtr dir, byte* buffer, int bufferSize, out InternalDirectoryEntry outputEntry); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_CloseDir", SetLastError = true)] - internal static extern int CloseDir(IntPtr dir); - - // The calling pattern for ReadDir is described in src/Native/System.Native/pal_readdir.cpp - internal static int ReadDir(SafeDirectoryHandle dir, out DirectoryEntry outputEntry) - { - bool addedRef = false; - try - { - // We avoid a native string copy into InternalDirectoryEntry. - // - If the platform suppors reading into a buffer, the data is read directly into the buffer. The - // data can be read as long as the buffer is valid. - // - If the platform does not support reading into a buffer, the information returned in - // InternalDirectoryEntry points to native memory owned by the SafeDirectoryHandle. The data is only - // valid until the next call to CloseDir/ReadDir. We extend the reference until we have copied all data - // to ensure it does not become invalid by a CloseDir; and we copy the data so our caller does not - // use the native memory held by the SafeDirectoryHandle. - dir.DangerousAddRef(ref addedRef); - - unsafe - { - // s_readBufferSize is zero when the native implementation does not support reading into a buffer. - byte* buffer = stackalloc byte[s_readBufferSize]; - InternalDirectoryEntry temp; - int ret = ReadDirR(dir.DangerousGetHandle(), buffer, s_readBufferSize, out temp); - // We copy data into DirectoryEntry to ensure there are no dangling references. - outputEntry = ret == 0 ? - new DirectoryEntry() { InodeName = GetDirectoryEntryName(temp), InodeType = temp.InodeType } : - default(DirectoryEntry); - - return ret; - } - } - finally - { - if (addedRef) - { - dir.DangerousRelease(); - } - } - } - - private static unsafe string GetDirectoryEntryName(InternalDirectoryEntry dirEnt) - { - if (dirEnt.NameLength == -1) - return Marshal.PtrToStringAnsi(dirEnt.Name); - else - return Marshal.PtrToStringAnsi(dirEnt.Name, dirEnt.NameLength); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadLink.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadLink.cs deleted file mode 100644 index 50f1ae545e..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.ReadLink.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using System.Buffers; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Sys - { - /// - /// Takes a path to a symbolic link and attempts to place the link target path into the buffer. If the buffer is too - /// small, the path will be truncated. No matter what, the buffer will not be null terminated. - /// - /// The path to the symlink - /// The buffer to hold the output path - /// The size of the buffer - /// - /// Returns the number of bytes placed into the buffer on success; bufferSize if the buffer is too small; and -1 on error. - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ReadLink", SetLastError = true)] - private static extern unsafe int ReadLink(string path, byte[] buffer, int bufferSize); - - /// - /// Takes a path to a symbolic link and returns the link target path. - /// - /// The path to the symlink - /// - /// Returns the link to the target path on success; and null otherwise. - /// - public static string ReadLink(string path) - { - int bufferSize = 256; - do - { - byte[] buffer = ArrayPool.Shared.Rent(bufferSize); - try - { - int resultLength = Interop.Sys.ReadLink(path, buffer, buffer.Length); - if (resultLength < 0) - { - // error - return null; - } - else if (resultLength < buffer.Length) - { - // success - return Encoding.UTF8.GetString(buffer, 0, resultLength); - } - } - finally - { - ArrayPool.Shared.Return(buffer); - } - - // buffer was too small, loop around again and try with a larger buffer. - bufferSize *= 2; - } while (true); - } - } -} \ No newline at end of file diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Stat.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Stat.cs deleted file mode 100644 index 0ca199b70d..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Stat.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - // Even though csc will by default use a sequential layout, a CS0649 warning as error - // is produced for un-assigned fields when no StructLayout is specified. - // - // Explicitly saying Sequential disables that warning/error for consumers which only - // use Stat in debug builds. - [StructLayout(LayoutKind.Sequential)] - internal struct FileStatus - { - internal FileStatusFlags Flags; - internal int Mode; - internal uint Uid; - internal uint Gid; - internal long Size; - internal long ATime; - internal long ATimeNsec; - internal long MTime; - internal long MTimeNsec; - internal long CTime; - internal long CTimeNsec; - internal long BirthTime; - internal long BirthTimeNsec; - internal long Dev; - internal long Ino; - } - - internal static class FileTypes - { - internal const int S_IFMT = 0xF000; - internal const int S_IFIFO = 0x1000; - internal const int S_IFCHR = 0x2000; - internal const int S_IFDIR = 0x4000; - internal const int S_IFREG = 0x8000; - internal const int S_IFLNK = 0xA000; - internal const int S_IFSOCK = 0xC000; - } - - [Flags] - internal enum FileStatusFlags - { - None = 0, - HasBirthTime = 1, - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FStat2", SetLastError = true)] - internal static extern int FStat(SafeFileHandle fd, out FileStatus output); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat2", SetLastError = true)] - internal static extern int Stat(string path, out FileStatus output); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LStat2", SetLastError = true)] - internal static extern int LStat(string path, out FileStatus output); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.SysLog.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.SysLog.cs deleted file mode 100644 index 6b6a74b743..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.SysLog.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal enum SysLogPriority : int - { - // Priorities - LOG_EMERG = 0, /* system is unusable */ - LOG_ALERT = 1, /* action must be taken immediately */ - LOG_CRIT = 2, /* critical conditions */ - LOG_ERR = 3, /* error conditions */ - LOG_WARNING = 4, /* warning conditions */ - LOG_NOTICE = 5, /* normal but significant condition */ - LOG_INFO = 6, /* informational */ - LOG_DEBUG = 7, /* debug-level messages */ - // Facilities - LOG_KERN = (0<<3), /* kernel messages */ - LOG_USER = (1<<3), /* random user-level messages */ - LOG_MAIL = (2<<3), /* mail system */ - LOG_DAEMON = (3<<3), /* system daemons */ - LOG_AUTH = (4<<3), /* authorization messages */ - LOG_SYSLOG = (5<<3), /* messages generated internally by syslogd */ - LOG_LPR = (6<<3), /* line printer subsystem */ - LOG_NEWS = (7<<3), /* network news subsystem */ - LOG_UUCP = (8<<3), /* UUCP subsystem */ - LOG_CRON = (9<<3), /* clock daemon */ - LOG_AUTHPRIV = (10<<3), /* authorization messages (private) */ - LOG_FTP = (11<<3), /* ftp daemon */ - // Between FTP and Local is reserved for system use - LOG_LOCAL0 = (16<<3), /* reserved for local use */ - LOG_LOCAL1 = (17<<3), /* reserved for local use */ - LOG_LOCAL2 = (18<<3), /* reserved for local use */ - LOG_LOCAL3 = (19<<3), /* reserved for local use */ - LOG_LOCAL4 = (20<<3), /* reserved for local use */ - LOG_LOCAL5 = (21<<3), /* reserved for local use */ - LOG_LOCAL6 = (22<<3), /* reserved for local use */ - LOG_LOCAL7 = (23<<3), /* reserved for local use */ - } - - /// - /// Write a message to the system logger, which in turn writes the message to the system console, log files, etc. - /// See man 3 syslog for more info - /// - /// - /// The OR of a priority and facility in the SysLogPriority enum to declare the priority and facility of the log entry - /// - /// The message to put in the log entry - /// Like printf, the argument is passed to the variadic part of the C++ function to wildcards in the message - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SysLog")] - internal static extern void SysLog(SysLogPriority priority, string message, string arg1); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Unlink.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Unlink.cs deleted file mode 100644 index 829210fa7e..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Unlink.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Unlink", SetLastError = true)] - internal static extern int Unlink(string pathname); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Write.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Write.cs deleted file mode 100644 index 0636615a8b..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/CoreLib/Interop/Unix/System.Native/Interop.Write.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - /// - /// Writes the specified buffer to the provided open file descriptor - /// - /// The file descriptor to try and write to - /// The data to attempt to write - /// The amount of data to write, in bytes - /// - /// Returns the number of bytes written on success; otherwise, returns -1 and sets errno - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Write", SetLastError = true)] - internal static extern unsafe int Write(SafeFileHandle fd, byte* buffer, int bufferSize); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Write", SetLastError = true)] - internal static extern unsafe int Write(int fd, byte* buffer, int bufferSize); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/Interop.Libraries.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/Interop.Libraries.cs index 7446e1bfba..c4f2f36493 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/Interop.Libraries.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/Interop.Libraries.cs @@ -7,12 +7,6 @@ internal static partial class Interop internal static partial class Libraries { // Shims - internal const string SystemNative = "System.Native"; - internal const string HttpNative = "System.Net.Http.Native"; internal const string NetSecurityNative = "System.Net.Security.Native"; - internal const string CryptoNative = "System.Security.Cryptography.Native.OpenSsl"; - internal const string CompressionNative = "System.IO.Compression.Native"; - internal const string IOPortsNative = "System.IO.Ports.Native"; - internal const string Libdl = "libdl"; } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Accept.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Accept.cs deleted file mode 100644 index b37883a358..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Accept.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Accept")] - internal static extern unsafe Error Accept(SafeHandle socket, byte* socketAddress, int* socketAddressLen, IntPtr* acceptedFd); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Access.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Access.cs deleted file mode 100644 index a723f572a5..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Access.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal enum AccessMode : int - { - F_OK = 0, /* Check for existence */ - X_OK = 1, /* Check for execute */ - W_OK = 2, /* Check for write */ - R_OK = 4, /* Check for read */ - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Access", SetLastError = true)] - internal static extern int Access(string path, AccessMode mode); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Bind.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Bind.cs deleted file mode 100644 index 03f68de856..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Bind.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net.Sockets; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Bind")] - internal static extern unsafe Error Bind(SafeHandle socket, ProtocolType socketProtocolType, byte* socketAddress, int socketAddressLen); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ChDir.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ChDir.cs deleted file mode 100644 index 3c66995182..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ChDir.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ChDir", SetLastError = true)] - internal static extern int ChDir(string path); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ChMod.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ChMod.cs deleted file mode 100644 index 51381e2c2d..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ChMod.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ChMod", SetLastError = true)] - internal static extern int ChMod(string path, int mode); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Connect.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Connect.cs deleted file mode 100644 index 151b51e2f6..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Connect.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Connect")] - internal static extern unsafe Error Connect(SafeHandle socket, byte* socketAddress, int socketAddressLen); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.CopyFile.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.CopyFile.cs deleted file mode 100644 index f7035fcead..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.CopyFile.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Win32.SafeHandles; -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_CopyFile", SetLastError = true)] - internal static extern int CopyFile(SafeFileHandle source, SafeFileHandle destination); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Dup.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Dup.cs deleted file mode 100644 index 8ca2ad760d..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Dup.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Dup", SetLastError = true)] - internal static extern SafeFileHandle Dup(SafeFileHandle oldfd); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.EnumerateInterfaceAddresses.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.EnumerateInterfaceAddresses.cs deleted file mode 100644 index 1efe322f6f..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.EnumerateInterfaceAddresses.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [StructLayout(LayoutKind.Sequential)] - public unsafe struct LinkLayerAddressInfo - { - public int InterfaceIndex; - public fixed byte AddressBytes[8]; - public byte NumAddressBytes; - private byte __padding; // For native struct-size padding. Does not contain useful data. - public ushort HardwareType; - } - - [StructLayout(LayoutKind.Sequential)] - public unsafe struct IpAddressInfo - { - public int InterfaceIndex; - public fixed byte AddressBytes[16]; - public byte NumAddressBytes; - private fixed byte __padding[3]; - } - - public unsafe delegate void IPv4AddressDiscoveredCallback(string ifaceName, IpAddressInfo* ipAddressInfo, IpAddressInfo* netMaskInfo); - public unsafe delegate void IPv6AddressDiscoveredCallback(string ifaceName, IpAddressInfo* ipAddressInfo, uint* scopeId); - public unsafe delegate void LinkLayerAddressDiscoveredCallback(string ifaceName, LinkLayerAddressInfo* llAddress); - public unsafe delegate void DnsAddessDiscoveredCallback(IpAddressInfo* gatewayAddress); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_EnumerateInterfaceAddresses")] - public static extern int EnumerateInterfaceAddresses( - IPv4AddressDiscoveredCallback ipv4Found, - IPv6AddressDiscoveredCallback ipv6Found, - LinkLayerAddressDiscoveredCallback linkLayerFound); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_EnumerateGatewayAddressesForInterface")] - public static extern int EnumerateGatewayAddressesForInterface(uint interfaceIndex, DnsAddessDiscoveredCallback onGatewayFound); - - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.FChMod.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.FChMod.cs deleted file mode 100644 index 161ac71d81..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.FChMod.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Win32.SafeHandles; -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FChMod", SetLastError = true)] - internal static extern int FChMod(SafeFileHandle fd, int mode); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Fcntl.Pipe.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Fcntl.Pipe.cs deleted file mode 100644 index 96c7caf165..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Fcntl.Pipe.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal static partial class Fcntl - { - internal static readonly bool CanGetSetPipeSz = (FcntlCanGetSetPipeSz() != 0); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FcntlGetPipeSz", SetLastError=true)] - internal static extern int GetPipeSz(SafePipeHandle fd); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FcntlSetPipeSz", SetLastError=true)] - internal static extern int SetPipeSz(SafePipeHandle fd, int size); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FcntlCanGetSetPipeSz")] - private static extern int FcntlCanGetSetPipeSz(); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Fcntl.SetCloseOnExec.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Fcntl.SetCloseOnExec.cs deleted file mode 100644 index ec0836bacb..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Fcntl.SetCloseOnExec.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal static partial class Fcntl - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FcntlSetCloseOnExec", SetLastError=true)] - internal static extern int SetCloseOnExec(SafeHandle fd); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Fcntl.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Fcntl.cs deleted file mode 100644 index 5b2fb45e3e..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Fcntl.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal static class Fcntl - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FcntlSetIsNonBlocking", SetLastError = true)] - internal static extern int DangerousSetIsNonBlocking(IntPtr fd, int isNonBlocking); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FcntlSetIsNonBlocking", SetLastError=true)] - internal static extern int SetIsNonBlocking(SafeHandle fd, int isNonBlocking); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.FileDescriptors.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.FileDescriptors.cs deleted file mode 100644 index 82abc8bffa..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.FileDescriptors.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal static class FileDescriptors - { - internal static readonly SafeFileHandle STDIN_FILENO = CreateFileHandle(0); - internal static readonly SafeFileHandle STDOUT_FILENO = CreateFileHandle(1); - internal static readonly SafeFileHandle STDERR_FILENO = CreateFileHandle(2); - - private static SafeFileHandle CreateFileHandle(int fileNumber) - { - return new SafeFileHandle((IntPtr)fileNumber, ownsHandle: false); - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ForkAndExecProcess.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ForkAndExecProcess.cs deleted file mode 100644 index 3aa37279bc..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ForkAndExecProcess.cs +++ /dev/null @@ -1,111 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.ComponentModel; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal static unsafe void ForkAndExecProcess( - string filename, string[] argv, string[] envp, string cwd, - bool redirectStdin, bool redirectStdout, bool redirectStderr, - bool setUser, uint userId, uint groupId, - out int lpChildPid, out int stdinFd, out int stdoutFd, out int stderrFd, bool shouldThrow = true) - { - byte** argvPtr = null, envpPtr = null; - int result = -1; - try - { - AllocNullTerminatedArray(argv, ref argvPtr); - AllocNullTerminatedArray(envp, ref envpPtr); - result = ForkAndExecProcess( - filename, argvPtr, envpPtr, cwd, - redirectStdin ? 1 : 0, redirectStdout ? 1 : 0, redirectStderr ? 1 :0, - setUser ? 1 : 0, userId, groupId, - out lpChildPid, out stdinFd, out stdoutFd, out stderrFd); - if (result != 0) - { - // Normally we'd simply make this method return the result of the native - // call and allow the caller to use GetLastWin32Error. However, we need - // to free the native arrays after calling the function, and doing so - // stomps on the runtime's captured last error. So we need to access the - // error here, and without SetLastWin32Error available, we can't propagate - // the error to the caller via the normal GetLastWin32Error mechanism. We could - // return 0 on success or the GetLastWin32Error value on failure, but that's - // technically ambiguous, in the case of a failure with a 0 errno. Simplest - // solution then is just to throw here the same exception the Process caller - // would have. This can be revisited if we ever have another call site. - throw new Win32Exception(); - } - } - finally - { - FreeArray(envpPtr, envp.Length); - FreeArray(argvPtr, argv.Length); - } - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ForkAndExecProcess", SetLastError = true)] - private static extern unsafe int ForkAndExecProcess( - string filename, byte** argv, byte** envp, string cwd, - int redirectStdin, int redirectStdout, int redirectStderr, - int setUser, uint userId, uint groupId, - out int lpChildPid, out int stdinFd, out int stdoutFd, out int stderrFd); - - private static unsafe void AllocNullTerminatedArray(string[] arr, ref byte** arrPtr) - { - int arrLength = arr.Length + 1; // +1 is for null termination - - // Allocate the unmanaged array to hold each string pointer. - // It needs to have an extra element to null terminate the array. - arrPtr = (byte**)Marshal.AllocHGlobal(sizeof(IntPtr) * arrLength); - Debug.Assert(arrPtr != null); - - // Zero the memory so that if any of the individual string allocations fails, - // we can loop through the array to free any that succeeded. - // The last element will remain null. - for (int i = 0; i < arrLength; i++) - { - arrPtr[i] = null; - } - - // Now copy each string to unmanaged memory referenced from the array. - // We need the data to be an unmanaged, null-terminated array of UTF8-encoded bytes. - for (int i = 0; i < arr.Length; i++) - { - byte[] byteArr = Encoding.UTF8.GetBytes(arr[i]); - - arrPtr[i] = (byte*)Marshal.AllocHGlobal(byteArr.Length + 1); //+1 for null termination - Debug.Assert(arrPtr[i] != null); - - Marshal.Copy(byteArr, 0, (IntPtr)arrPtr[i], byteArr.Length); // copy over the data from the managed byte array - arrPtr[i][byteArr.Length] = (byte)'\0'; // null terminate - } - } - - private static unsafe void FreeArray(byte** arr, int length) - { - if (arr != null) - { - // Free each element of the array - for (int i = 0; i < length; i++) - { - if (arr[i] != null) - { - Marshal.FreeHGlobal((IntPtr)arr[i]); - arr[i] = null; - } - } - - // And then the array itself - Marshal.FreeHGlobal((IntPtr)arr); - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetBytesAvailable.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetBytesAvailable.cs deleted file mode 100644 index ee42a483d3..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetBytesAvailable.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetBytesAvailable")] - internal static extern unsafe Error GetBytesAvailable(SafeHandle socket, int* available); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetAtOutOfBandMark")] - internal static extern unsafe Error GetAtOutOfBandMark(SafeHandle socket, int* atMark); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetControlCharacters.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetControlCharacters.cs deleted file mode 100644 index f33a5544b9..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetControlCharacters.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetControlCharacters")] - internal static extern void GetControlCharacters( - ControlCharacterNames[] controlCharacterNames, byte[] controlCharacterValues, int controlCharacterLength, - out byte posixDisableValue); - - internal enum ControlCharacterNames : int - { - VINTR = 0, - VQUIT = 1, - VERASE = 2, - VKILL = 3, - VEOF = 4, - VTIME = 5, - VMIN = 6, - VSWTC = 7, - VSTART = 8, - VSTOP = 9, - VSUSP = 10, - VEOL = 11, - VREPRINT = 12, - VDISCARD = 13, - VWERASE = 14, - VLNEXT = 15, - VEOL2 = 16 - }; - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetDomainName.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetDomainName.cs deleted file mode 100644 index 4466d63413..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetDomainName.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetDomainName", SetLastError = true)] - private static extern unsafe int GetDomainName(byte* name, int len); - - internal static unsafe string GetDomainName() - { - const int HOST_NAME_MAX = 255; // man getdomainname - const int ArrLength = HOST_NAME_MAX + 1; - - byte* name = stackalloc byte[ArrLength]; - int err = GetDomainName(name, ArrLength); - if (err != 0) - { - // This should never happen. According to the man page, - // the only possible errno for getdomainname is ENAMETOOLONG, - // which should only happen if the buffer we supply isn't big - // enough, and we're using a buffer size that the man page - // says is the max for POSIX (and larger than the max for Linux). - Debug.Fail($"{nameof(GetDomainName)} failed with error {err}"); - throw new InvalidOperationException($"{nameof(GetDomainName)}: {err}"); - } - - // Marshal.PtrToStringAnsi uses UTF8 on Unix. - return Marshal.PtrToStringAnsi((IntPtr)name); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetDomainSocketSizes.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetDomainSocketSizes.cs deleted file mode 100644 index bb0f48c721..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetDomainSocketSizes.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetDomainSocketSizes")] - internal static extern void GetDomainSocketSizes(out int pathOffset, out int pathSize, out int addressSize); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetEGid.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetEGid.cs deleted file mode 100644 index 6530b2303a..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetEGid.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetEGid")] - internal static extern uint GetEGid(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetEUid.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetEUid.cs deleted file mode 100644 index 8b525fa327..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetEUid.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetEUid")] - internal static extern uint GetEUid(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetHostName.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetHostName.cs deleted file mode 100644 index 3858b495a1..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetHostName.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetHostName", SetLastError = true)] - private static extern unsafe int GetHostName(byte* name, int nameLength); - - internal static unsafe string GetHostName() - { - const int HOST_NAME_MAX = 255; - const int ArrLength = HOST_NAME_MAX + 1; - - byte* name = stackalloc byte[ArrLength]; - int err = GetHostName(name, ArrLength); - if (err != 0) - { - // This should never happen. According to the man page, - // the only possible errno for gethostname is ENAMETOOLONG, - // which should only happen if the buffer we supply isn't big - // enough, and we're using a buffer size that the man page - // says is the max for POSIX (and larger than the max for Linux). - Debug.Fail("gethostname failed"); - throw new InvalidOperationException(string.Format("gethostname returned {0}", err)); - } - - // If the hostname is truncated, it is unspecified whether the returned buffer includes a terminating null byte. - name[ArrLength - 1] = 0; - - return Marshal.PtrToStringAnsi((IntPtr)name); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetLine.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetLine.cs deleted file mode 100644 index f6a6c7e3ae..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetLine.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetLine", SetLastError = true)] - internal static extern string GetLine(IntPtr stream); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetNameInfo.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetNameInfo.cs deleted file mode 100644 index bd22e8c912..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetNameInfo.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [Flags] - internal enum GetNameInfoFlags : int - { - NI_NAMEREQD = 0x1, - NI_NUMERICHOST = 0x2, - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetNameInfo")] - internal static extern unsafe int GetNameInfo( - byte* address, - uint addressLength, - byte isIpv6, - byte* host, - uint hostLength, - byte* service, - uint serviceLength, - GetNameInfoFlags flags); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetNodeName.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetNodeName.cs deleted file mode 100644 index a303544e4e..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetNodeName.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetNodeName", SetLastError = true)] - private static extern unsafe int GetNodeName(char* name, out int len); - - internal static unsafe string GetNodeName() - { - // max value of _UTSNAME_LENGTH on known Unix platforms is 1024. - const int _UTSNAME_LENGTH = 1024; - int len = _UTSNAME_LENGTH; - char* name = stackalloc char[_UTSNAME_LENGTH]; - int err = GetNodeName(name, out len); - if (err != 0) - { - // max domain name can be 255 chars. - Debug.Fail($"{nameof(GetNodeName)} failed with error {err}"); - throw new InvalidOperationException(string.Format($"{nameof(GetNodeName)}: {err}"); - } - - // Marshal.PtrToStringAnsi uses UTF8 on Unix. - return Marshal.PtrToStringAnsi((IntPtr)name); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetOSArchitecture.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetOSArchitecture.cs deleted file mode 100644 index 70f614ebcf..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetOSArchitecture.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetOSArchitecture")] - internal static extern int GetOSArchitecture(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerID.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerID.cs deleted file mode 100644 index 9ebb48ec39..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerID.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPeerID", SetLastError = true)] - internal static extern unsafe int GetPeerID(SafeHandle socket, out uint euid); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerName.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerName.cs deleted file mode 100644 index 3635b92d29..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerName.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPeerName")] - internal static extern unsafe Error GetPeerName(SafeHandle socket, byte* socketAddress, int* socketAddressLen); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerUserName.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerUserName.cs deleted file mode 100644 index 8effc8883e..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPeerUserName.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPeerUserName", SetLastError = true)] - internal static extern unsafe string GetPeerUserName(SafeHandle socket); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPid.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPid.cs deleted file mode 100644 index f25005d798..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPid.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPid")] - internal static extern int GetPid(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetProcessArchitecture.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetProcessArchitecture.cs deleted file mode 100644 index be23a335b7..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetProcessArchitecture.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetProcessArchitecture")] - internal static extern int GetProcessArchitecture(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPwUid.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPwUid.cs deleted file mode 100644 index 56d55c948f..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetPwUid.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal unsafe struct Passwd - { - internal const int InitialBufferSize = 256; - - internal byte* Name; - internal byte* Password; - internal uint UserId; - internal uint GroupId; - internal byte* UserInfo; - internal byte* HomeDirectory; - internal byte* Shell; - }; - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPwUidR", SetLastError = false)] - internal static extern unsafe int GetPwUidR(uint uid, out Passwd pwd, byte* buf, int bufLen); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPwNamR", SetLastError = false)] - internal static extern unsafe int GetPwNamR(string name, out Passwd pwd, byte* buf, int bufLen); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSetPriority.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSetPriority.cs deleted file mode 100644 index fc1002be97..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSetPriority.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Reflection; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal enum PriorityWhich : int - { - PRIO_PROCESS = 0, - PRIO_PGRP = 1, - PRIO_USER = 2, - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPriority", SetLastError = true)] - private static extern int GetPriority(PriorityWhich which, int who); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetPriority", SetLastError = true)] - internal static extern int SetPriority(PriorityWhich which, int who, int nice); - - /// - /// Wrapper around getpriority since getpriority can return from -20 to 20; therefore, - /// we cannot rely on the return value for success and failure. This wrapper makes the - /// getpriority call to act more naturally where the return value is the actual error - /// value (or 0 if success) instead of forcing the caller to retrieve the last error. - /// - /// Returns 0 on success; otherwise, returns the errno value - internal static int GetPriority(PriorityWhich which, int who, out int priority) - { - priority = GetPriority(which, who); - return Marshal.GetLastWin32Error(); - } - - internal static System.Diagnostics.ThreadPriorityLevel GetThreadPriorityFromNiceValue(int nice) - { - Debug.Assert((nice >= -20) && (nice <= 20)); - return - (nice < -15) ? ThreadPriorityLevel.TimeCritical : - (nice < -10) ? ThreadPriorityLevel.Highest : - (nice < -5) ? ThreadPriorityLevel.AboveNormal : - (nice == 0) ? ThreadPriorityLevel.Normal : - (nice <= 5) ? ThreadPriorityLevel.BelowNormal : - (nice <= 10) ? ThreadPriorityLevel.Lowest : - ThreadPriorityLevel.Idle; - } - - internal static int GetNiceValueFromThreadPriority(System.Diagnostics.ThreadPriorityLevel priority) - { - return (priority == ThreadPriorityLevel.TimeCritical ? -20 : - priority == ThreadPriorityLevel.Highest ? -15 : - priority == ThreadPriorityLevel.AboveNormal ? -10 : - priority == ThreadPriorityLevel.Normal ? 0 : - priority == ThreadPriorityLevel.BelowNormal ? 5 : - priority == ThreadPriorityLevel.Lowest ? 10 : - 20); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSockName.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSockName.cs deleted file mode 100644 index f46297943e..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSockName.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetSockName")] - internal static extern unsafe Error GetSockName(SafeHandle socket, byte* socketAddress, int* socketAddressLen); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSockOpt.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSockOpt.cs deleted file mode 100644 index 3e48b84536..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSockOpt.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net.Sockets; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetSockOpt")] - internal static extern unsafe Error GetSockOpt(SafeHandle socket, SocketOptionLevel optionLevel, SocketOptionName optionName, byte* optionValue, int* optionLen); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSocketErrorOption.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSocketErrorOption.cs deleted file mode 100644 index 070171d63d..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSocketErrorOption.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net.Sockets; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetSocketErrorOption")] - internal static extern unsafe Error GetSocketErrorOption(SafeHandle socket, Error* socketError); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetTimestamp.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetTimestamp.cs deleted file mode 100644 index a6c9d28054..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetTimestamp.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetTimestampResolution")] - internal static extern bool GetTimestampResolution(out long resolution); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetTimestamp")] - internal static extern bool GetTimestamp(out long timestamp); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetAbsoluteTime")] - internal static extern bool GetAbsoluteTime(out ulong timestamp); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetTimebaseInfo")] - internal static extern bool GetTimebaseInfo(out uint numer, out uint denom); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetUnixName.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetUnixName.cs deleted file mode 100644 index 33664c4d39..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetUnixName.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetUnixName")] - private static extern IntPtr GetUnixNamePrivate(); - - internal static string GetUnixName() - { - IntPtr ptr = GetUnixNamePrivate(); - return Marshal.PtrToStringAnsi(ptr); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetUnixRelease.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetUnixRelease.cs deleted file mode 100644 index 5e41ae9804..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetUnixRelease.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetUnixRelease", CharSet = CharSet.Ansi, SetLastError = true)] - public static extern string GetUnixRelease(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetUnixVersion.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetUnixVersion.cs deleted file mode 100644 index 9124607552..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetUnixVersion.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetUnixVersion", CharSet = CharSet.Ansi, SetLastError = true)] - private static extern int GetUnixVersion(StringBuilder version, out int capacity); - - internal static string GetUnixVersion() - { - // max value of _UTSNAME_LENGTH on known Unix platforms is 1024. - const int _UTSNAME_LENGTH = 1024; - int capacity = _UTSNAME_LENGTH * 3 + 2; - StringBuilder version = new StringBuilder(capacity); - - if (GetUnixVersion(version, out capacity) != 0) - { - // Check if the function failed due to insufficient buffer. - if (capacity > version.Capacity) - { - version.Capacity = capacity; - GetUnixVersion(version, out capacity); - } - } - - return version.ToString(); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetWindowWidth.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetWindowWidth.cs deleted file mode 100644 index 290857d742..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetWindowWidth.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [StructLayout(LayoutKind.Sequential)] - internal struct WinSize - { - internal ushort Row; - internal ushort Col; - internal ushort XPixel; - internal ushort YPixel; - }; - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetWindowSize", SetLastError = true)] - internal static extern int GetWindowSize(out WinSize winSize); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.HostEntry.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.HostEntry.cs deleted file mode 100644 index 944a235821..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.HostEntry.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal const int NI_MAXHOST = 1025; - internal const int NI_MAXSERV = 32; - - internal enum GetAddrInfoErrorFlags : int - { - EAI_AGAIN = 1, // Temporary failure in name resolution. - EAI_BADFLAGS = 2, // Invalid value for `ai_flags' field. - EAI_FAIL = 3, // Non-recoverable failure in name resolution. - EAI_FAMILY = 4, // 'ai_family' not supported. - EAI_NONAME = 5, // NAME or SERVICE is unknown. - EAI_BADARG = 6, // One or more input arguments were invalid. - EAI_NOMORE = 7, // No more entries are present in the list. - } - - internal enum GetHostErrorCodes : int - { - HOST_NOT_FOUND = 1, - TRY_AGAIN = 2, - NO_RECOVERY = 3, - NO_DATA = 4, - NO_ADDRESS = NO_DATA, - } - - //opaque structure to maintain consistency with native function signature - internal unsafe struct addrinfo - { - - } - - [StructLayout(LayoutKind.Sequential)] - internal unsafe struct HostEntry - { - internal byte* CanonicalName; // Canonical Name of the Host - internal byte** Aliases; // List of aliases for the host - internal addrinfo* AddressListHandle; // Handle for socket address list - internal int IPAddressCount; // Number of IP addresses in the list - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetHostEntryForName")] - internal static extern unsafe int GetHostEntryForName(string address, HostEntry* entry); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetNextIPAddress")] - internal static extern unsafe int GetNextIPAddress(HostEntry* entry, addrinfo** addressListHandle, IPAddress* endPoint); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FreeHostEntry")] - internal static extern unsafe void FreeHostEntry(HostEntry* entry); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.IPAddress.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.IPAddress.cs deleted file mode 100644 index dc9b25f758..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.IPAddress.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal const int IPv4AddressBytes = 4; - internal const int IPv6AddressBytes = 16; - - internal const int MAX_IP_ADDRESS_BYTES = 16; - - internal const int INET_ADDRSTRLEN = 22; - internal const int INET6_ADDRSTRLEN = 65; - - // NOTE: `_isIPv6` cannot be of type `bool` because `bool` is not a blittable type and this struct is - // embedded in other structs for interop purposes. - [StructLayout(LayoutKind.Sequential)] - internal unsafe struct IPAddress : IEquatable - { - public bool IsIPv6 - { - get { return _isIPv6 != 0; } - set { _isIPv6 = value ? 1u : 0u; } - } - - internal fixed byte Address[MAX_IP_ADDRESS_BYTES]; // Buffer to fit an IPv4 or IPv6 address - private uint _isIPv6; // Non-zero if this is an IPv6 address; zero for IPv4. - internal uint ScopeId; // Scope ID (IPv6 only) - - public bool Equals(IPAddress other) - { - int addressByteCount; - if (IsIPv6) - { - if (!other.IsIPv6) - { - return false; - } - if (ScopeId != other.ScopeId) - { - return false; - } - - addressByteCount = IPv6AddressBytes; - } - else - { - if (other.IsIPv6) - { - return false; - } - - addressByteCount = IPv4AddressBytes; - } - - fixed (byte* thisAddress = Address) - { - for (int i = 0; i < addressByteCount; i++) - { - if (thisAddress[i] != other.Address[i]) - { - return false; - } - } - } - - return true; - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.IPPacketInformation.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.IPPacketInformation.cs deleted file mode 100644 index b676eaaad8..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.IPPacketInformation.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal struct IPPacketInformation - { - public IPAddress Address; // Destination IP Address - public int InterfaceIndex; // Interface index - private int Padding; // Pad out to 8-byte alignment - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetControlMessageBufferSize")] - internal static extern int GetControlMessageBufferSize(bool isIPv4, bool isIPv6); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_TryGetIPPacketInformation")] - internal static extern unsafe bool TryGetIPPacketInformation(MessageHeader* messageHeader, bool isIPv4, IPPacketInformation* packetInfo); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.InitializeConsole.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.InitializeConsole.cs deleted file mode 100644 index aeb1b69bfb..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.InitializeConsole.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_InitializeConsole", SetLastError = true)] - internal static extern bool InitializeConsole(); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetKeypadXmit")] - internal static extern void SetKeypadXmit(string terminfoString); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.IsATty.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.IsATty.cs deleted file mode 100644 index c68e8c7cdb..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.IsATty.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_IsATty", SetLastError = true)] - internal static extern bool IsATty(SafeFileHandle fd); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Kill.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Kill.cs deleted file mode 100644 index 47b22366ab..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Kill.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal enum Signals : int - { - None = 0, - SIGKILL = 9, - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Kill", SetLastError = true)] - internal static extern int Kill(int pid, Signals signal); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.LingerOption.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.LingerOption.cs deleted file mode 100644 index e1d659f350..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.LingerOption.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal struct LingerOption - { - public int OnOff; // Non-zero to enable linger - public int Seconds; // Number of seconds to linger for - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetLingerOption")] - internal static extern unsafe Error GetLingerOption(SafeHandle socket, LingerOption* option); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetLingerOption")] - internal static extern unsafe Error SetLingerOption(SafeHandle socket, LingerOption* option); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetLingerOption")] - internal static extern unsafe Error SetLingerOption(IntPtr socket, LingerOption* option); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Link.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Link.cs deleted file mode 100644 index 714649f5b2..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Link.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Link", SetLastError = true)] - internal static extern int Link(string source, string link); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Listen.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Listen.cs deleted file mode 100644 index 03b95ed00f..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Listen.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Listen")] - internal static extern Error Listen(SafeHandle socket, int backlog); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MAdvise.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MAdvise.cs deleted file mode 100644 index b46a506986..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MAdvise.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_MAdvise", SetLastError = true)] - internal static extern int MAdvise(IntPtr addr, ulong length, MemoryAdvice advice); - - internal enum MemoryAdvice - { - MADV_DONTFORK = 1, - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MMap.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MMap.cs deleted file mode 100644 index d7d1957af1..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MMap.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - - internal static partial class Sys - { - [Flags] - internal enum MemoryMappedProtections - { - PROT_NONE = 0x0, - PROT_READ = 0x1, - PROT_WRITE = 0x2, - PROT_EXEC = 0x4 - } - - [Flags] - internal enum MemoryMappedFlags - { - MAP_SHARED = 0x01, - MAP_PRIVATE = 0x02, - MAP_ANONYMOUS = 0x10, - } - - // NOTE: Shim returns null pointer on failure, not non-null MAP_FAILED sentinel. - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_MMap", SetLastError = true)] - internal static extern IntPtr MMap( - IntPtr addr, ulong len, - MemoryMappedProtections prot, MemoryMappedFlags flags, - SafeFileHandle fd, long offset); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MSync.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MSync.cs deleted file mode 100644 index 9326c64004..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MSync.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [Flags] - internal enum MemoryMappedSyncFlags - { - MS_ASYNC = 0x1, - MS_SYNC = 0x2, - MS_INVALIDATE = 0x10, - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_MSync", SetLastError = true)] - internal static extern int MSync(IntPtr addr, ulong len, MemoryMappedSyncFlags flags); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MUnmap.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MUnmap.cs deleted file mode 100644 index 1bfc1bae65..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MUnmap.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_MUnmap", SetLastError = true)] - internal static extern int MUnmap(IntPtr addr, ulong len); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MapTcpState.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MapTcpState.cs deleted file mode 100644 index f0ac9d98a9..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MapTcpState.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Net.NetworkInformation; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_MapTcpState")] - internal static extern TcpState MapTcpState(int nativeState); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MemSet.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MemSet.cs deleted file mode 100644 index 431d17029b..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MemSet.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_MemSet")] - internal static extern unsafe void* MemSet(void *s, int c, UIntPtr n); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MessageHeader.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MessageHeader.cs deleted file mode 100644 index 0748eb9213..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MessageHeader.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net.Sockets; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal unsafe struct IOVector - { - public byte* Base; - public UIntPtr Count; - } - - internal unsafe struct MessageHeader - { - public byte* SocketAddress; - public IOVector* IOVectors; - public byte* ControlBuffer; - public int SocketAddressLen; - public int IOVectorCount; - public int ControlBufferLen; - public SocketFlags Flags; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MkDir.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MkDir.cs deleted file mode 100644 index 3e4105cf43..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MkDir.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_MkDir", SetLastError = true)] - internal static extern int MkDir(string path, int mode); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs deleted file mode 100644 index 217790122e..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs +++ /dev/null @@ -1,440 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.IO; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { -#if DEBUG - static Sys() - { - foreach (string name in Enum.GetNames(typeof(UnixFileSystemTypes))) - { - System.Diagnostics.Debug.Assert(GetDriveType(name) != DriveType.Unknown, - $"Expected {nameof(UnixFileSystemTypes)}.{name} to have an entry in {nameof(GetDriveType)}."); - } - } -#endif - - private const int MountPointFormatBufferSizeInBytes = 32; - - /// - /// Internal FileSystem names and magic numbers taken from man(2) statfs - /// - /// - /// These value names MUST be kept in sync with those in GetDriveType below, - /// where this enum must be a subset of the GetDriveType list, with the enum - /// values here exactly matching a string there. - /// - internal enum UnixFileSystemTypes : long - { - adfs = 0xADF5, - affs = 0xADFF, - afs = 0x5346414F, - anoninode = 0x09041934, - aufs = 0x61756673, - autofs = 0x0187, - autofs4 = 0x6D4A556D, - befs = 0x42465331, - bdevfs = 0x62646576, - bfs = 0x1BADFACE, - binfmt_misc = 0x42494E4D, - btrfs = 0x9123683E, - ceph = 0x00C36400, - cgroupfs = 0x0027E0EB, - cifs = 0xFF534D42, - coda = 0x73757245, - coherent = 0x012FF7B7, - configfs = 0x62656570, - cramfs = 0x28CD3D45, - debugfs = 0x64626720, - devfs = 0x1373, - devpts = 0x1CD1, - ecryptfs = 0xF15F, - efs = 0x00414A53, - exofs = 0x5DF5, - ext = 0x137D, - ext2_old = 0xEF51, - ext2 = 0xEF53, - ext3 = 0xEF53, - ext4 = 0xEF53, - fat = 0x4006, - fhgfs = 0x19830326, - fuse = 0x65735546, - fuseblk = 0x65735546, - fusectl = 0x65735543, - futexfs = 0x0BAD1DEA, - gfsgfs2 = 0x1161970, - gfs2 = 0x01161970, - gpfs = 0x47504653, - hfs = 0x4244, - hfsplus = 0x482B, - hpfs = 0xF995E849, - hugetlbfs = 0x958458F6, - inodefs = 0x11307854, - inotifyfs = 0x2BAD1DEA, - isofs = 0x9660, - // isofs = 0x4004, // R_WIN - // isofs = 0x4000, // WIN - jffs = 0x07C0, - jffs2 = 0x72B6, - jfs = 0x3153464A, - kafs = 0x6B414653, - logfs = 0xC97E8168, - lustre = 0x0BD00BD0, - minix_old = 0x137F, /* orig. minix */ - minix = 0x138F, /* 30 char minix */ - minix2 = 0x2468, /* minix V2 */ - minix2v2 = 0x2478, /* MINIX V2, 30 char names */ - minix3 = 0x4D5A, - mqueue = 0x19800202, - msdos = 0x4D44, - nfs = 0x6969, - nfsd = 0x6E667364, - nilfs = 0x3434, - novell = 0x564C, - ntfs = 0x5346544E, - openprom = 0x9FA1, - ocfs2 = 0x7461636F, - omfs = 0xC2993D87, - overlay = 0x794C7630, - overlayfs = 0x794C764F, - panfs = 0xAAD7AAEA, - pipefs = 0x50495045, - proc = 0x9FA0, - pstorefs = 0x6165676C, - qnx4 = 0x002F, - qnx6 = 0x68191122, - ramfs = 0x858458F6, - reiserfs = 0x52654973, - romfs = 0x7275, - rpc_pipefs = 0x67596969, - samba = 0x517B, - securityfs = 0x73636673, - selinux = 0xF97CFF8C, - smb = 0x517B, - sockfs = 0x534F434B, - squashfs = 0x73717368, - sysfs = 0x62656572, - sysv2 = 0x012FF7B6, - sysv4 = 0x012FF7B5, - tmpfs = 0x01021994, - ubifs = 0x24051905, - udf = 0x15013346, - ufs = 0x00011954, - ufscigam = 0x54190100, // ufs byteswapped - ufs2 = 0x19540119, - usbdevice = 0x9FA2, - v9fs = 0x01021997, - vmhgfs = 0xBACBACBC, - vxfs = 0xA501FCF5, - vzfs = 0x565A4653, - xenfs = 0xABBA1974, - xenix = 0x012FF7B4, - xfs = 0x58465342, - xia = 0x012FD16D, - zfs = 0x2FC12FC1, - } - - [StructLayout(LayoutKind.Sequential)] - internal struct MountPointInformation - { - internal ulong AvailableFreeSpace; - internal ulong TotalFreeSpace; - internal ulong TotalSize; - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetSpaceInfoForMountPoint", SetLastError = true)] - internal static extern int GetSpaceInfoForMountPoint([MarshalAs(UnmanagedType.LPStr)]string name, out MountPointInformation mpi); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetFormatInfoForMountPoint", SetLastError = true)] - private static extern unsafe int GetFormatInfoForMountPoint( - [MarshalAs(UnmanagedType.LPStr)]string name, - byte* formatNameBuffer, - int bufferLength, - long* formatType); - - internal static int GetFormatInfoForMountPoint(string name, out string format) - { - DriveType temp; - return GetFormatInfoForMountPoint(name, out format, out temp); - } - - internal static int GetFormatInfoForMountPoint(string name, out DriveType type) - { - string temp; - return GetFormatInfoForMountPoint(name, out temp, out type); - } - - private static int GetFormatInfoForMountPoint(string name, out string format, out DriveType type) - { - unsafe - { - byte* formatBuffer = stackalloc byte[MountPointFormatBufferSizeInBytes]; // format names should be small - long numericFormat; - int result = GetFormatInfoForMountPoint(name, formatBuffer, MountPointFormatBufferSizeInBytes, &numericFormat); - if (result == 0) - { - // Check if we have a numeric answer or string - format = numericFormat != -1 ? - Enum.GetName(typeof(UnixFileSystemTypes), numericFormat) : - Marshal.PtrToStringAnsi((IntPtr)formatBuffer); - type = GetDriveType(format); - } - else - { - format = string.Empty; - type = DriveType.Unknown; - } - - return result; - } - } - - /// Categorizes a file system name into a drive type. - /// The name to categorize. - /// The recognized drive type. - private static DriveType GetDriveType(string fileSystemName) - { - // This list is based primarily on "man fs", "man mount", "mntent.h", "/proc/filesystems", coreutils "stat.c", - // and "wiki.debian.org/FileSystem". It can be extended over time as we find additional file systems that should - // be recognized as a particular drive type. - switch (fileSystemName) - { - case "cddafs": - case "cd9660": - case "iso": - case "isofs": - case "iso9660": - case "fuseiso": - case "fuseiso9660": - case "udf": - case "umview-mod-umfuseiso9660": - return DriveType.CDRom; - - case "aafs": - case "adfs": - case "affs": - case "anoninode": - case "anon-inode FS": - case "apfs": - case "balloon-kvm-fs": - case "bdevfs": - case "befs": - case "bfs": - case "bpf_fs": - case "btrfs": - case "btrfs_test": - case "cgroup2fs": - case "coh": - case "daxfs": - case "drvfs": - case "efivarfs": - case "efs": - case "exfat": - case "exofs": - case "ext": - case "ext2": - case "ext2_old": - case "ext3": - case "ext2/ext3": - case "ext4": - case "ext4dev": - case "f2fs": - case "fat": - case "fuseext2": - case "fusefat": - case "hfs": - case "hfs+": - case "hfsplus": - case "hfsx": - case "hostfs": - case "hpfs": - case "inodefs": - case "inotifyfs": - case "jbd": - case "jbd2": - case "jffs": - case "jffs2": - case "jfs": - case "logfs": - case "lxfs": - case "minix (30 char.)": - case "minix v2 (30 char.)": - case "minix v2": - case "minix": - case "minix_old": - case "minix2": - case "minix2v2": - case "minix2 v2": - case "minix3": - case "mlfs": - case "msdos": - case "nilfs": - case "nsfs": - case "ntfs": - case "ntfs-3g": - case "ocfs2": - case "omfs": - case "overlay": - case "overlayfs": - case "pstorefs": - case "qnx4": - case "qnx6": - case "reiserfs": - case "rpc_pipefs": - case "smackfs": - case "squashfs": - case "swap": - case "sysv": - case "sysv2": - case "sysv4": - case "tracefs": - case "ubifs": - case "ufs": - case "ufscigam": - case "ufs2": - case "umsdos": - case "umview-mod-umfuseext2": - case "v9fs": - case "vxfs": - case "vxfs_olt": - case "vzfs": - case "wslfs": - case "xenix": - case "xfs": - case "xia": - case "xiafs": - case "xmount": - case "zfs": - case "zfs-fuse": - case "zsmallocfs": - return DriveType.Fixed; - - case "9p": - case "acfs": - case "afp": - case "afpfs": - case "afs": - case "aufs": - case "autofs": - case "autofs4": - case "beaglefs": - case "ceph": - case "cifs": - case "coda": - case "coherent": - case "curlftpfs": - case "davfs2": - case "dlm": - case "ecryptfs": - case "eCryptfs": - case "fhgfs": - case "flickrfs": - case "ftp": - case "fuse": - case "fuseblk": - case "fusedav": - case "fusesmb": - case "gfsgfs2": - case "gfs/gfs2": - case "gfs2": - case "glusterfs-client": - case "gmailfs": - case "gpfs": - case "ibrix": - case "k-afs": - case "kafs": - case "kbfuse": - case "ltspfs": - case "lustre": - case "ncp": - case "ncpfs": - case "nfs": - case "nfs4": - case "nfsd": - case "novell": - case "obexfs": - case "panfs": - case "prl_fs": - case "s3ql": - case "samba": - case "smb": - case "smb2": - case "smbfs": - case "snfs": - case "sshfs": - case "vmhgfs": - case "webdav": - case "wikipediafs": - case "xenfs": - return DriveType.Network; - - case "anon_inode": - case "anon_inodefs": - case "aptfs": - case "avfs": - case "bdev": - case "binfmt_misc": - case "cgroup": - case "cgroupfs": - case "configfs": - case "cramfs": - case "cramfs-wend": - case "cryptkeeper": - case "cpuset": - case "debugfs": - case "devfs": - case "devpts": - case "devtmpfs": - case "encfs": - case "fdesc": - case "fuse.gvfsd-fuse": - case "fusectl": - case "futexfs": - case "hugetlbfs": - case "libpam-encfs": - case "ibpam-mount": - case "mtpfs": - case "mythtvfs": - case "mqueue": - case "openprom": - case "openpromfs": - case "pipefs": - case "plptools": - case "proc": - case "pstore": - case "pytagsfs": - case "ramfs": - case "rofs": - case "romfs": - case "rootfs": - case "securityfs": - case "selinux": - case "selinuxfs": - case "sockfs": - case "sysfs": - case "tmpfs": - case "usbdev": - case "usbdevfs": - return DriveType.Ram; - - case "gphotofs": - case "usbfs": - case "usbdevice": - case "vfat": - return DriveType.Removable; - - // Categorize as "Unknown" everything else not explicitly - // recognized as a particular drive type. - default: - return DriveType.Unknown; - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.cs deleted file mode 100644 index 7e31197149..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [UnmanagedFunctionPointer(CallingConvention.Cdecl)] - private unsafe delegate void MountPointFound(byte* name); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetAllMountPoints", SetLastError = true)] - private static extern int GetAllMountPoints(MountPointFound mpf); - - internal static string[] GetAllMountPoints() - { - int count = 0; - var found = new string[4]; - - unsafe - { - int result = GetAllMountPoints((byte* name) => - { - if (count == found.Length) - { - Array.Resize(ref found, count * 2); - } - found[count++] = Marshal.PtrToStringAnsi((IntPtr)name); - }); - } - - Array.Resize(ref found, count); - return found; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MulticastOption.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MulticastOption.cs deleted file mode 100644 index 8a12048c8e..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.MulticastOption.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal enum MulticastOption : int - { - MULTICAST_ADD = 0, - MULTICAST_DROP = 1, - MULTICAST_IF = 2 - } - - internal struct IPv4MulticastOption - { - public uint MulticastAddress; - public uint LocalAddress; - public int InterfaceIndex; - private int _padding; - } - - internal struct IPv6MulticastOption - { - public IPAddress Address; - public int InterfaceIndex; - private int _padding; - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetIPv4MulticastOption")] - internal static extern unsafe Error GetIPv4MulticastOption(SafeHandle socket, MulticastOption multicastOption, IPv4MulticastOption* option); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetIPv4MulticastOption")] - internal static extern unsafe Error SetIPv4MulticastOption(SafeHandle socket, MulticastOption multicastOption, IPv4MulticastOption* option); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetIPv6MulticastOption")] - internal static extern unsafe Error GetIPv6MulticastOption(SafeHandle socket, MulticastOption multicastOption, IPv6MulticastOption* option); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetIPv6MulticastOption")] - internal static extern unsafe Error SetIPv6MulticastOption(SafeHandle socket, MulticastOption multicastOption, IPv6MulticastOption* option); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.POpen.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.POpen.cs deleted file mode 100644 index 06854f0a45..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.POpen.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_POpen", SetLastError = true)] - internal static extern IntPtr POpen(string command, string type); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_PClose", SetLastError = true)] - internal static extern int PClose(IntPtr stream); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Pipe.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Pipe.cs deleted file mode 100644 index 4cea90805d..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Pipe.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [Flags] - internal enum PipeFlags - { - O_CLOEXEC = 0x0010, - } - - /// - /// The index into the array filled by which represents the read end of the pipe. - /// - internal const int ReadEndOfPipe = 0; - - /// - /// The index into the array filled by which represents the read end of the pipe. - /// - internal const int WriteEndOfPipe = 1; - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Pipe", SetLastError = true)] - internal static extern unsafe int Pipe(int* pipefd, PipeFlags flags = 0); // pipefd is an array of two ints - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.PlatformSocketSupport.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.PlatformSocketSupport.cs deleted file mode 100644 index a148f64c0c..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.PlatformSocketSupport.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_PlatformSupportsDualModeIPv4PacketInfo")] - internal static extern bool PlatformSupportsDualModeIPv4PacketInfo(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Poll.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Poll.cs deleted file mode 100644 index 255cd55291..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Poll.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - [Flags] - internal enum PollEvents : short - { - POLLNONE = 0x0000, // No events occurred. - POLLIN = 0x0001, // non-urgent readable data available - POLLPRI = 0x0002, // urgent readable data available - POLLOUT = 0x0004, // data can be written without blocked - POLLERR = 0x0008, // an error occurred - POLLHUP = 0x0010, // the file descriptor hung up - POLLNVAL = 0x0020, // the requested events were invalid - } - - internal struct PollEvent - { - internal int FileDescriptor; // The file descriptor to poll - internal PollEvents Events; // The events to poll for - internal PollEvents TriggeredEvents; // The events that occurred which triggered the poll - } - - /// - /// Polls a set of file descriptors for signals and returns what signals have been set - /// - /// A list of PollEvent entries - /// The number of entries in pollEvents - /// The amount of time to wait; -1 for infinite, 0 for immediate return, and a positive number is the number of milliseconds - /// The number of events triggered (i.e. the number of entries in pollEvents with a non-zero TriggeredEvents). May be zero in the event of a timeout. - /// An error or Error.SUCCESS. - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Poll")] - internal static extern unsafe Error Poll(PollEvent* pollEvents, uint eventCount, int timeout, uint* triggered); - - /// - /// Polls a File Descriptor for the passed in flags. - /// - /// The descriptor to poll - /// The events to poll for - /// The amount of time to wait; -1 for infinite, 0 for immediate return, and a positive number is the number of milliseconds - /// The events that were returned by the poll call. May be PollEvents.POLLNONE in the case of a timeout. - /// An error or Error.SUCCESS. - internal static unsafe Error Poll(SafeHandle fd, PollEvents events, int timeout, out PollEvents triggered) - { - bool gotRef = false; - try - { - fd.DangerousAddRef(ref gotRef); - - var pollEvent = new PollEvent - { - FileDescriptor = fd.DangerousGetHandle().ToInt32(), - Events = events, - }; - - uint unused; - Error err = Poll(&pollEvent, 1, timeout, &unused); - triggered = pollEvent.TriggeredEvents; - return err; - } - finally - { - if (gotRef) - { - fd.DangerousRelease(); - } - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.PrintF.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.PrintF.cs deleted file mode 100644 index 465c34e4bb..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.PrintF.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - // printf takes a variable number of arguments, which is difficult to represent in C#. - // Instead, since we only have a small and fixed number of call sites, we declare - // an overload for each of the specific argument sets we need. - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_PrintF", SetLastError = true)] - internal static extern unsafe int PrintF(string format, string arg1); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ProcessorArchitecture.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ProcessorArchitecture.cs deleted file mode 100644 index 9535f392f1..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ProcessorArchitecture.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal enum ProcessorArchitecture - { - x86, - x64, - ARM, - ARM64 - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Read.Pipe.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Read.Pipe.cs deleted file mode 100644 index f41f6eefab..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Read.Pipe.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - /// - /// Reads a number of bytes from an open file descriptor into a specified buffer. - /// - /// The open file descriptor to try to read from - /// The buffer to read info into - /// The size of the buffer - /// - /// Returns the number of bytes read on success; otherwise, -1 is returned - /// Note - on fail. the position of the stream may change depending on the platform; consult man 2 read for more info - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Read", SetLastError = true)] - internal static extern unsafe int Read(SafePipeHandle fd, byte* buffer, int count); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ReadDir.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ReadDir.cs deleted file mode 100644 index 695d50ba2b..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ReadDir.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Text; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal static int ReadBufferSize { get; } = GetReadDirRBufferSize(); - - internal enum NodeType : int - { - DT_UNKNOWN = 0, - DT_FIFO = 1, - DT_CHR = 2, - DT_DIR = 4, - DT_BLK = 6, - DT_REG = 8, - DT_LNK = 10, - DT_SOCK = 12, - DT_WHT = 14 - } - - [StructLayout(LayoutKind.Sequential)] - internal unsafe struct DirectoryEntry - { - internal byte* Name; - internal int NameLength; - internal NodeType InodeType; - - internal ReadOnlySpan GetName(Span buffer) - { - Debug.Assert(buffer.Length >= Encoding.UTF8.GetMaxCharCount(255), "should have enough space for the max file name"); - Debug.Assert(Name != null, "should not have a null name"); - - ReadOnlySpan nameBytes = (NameLength == -1) - // In this case the struct was allocated via struct dirent *readdir(DIR *dirp); - ? new ReadOnlySpan(Name, new ReadOnlySpan(Name, 255).IndexOf(0)) - : new ReadOnlySpan(Name, NameLength); - - Debug.Assert(nameBytes.Length > 0, "we shouldn't have gotten a garbage value from the OS"); - if (nameBytes.Length == 0) - return buffer.Slice(0, 0); - - int charCount = Encoding.UTF8.GetChars(nameBytes, buffer); - ReadOnlySpan value = buffer.Slice(0, charCount); - Debug.Assert(NameLength != -1 || value.IndexOf('\0') == -1, "should not have embedded nulls if we parsed the end of string"); - return value; - } - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_OpenDir", SetLastError = true)] - internal static extern IntPtr OpenDir(string path); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetReadDirRBufferSize", SetLastError = false)] - internal static extern int GetReadDirRBufferSize(); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ReadDirR", SetLastError = false)] - private static extern unsafe int ReadDirR(IntPtr dir, ref byte buffer, int bufferSize, ref DirectoryEntry outputEntry); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_CloseDir", SetLastError = true)] - internal static extern int CloseDir(IntPtr dir); - - /// - /// Get the next directory entry for the given handle. **Note** the actual memory used may be allocated - /// by the OS and will be freed when the handle is closed. As such, the handle lifespan MUST be kept tightly - /// controlled. The DirectoryEntry name cannot be accessed after the handle is closed. - /// - /// Call to see what size buffer to allocate. - /// - internal static int ReadDir(IntPtr dir, Span buffer, ref DirectoryEntry entry) - { - // The calling pattern for ReadDir is described in src/Native/Unix/System.Native/pal_io.cpp|.h - Debug.Assert(buffer.Length >= ReadBufferSize, "should have a big enough buffer for the raw data"); - - // ReadBufferSize is zero when the native implementation does not support reading into a buffer. - return ReadDirR(dir, ref MemoryMarshal.GetReference(buffer), ReadBufferSize, ref entry); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ReadStdinUnbuffered.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ReadStdinUnbuffered.cs deleted file mode 100644 index 1b3b0ac7ea..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ReadStdinUnbuffered.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ReadStdin", SetLastError = true)] - internal static extern unsafe int ReadStdin(byte* buffer, int bufferSize); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_InitializeConsoleBeforeRead")] - internal static extern unsafe void InitializeConsoleBeforeRead(byte minChars = 1, byte decisecondsTimeout = 0); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_UninitializeConsoleAfterRead")] - internal static extern unsafe void UninitializeConsoleAfterRead(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RealPath.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RealPath.cs deleted file mode 100644 index aabb54cc7c..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RealPath.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - /// - /// Takes a path containing relative subpaths or links and returns the absolute path. - /// This function works on both files and folders and returns a null-terminated string. - /// - /// The path to the file system object - /// Returns the result string on success and null on failure - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_RealPath", SetLastError = true)] - internal static extern string RealPath(string path); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ReceiveMessage.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ReceiveMessage.cs deleted file mode 100644 index 5a89ecf6de..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ReceiveMessage.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net.Sockets; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ReceiveMessage")] - internal static extern unsafe Error ReceiveMessage(IntPtr socket, MessageHeader* messageHeader, SocketFlags flags, long* received); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RegisterForCtrlC.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RegisterForCtrlC.cs deleted file mode 100644 index 603d8fa68b..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RegisterForCtrlC.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal partial class Interop -{ - internal partial class Sys - { - internal enum CtrlCode - { - Interrupt = 0, - Break = 1 - } - - internal delegate void CtrlCallback(CtrlCode ctrlCode); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_RegisterForCtrl")] - internal static extern void RegisterForCtrl(CtrlCallback handler); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_UnregisterForCtrl")] - internal static extern void UnregisterForCtrl(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RegisterForSigChld.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RegisterForSigChld.cs deleted file mode 100644 index f0d428d45c..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RegisterForSigChld.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal partial class Interop -{ - internal partial class Sys - { - internal delegate void SigChldCallback(bool reapAll); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_RegisterForSigChld")] - internal static extern bool RegisterForSigChld(SigChldCallback handler); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Rename.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Rename.cs deleted file mode 100644 index a82d913a15..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Rename.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - /// - /// Renames a file, moving to the correct destination if necessary. There are many edge cases to this call, check man 2 rename for more info - /// - /// Path to the source item - /// Path to the desired new item - /// - /// Returns 0 on success; otherwise, returns -1 - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Rename", SetLastError = true)] - internal static extern int Rename(string oldPath, string newPath); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ResourceLimits.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ResourceLimits.cs deleted file mode 100644 index bf8bf00700..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ResourceLimits.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal const ulong RLIM_INFINITY = ulong.MaxValue; - - internal enum RlimitResources : int - { - RLIMIT_CPU = 0, // CPU limit in seconds - RLIMIT_FSIZE = 1, // Largest file that can be created, in bytes - RLIMIT_DATA = 2, // Maximum size of data segment, in bytes - RLIMIT_STACK = 3, // Maximum size of stack segment, in bytes - RLIMIT_CORE = 4, // Largest core file that can be created, in bytes - RLIMIT_AS = 5, // Address space limit - RLIMIT_RSS = 6, // Largest resident set size, in bytes - RLIMIT_MEMLOCK = 7, // Locked-in-memory address space - RLIMIT_NPROC = 8, // Number of processes - RLIMIT_NOFILE = 9, // Number of open files - } - - [StructLayout(LayoutKind.Sequential)] - internal struct RLimit - { - internal ulong CurrentLimit; - internal ulong MaximumLimit; - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetRLimit", SetLastError = true)] - internal static extern int GetRLimit(RlimitResources resourceType, out RLimit limits); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetRLimit", SetLastError = true)] - internal static extern int SetRLimit(RlimitResources resourceType, ref RLimit limits); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RestoreAndHandleCtrl.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RestoreAndHandleCtrl.cs deleted file mode 100644 index 0f7b1a1e12..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RestoreAndHandleCtrl.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal partial class Interop -{ - internal partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_RestoreAndHandleCtrl")] - internal static extern void RestoreAndHandleCtrl(CtrlCode ctrlCode); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RmDir.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RmDir.cs deleted file mode 100644 index ddc0c3ad34..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.RmDir.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - /// - /// Deletes the specified empty directory. - /// - /// The path of the directory to delete - /// - /// Returns 0 on success; otherwise, returns -1 - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_RmDir", SetLastError = true)] - internal static extern int RmDir(string path); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SNPrintF.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SNPrintF.cs deleted file mode 100644 index 61fa8d60a0..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SNPrintF.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - /// - /// Takes a string and applies a formatting to it to transform - /// parameters to input values (such as replacing %s in the string with a variable) - /// - /// The output buffer to put the transformed data into - /// The size of the output buffer - /// The input string with wildcards to be replaced - /// The argument to replace a wildcard with - /// - /// Since snprintf has a variadic parameter, which cannot be described by C#, we have different - /// PInvokes declared for each one we need. The PInvoke layer will take care of putting the - /// arguments in correctly. - /// - /// - /// Returns the number of characters (excluding null terminator) written to the buffer on - /// success; if the return value is equal to the size then the result may have been truncated. - /// On failure, returns a negative value. - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SNPrintF", SetLastError = true)] - internal static extern unsafe int SNPrintF(byte* str, int size, string format, string arg1); - - /// - /// Takes a string and applies a formatting to it to transform - /// parameters to input values (such as replacing %s in the string with a variable) - /// - /// The output buffer to put the transformed data into - /// The size of the output buffer - /// The input string with wildcards to be replaced - /// The argument to replace a wildcard with - /// - /// Since snprintf has a variadic parameter, which cannot be described by C#, we have different - /// PInvokes declared for each one we need. The PInvoke layer will take care of putting the - /// arguments in correctly. - /// - /// - /// Returns the number of characters (excluding null terminator) written to the buffer on - /// success; if the return value is equal to the size then the result may have been truncated. - /// On failure, returns a negative value. - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SNPrintF", SetLastError = true)] - internal static extern unsafe int SNPrintF(byte* str, int size, string format, int arg1); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SchedGetSetAffinity.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SchedGetSetAffinity.cs deleted file mode 100644 index 881223aeff..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SchedGetSetAffinity.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SchedSetAffinity", SetLastError = true)] - internal static extern int SchedSetAffinity(int pid, ref IntPtr mask); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SchedGetAffinity", SetLastError = true)] - internal static extern int SchedGetAffinity(int pid, out IntPtr mask); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SendFile.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SendFile.cs deleted file mode 100644 index b253a59b0d..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SendFile.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SendFile", SetLastError = true)] - internal static extern unsafe Error SendFile(SafeHandle out_fd, SafeHandle in_fd, long offset, long count, out long sent); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SendMessage.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SendMessage.cs deleted file mode 100644 index 62cca3bdb5..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SendMessage.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net.Sockets; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SendMessage")] - internal static extern unsafe Error SendMessage(IntPtr socket, MessageHeader* messageHeader, SocketFlags flags, long* sent); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetEUid.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetEUid.cs deleted file mode 100644 index 8f537f8b46..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetEUid.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetEUid")] - internal static extern unsafe int SetEUid(uint euid); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetReceiveTimeout.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetReceiveTimeout.cs deleted file mode 100644 index b1bf252f25..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetReceiveTimeout.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net.Sockets; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetReceiveTimeout")] - internal static extern unsafe Error SetReceiveTimeout(SafeHandle socket, int millisecondsTimeout); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetSendTimeout.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetSendTimeout.cs deleted file mode 100644 index 89a3bfbbf6..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetSendTimeout.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net.Sockets; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetSendTimeout")] - internal static extern unsafe Error SetSendTimeout(SafeHandle socket, int millisecondsTimeout); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetSignalForBreak.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetSignalForBreak.cs deleted file mode 100644 index 40eacccd5a..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetSignalForBreak.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetSignalForBreak")] - internal static extern bool GetSignalForBreak(); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetSignalForBreak")] - internal static extern bool SetSignalForBreak(bool signalForBreak); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetSockOpt.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetSockOpt.cs deleted file mode 100644 index 4c92eccaca..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SetSockOpt.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net.Sockets; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetSockOpt")] - internal static extern unsafe Error SetSockOpt(SafeHandle socket, SocketOptionLevel optionLevel, SocketOptionName optionName, byte* optionValue, int optionLen); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetSockOpt")] - internal static extern unsafe Error SetSockOpt(IntPtr socket, SocketOptionLevel optionLevel, SocketOptionName optionName, byte* optionValue, int optionLen); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ShmOpen.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ShmOpen.cs deleted file mode 100644 index 8481c61dd1..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.ShmOpen.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ShmOpen", SetLastError = true)] - internal static extern SafeFileHandle ShmOpen(string name, OpenFlags flags, int mode); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ShmUnlink", SetLastError = true)] - internal static extern int ShmUnlink(string name); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Shutdown.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Shutdown.cs deleted file mode 100644 index ad5e72945b..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Shutdown.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net.Sockets; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Shutdown")] - internal static extern Error Shutdown(SafeHandle socket, SocketShutdown how); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Socket.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Socket.cs deleted file mode 100644 index e69171690c..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Socket.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Net; -using System.Net.Internals; -using System.Net.Sockets; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Socket")] - internal static extern unsafe Error Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, IntPtr* socket); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SocketAddress.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SocketAddress.cs deleted file mode 100644 index 86a83fdf8c..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SocketAddress.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetIPSocketAddressSizes")] - internal static extern unsafe Error GetIPSocketAddressSizes(int* ipv4SocketAddressSize, int* ipv6SocketAddressSize); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetAddressFamily")] - internal static extern unsafe Error GetAddressFamily(byte* socketAddress, int socketAddressLen, int* addressFamily); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetAddressFamily")] - internal static extern unsafe Error SetAddressFamily(byte* socketAddress, int socketAddressLen, int addressFamily); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetPort")] - internal static extern unsafe Error GetPort(byte* socketAddress, int socketAddressLen, ushort* port); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetPort")] - internal static extern unsafe Error SetPort(byte* socketAddress, int socketAddressLen, ushort port); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetIPv4Address")] - internal static extern unsafe Error GetIPv4Address(byte* socketAddress, int socketAddressLen, uint* address); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetIPv4Address")] - internal static extern unsafe Error SetIPv4Address(byte* socketAddress, int socketAddressLen, uint address); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetIPv6Address")] - internal static extern unsafe Error GetIPv6Address(byte* socketAddress, int socketAddressLen, byte* address, int addressLen, uint* scopeId); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SetIPv6Address")] - internal static extern unsafe Error SetIPv6Address(byte* socketAddress, int socketAddressLen, byte* address, int addressLen, uint scopeId); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SocketEvent.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SocketEvent.cs deleted file mode 100644 index 7752f309aa..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SocketEvent.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [Flags] - internal enum SocketEvents : int - { - None = 0x00, - Read = 0x01, - Write = 0x02, - ReadClose = 0x04, - Close = 0x08, - Error = 0x10 - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SocketEvent - { - public IntPtr Data; - public SocketEvents Events; - private int _padding; - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_CreateSocketEventPort")] - internal static extern unsafe Error CreateSocketEventPort(out IntPtr port); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_CloseSocketEventPort")] - internal static extern Error CloseSocketEventPort(IntPtr port); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_CreateSocketEventBuffer")] - internal static extern unsafe Error CreateSocketEventBuffer(int count, out SocketEvent* buffer); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FreeSocketEventBuffer")] - internal static extern unsafe Error FreeSocketEventBuffer(SocketEvent* buffer); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_TryChangeSocketEventRegistration")] - internal static extern Error TryChangeSocketEventRegistration(IntPtr port, SafeHandle socket, SocketEvents currentEvents, SocketEvents newEvents, IntPtr data); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_TryChangeSocketEventRegistration")] - internal static extern Error TryChangeSocketEventRegistration(IntPtr port, IntPtr socket, SocketEvents currentEvents, SocketEvents newEvents, IntPtr data); - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_WaitForSocketEvents")] - internal static extern unsafe Error WaitForSocketEvents(IntPtr port, SocketEvent* buffer, int* count); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Stat.Pipe.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Stat.Pipe.cs deleted file mode 100644 index 7985cebaa6..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Stat.Pipe.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FStat2", SetLastError = true)] - internal static extern int FStat(SafePipeHandle fd, out FileStatus output); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Stat.Span.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Stat.Span.cs deleted file mode 100644 index 6216a6bda8..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Stat.Span.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Sys - { - // Unix max paths are typically 1K or 4K UTF-8 bytes, 256 should handle the majority of paths - // without putting too much pressure on the stack. - private const int StackBufferSize = 256; - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat2", SetLastError = true)] - internal unsafe static extern int Stat(ref byte path, out FileStatus output); - - internal unsafe static int Stat(ReadOnlySpan path, out FileStatus output) - { - byte* buffer = stackalloc byte[StackBufferSize]; - var converter = new ValueUtf8Converter(new Span(buffer, StackBufferSize)); - int result = Stat(ref MemoryMarshal.GetReference(converter.ConvertAndTerminateString(path)), out output); - converter.Dispose(); - return result; - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LStat2", SetLastError = true)] - internal static extern int LStat(ref byte path, out FileStatus output); - - internal unsafe static int LStat(ReadOnlySpan path, out FileStatus output) - { - byte* buffer = stackalloc byte[StackBufferSize]; - var converter = new ValueUtf8Converter(new Span(buffer, StackBufferSize)); - int result = LStat(ref MemoryMarshal.GetReference(converter.ConvertAndTerminateString(path)), out output); - converter.Dispose(); - return result; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.StdinReady.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.StdinReady.cs deleted file mode 100644 index 7a19512c66..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.StdinReady.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_StdinReady")] - internal static extern unsafe bool StdinReady(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Sync.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Sync.cs deleted file mode 100644 index babb2d6740..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Sync.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - /// - /// Forces a write of all modified I/O buffers to their storage mediums. - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Sync")] - internal static extern void Sync(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SysConf.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SysConf.cs deleted file mode 100644 index be0c0dee7b..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.SysConf.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal enum SysConfName - { - _SC_CLK_TCK = 1, - _SC_PAGESIZE = 2 - } - - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SysConf", SetLastError = true)] - internal static extern long SysConf(SysConfName name); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.UTimensat.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.UTimensat.cs deleted file mode 100644 index 769ca687e3..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.UTimensat.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - internal struct TimeSpec - { - internal long TvSec; - internal long TvNsec; - } - - /// - /// Sets the last access and last modified time of a file - /// - /// The path to the item to get time values for - /// The output time values of the item - /// - /// Returns 0 on success; otherwise, returns -1 - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_UTimensat", SetLastError = true)] - internal static extern int UTimensat(string path, ref TimeSpec times); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.WaitId.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.WaitId.cs deleted file mode 100644 index 3bf9e82e11..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.WaitId.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - /// - /// Returns the pid of a terminated child without reaping it. - /// - /// - /// 1) returns the process id of a terminated child process - /// 2) if no children are terminated, 0 is returned - /// 3) on error, -1 is returned - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_WaitIdAnyExitedNoHangNoWait", SetLastError = true)] - internal static extern int WaitIdAnyExitedNoHangNoWait(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.WaitPid.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.WaitPid.cs deleted file mode 100644 index 8292971d48..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.WaitPid.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Sys - { - /// - /// Reaps a terminated child. - /// - /// - /// 1) when a child is reaped, its process id is returned - /// 2) if pid is not a child or there are no unwaited-for children, -1 is returned (errno=ECHILD) - /// 3) if the child has not yet terminated, 0 is returned - /// 4) on error, -1 is returned. - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_WaitPidExitedNoHang", SetLastError = true)] - internal static extern int WaitPidExitedNoHang(int pid, out int exitCode); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Write.Pipe.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Write.Pipe.cs deleted file mode 100644 index 89bf8c3383..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.Write.Pipe.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Sys - { - /// - /// Writes the specified buffer to the provided open file descriptor - /// - /// The file descriptor to try and write to - /// The data to attempt to write - /// The amount of data to write, in bytes - /// - /// Returns the number of bytes written on success; otherwise, returns -1 and sets errno - /// - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Write", SetLastError = true)] - internal static extern unsafe int Write(SafePipeHandle fd, byte* buffer, int bufferSize); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.CURLcode.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.CURLcode.cs deleted file mode 100644 index b2d0c5c0bb..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.CURLcode.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -internal static partial class Interop -{ - internal static partial class Http - { - // Enum for constants defined for the enum CURLcode in curl.h - internal enum CURLcode - { - CURLE_OK = 0, - CURLE_UNSUPPORTED_PROTOCOL = 1, - CURLE_FAILED_INIT = 2, - CURLE_NOT_BUILT_IN = 4, - CURLE_COULDNT_RESOLVE_HOST = 6, - CURLE_OUT_OF_MEMORY = 27, - CURLE_OPERATION_TIMEDOUT = 28, - CURLE_ABORTED_BY_CALLBACK = 42, - CURLE_UNKNOWN_OPTION = 48, - CURLE_RECV_ERROR = 56, - CURLE_SEND_FAIL_REWIND = 65 - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.Easy.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.Easy.cs deleted file mode 100644 index ab3200b333..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.Easy.cs +++ /dev/null @@ -1,268 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Http - { - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyCreate")] - public static extern SafeCurlHandle EasyCreate(); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyDestroy")] - private static extern void EasyDestroy(IntPtr handle); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionString", CharSet = CharSet.Ansi)] - public static extern CURLcode EasySetOptionString(SafeCurlHandle curl, CURLoption option, string value); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionLong")] - public static extern CURLcode EasySetOptionLong(SafeCurlHandle curl, CURLoption option, long value); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionPointer")] - public static extern CURLcode EasySetOptionPointer(SafeCurlHandle curl, CURLoption option, IntPtr value); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionPointer")] - public static extern CURLcode EasySetOptionPointer(SafeCurlHandle curl, CURLoption option, SafeHandle value); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetErrorString")] - public static extern IntPtr EasyGetErrorString(int code); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoPointer")] - public static extern CURLcode EasyGetInfoPointer(IntPtr handle, CURLINFO info, out IntPtr value); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoPointer")] - public static extern CURLcode EasyGetInfoPointer(SafeCurlHandle handle, CURLINFO info, out IntPtr value); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoLong")] - public static extern CURLcode EasyGetInfoLong(SafeCurlHandle handle, CURLINFO info, out long value); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyPerform")] - public static extern CURLcode EasyPerform(SafeCurlHandle curl); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyUnpause")] - public static extern CURLcode EasyUnpause(SafeCurlHandle easy); - - public delegate CurlSeekResult SeekCallback(IntPtr userPointer, long offset, int origin); - - public delegate ulong ReadWriteCallback(IntPtr buffer, ulong bufferSize, ulong nitems, IntPtr userPointer); - - public delegate CURLcode SslCtxCallback(IntPtr curl, IntPtr sslCtx, IntPtr userPointer); - - public delegate void DebugCallback(IntPtr curl, CurlInfoType type, IntPtr data, ulong size, IntPtr userPointer); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterSeekCallback")] - public static extern void RegisterSeekCallback( - SafeCurlHandle curl, - SeekCallback callback, - IntPtr userPointer, - ref SafeCallbackHandle callbackHandle); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterReadWriteCallback")] - public static extern void RegisterReadWriteCallback( - SafeCurlHandle curl, - ReadWriteFunction functionType, - ReadWriteCallback callback, - IntPtr userPointer, - ref SafeCallbackHandle callbackHandle); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterSslCtxCallback")] - public static extern CURLcode RegisterSslCtxCallback( - SafeCurlHandle curl, - SslCtxCallback callback, - IntPtr userPointer, - ref SafeCallbackHandle callbackHandle); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterDebugCallback")] - public static extern CURLcode RegisterDebugCallback( - SafeCurlHandle curl, - DebugCallback callback, - IntPtr userPointer, - ref SafeCallbackHandle callbackHandle); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_FreeCallbackHandle")] - private static extern void FreeCallbackHandle(IntPtr handle); - - // Curl options are of the format + - private const int CurlOptionLongBase = 0; - private const int CurlOptionObjectPointBase = 10000; - private const int CurlOptionOffTBase = 30000; - - // Enum for constants defined for the enum CURLoption in curl.h - internal enum CURLoption - { - CURLOPT_INFILESIZE = CurlOptionLongBase + 14, - CURLOPT_SSLVERSION = CurlOptionLongBase + 32, - CURLOPT_VERBOSE = CurlOptionLongBase + 41, - CURLOPT_NOBODY = CurlOptionLongBase + 44, - CURLOPT_UPLOAD = CurlOptionLongBase + 46, - CURLOPT_POST = CurlOptionLongBase + 47, - CURLOPT_FOLLOWLOCATION = CurlOptionLongBase + 52, - CURLOPT_PROXYPORT = CurlOptionLongBase + 59, - CURLOPT_POSTFIELDSIZE = CurlOptionLongBase + 60, - CURLOPT_SSL_VERIFYPEER = CurlOptionLongBase + 64, - CURLOPT_MAXREDIRS = CurlOptionLongBase + 68, - CURLOPT_SSL_VERIFYHOST = CurlOptionLongBase + 81, - CURLOPT_HTTP_VERSION = CurlOptionLongBase + 84, - CURLOPT_DNS_CACHE_TIMEOUT = CurlOptionLongBase + 92, - CURLOPT_NOSIGNAL = CurlOptionLongBase + 99, - CURLOPT_PROXYTYPE = CurlOptionLongBase + 101, - CURLOPT_HTTPAUTH = CurlOptionLongBase + 107, - CURLOPT_TCP_NODELAY = CurlOptionLongBase + 121, - CURLOPT_TCP_KEEPALIVE = CurlOptionLongBase + 213, - CURLOPT_CONNECTTIMEOUT_MS = CurlOptionLongBase + 156, - CURLOPT_ADDRESS_SCOPE = CurlOptionLongBase + 171, - CURLOPT_PROTOCOLS = CurlOptionLongBase + 181, - CURLOPT_REDIR_PROTOCOLS = CurlOptionLongBase + 182, - - CURLOPT_URL = CurlOptionObjectPointBase + 2, - CURLOPT_PROXY = CurlOptionObjectPointBase + 4, - CURLOPT_PROXYUSERPWD = CurlOptionObjectPointBase + 6, - CURLOPT_COOKIE = CurlOptionObjectPointBase + 22, - CURLOPT_HTTPHEADER = CurlOptionObjectPointBase + 23, - CURLOPT_CUSTOMREQUEST = CurlOptionObjectPointBase + 36, - CURLOPT_ACCEPT_ENCODING = CurlOptionObjectPointBase + 102, - CURLOPT_PRIVATE = CurlOptionObjectPointBase + 103, - CURLOPT_COPYPOSTFIELDS = CurlOptionObjectPointBase + 165, - CURLOPT_USERNAME = CurlOptionObjectPointBase + 173, - CURLOPT_PASSWORD = CurlOptionObjectPointBase + 174, - CURLOPT_CAPATH = CurlOptionObjectPointBase + 97, - CURLOPT_PROXY_CAPATH = CurlOptionObjectPointBase + 247, - CURLOPT_CAINFO = CurlOptionObjectPointBase + 65, - CURLOPT_PROXY_CAINFO = CurlOptionObjectPointBase + 246, - - CURLOPT_INFILESIZE_LARGE = CurlOptionOffTBase + 115, - CURLOPT_POSTFIELDSIZE_LARGE = CurlOptionOffTBase + 120, - } - - internal enum ReadWriteFunction - { - Write = 0, - Read = 1, - Header = 2, - } - - // Curl info are of the format + - private const int CurlInfoStringBase = 0x100000; - private const int CurlInfoLongBase = 0x200000; - - // Enum for constants defined for CURL_HTTP_VERSION - internal enum CurlHttpVersion - { - CURL_HTTP_VERSION_NONE = 0, - CURL_HTTP_VERSION_1_0 = 1, - CURL_HTTP_VERSION_1_1 = 2, - CURL_HTTP_VERSION_2TLS = 4, - }; - - // Enum for constants defined for CURL_SSLVERSION - internal enum CurlSslVersion - { - CURL_SSLVERSION_TLSv1 = 1, /* TLS 1.x */ - CURL_SSLVERSION_SSLv2 = 2, /* SSL 2 */ - CURL_SSLVERSION_SSLv3 = 3, /* SSL 3 */ - CURL_SSLVERSION_TLSv1_0 = 4, /* TLS 1.0 */ - CURL_SSLVERSION_TLSv1_1 = 5, /* TLS 1.1 */ - CURL_SSLVERSION_TLSv1_2 = 6, /* TLS 1.2 */ - }; - - // Enum for constants defined for the enum CURLINFO in curl.h - internal enum CURLINFO - { - CURLINFO_EFFECTIVE_URL = CurlInfoStringBase + 1, - CURLINFO_PRIVATE = CurlInfoStringBase + 21, - CURLINFO_HTTPAUTH_AVAIL = CurlInfoLongBase + 23, - } - - // AUTH related constants - [Flags] - internal enum CURLAUTH - { - None = 0, - Basic = 1 << 0, - Digest = 1 << 1, - Negotiate = 1 << 2, - NTLM = 1 << 3, - } - - // Enum for constants defined for the enum curl_proxytype in curl.h - internal enum curl_proxytype - { - CURLPROXY_HTTP = 0, - } - - [Flags] - internal enum CurlProtocols - { - CURLPROTO_HTTP = (1 << 0), - CURLPROTO_HTTPS = (1 << 1), - } - - // Enum for constants defined for the results of CURL_SEEKFUNCTION - internal enum CurlSeekResult : int - { - CURL_SEEKFUNC_OK = 0, - CURL_SEEKFUNC_FAIL = 1, - CURL_SEEKFUNC_CANTSEEK = 2, - } - - internal enum CurlInfoType : int - { - CURLINFO_TEXT = 0, - CURLINFO_HEADER_IN = 1, - CURLINFO_HEADER_OUT = 2, - CURLINFO_DATA_IN = 3, - CURLINFO_DATA_OUT = 4, - CURLINFO_SSL_DATA_IN = 5, - CURLINFO_SSL_DATA_OUT = 6, - }; - - // constants defined for the results of a CURL_READ or CURL_WRITE function - internal const ulong CURL_READFUNC_ABORT = 0x10000000; - internal const ulong CURL_READFUNC_PAUSE = 0x10000001; - internal const ulong CURL_WRITEFUNC_PAUSE = 0x10000001; - - internal const ulong CURL_MAX_HTTP_HEADER = 100 * 1024; - - internal sealed class SafeCurlHandle : SafeHandle - { - public SafeCurlHandle() : base(IntPtr.Zero, true) - { - } - - public override bool IsInvalid - { - get { return handle == IntPtr.Zero; } - } - - protected override bool ReleaseHandle() - { - EasyDestroy(handle); - SetHandle(IntPtr.Zero); - return true; - } - } - - internal sealed class SafeCallbackHandle : SafeHandle - { - public SafeCallbackHandle() - : base(IntPtr.Zero, true) - { - } - - public override bool IsInvalid - { - get { return handle == IntPtr.Zero; } - } - - protected override bool ReleaseHandle() - { - FreeCallbackHandle(handle); - SetHandle(IntPtr.Zero); - return true; - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.Initialization.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.Initialization.cs deleted file mode 100644 index eef56ec0b3..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.Initialization.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - // Initialization of libcurl is done in a static constructor. - // This enables a project simply to include this file, and any usage of any of - // the Http functions will trigger initialization. - - internal static partial class Http - { - static Http() - { - HttpInitializer.Initialize(); - } - } - - internal static class HttpInitializer - { - static HttpInitializer() - { -#if !SYSNETHTTP_NO_OPENSSL - string opensslVersion = Interop.Http.GetSslVersionDescription(); - if (string.IsNullOrEmpty(opensslVersion) || - opensslVersion.IndexOf(Interop.Http.OpenSsl10Description, StringComparison.OrdinalIgnoreCase) != -1) - { - // CURL uses OpenSSL which we must initialize first to guarantee thread-safety - // Only initialize for OpenSSL/1.0, any newer versions may have mismatched - // pointers, resulting in segfaults. - CryptoInitializer.Initialize(); - } -#endif - - if (EnsureCurlIsInitialized() != 0) - { - throw new InvalidOperationException(); - } - } - - internal static void Initialize() - { - // No-op that exists to provide a hook for other static constructors - } - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EnsureCurlIsInitialized")] - private static extern int EnsureCurlIsInitialized(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.Multi.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.Multi.cs deleted file mode 100644 index f3c058e319..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.Multi.cs +++ /dev/null @@ -1,104 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Http - { - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_MultiCreate")] - public static extern SafeCurlMultiHandle MultiCreate(); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_MultiDestroy")] - private static extern CURLMcode MultiDestroy(IntPtr handle); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_MultiAddHandle")] - public static extern CURLMcode MultiAddHandle(SafeCurlMultiHandle multiHandle, SafeCurlHandle easyHandle); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_MultiRemoveHandle")] - public static extern CURLMcode MultiRemoveHandle(SafeCurlMultiHandle multiHandle, SafeCurlHandle easyHandle); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_MultiWait")] - public static extern CURLMcode MultiWait( - SafeCurlMultiHandle multiHandle, - SafeFileHandle extraFileDescriptor, - out bool isExtraFileDescriptorActive, - out bool isTimeout); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_MultiPerform")] - public static extern CURLMcode MultiPerform(SafeCurlMultiHandle multiHandle); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_MultiInfoRead")] - public static extern bool MultiInfoRead( - SafeCurlMultiHandle multiHandle, - out CURLMSG message, - out IntPtr easyHandle, - out CURLcode result); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_MultiGetErrorString")] - public static extern IntPtr MultiGetErrorString(int code); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_MultiSetOptionLong")] - public static extern CURLMcode MultiSetOptionLong(SafeCurlMultiHandle curl, CURLMoption option, long value); - - // Enum for constants defined for the enum CURLMcode in multi.h - internal enum CURLMcode : int - { - CURLM_CALL_MULTI_PERFORM = -1, - CURLM_OK = 0, - CURLM_BAD_HANDLE = 1, - CURLM_BAD_EASY_HANDLE = 2, - CURLM_OUT_OF_MEMORY = 3, - CURLM_INTERNAL_ERROR = 4, - CURLM_BAD_SOCKET = 5, - CURLM_UNKNOWN_OPTION = 6, - CURLM_ADDED_ALREADY = 7, - } - - internal enum CURLMoption : int - { - CURLMOPT_PIPELINING = 3, - CURLMOPT_MAX_HOST_CONNECTIONS = 7, - } - - internal enum CurlPipe : int - { - CURLPIPE_MULTIPLEX = 2 - } - - // Enum for constants defined for the enum CURLMSG in multi.h - internal enum CURLMSG : int - { - CURLMSG_DONE = 1, - } - - internal sealed class SafeCurlMultiHandle : SafeHandle - { - public SafeCurlMultiHandle() - : base(IntPtr.Zero, true) - { - } - - public override bool IsInvalid - { - get { return this.handle == IntPtr.Zero; } - } - - protected override bool ReleaseHandle() - { - bool result = MultiDestroy(handle) == CURLMcode.CURLM_OK; - SetHandle(IntPtr.Zero); - -#if !SYSNETHTTP_NO_OPENSSL - Interop.Crypto.ErrClearError(); // Ensure that no SSL errors were left on the queue by libcurl. -#endif - - return result; - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.SList.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.SList.cs deleted file mode 100644 index 58fe776f93..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.SList.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Http - { - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_SListAppend", CharSet = CharSet.Ansi)] - private static extern IntPtr SListAppend(IntPtr slist, string headerValue); - - internal static bool SListAppend(SafeCurlSListHandle slist, string headerValue) - { - bool gotRef = false; - try - { - slist.DangerousAddRef(ref gotRef); - IntPtr newHandle = SListAppend(slist.DangerousGetHandle(), headerValue); - if (newHandle != IntPtr.Zero) - { - slist.SetHandle(newHandle); - return true; - } - return false; - } - finally - { - if (gotRef) - slist.DangerousRelease(); - } - } - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_SListFreeAll")] - private static extern void SListFreeAll(IntPtr slist); - - internal sealed class SafeCurlSListHandle : SafeHandle - { - public SafeCurlSListHandle() : base(IntPtr.Zero, true) - { - } - - public override bool IsInvalid - { - get { return handle == IntPtr.Zero; } - } - - public new void SetHandle(IntPtr newHandle) - { - base.SetHandle(newHandle); - } - - protected override bool ReleaseHandle() - { - SListFreeAll(handle); - SetHandle(IntPtr.Zero); - return true; - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.VersionInfo.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.VersionInfo.cs deleted file mode 100644 index 1899fd0af3..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.VersionInfo.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Http - { - [Flags] - internal enum CurlFeatures : int - { - CURL_VERSION_IPV6 = (1 << 0), - CURL_VERSION_KERBEROS4 = (1 << 1), - CURL_VERSION_SSL = (1 << 2), - CURL_VERSION_LIBZ = (1 << 3), - CURL_VERSION_NTLM = (1 << 4), - CURL_VERSION_GSSNEGOTIATE = (1 << 5), - CURL_VERSION_DEBUG = (1 << 6), - CURL_VERSION_ASYNCHDNS = (1 << 7), - CURL_VERSION_SPNEGO = (1 << 8), - CURL_VERSION_LARGEFILE = (1 << 9), - CURL_VERSION_IDN = (1 << 10), - CURL_VERSION_SSPI = (1 << 11), - CURL_VERSION_CONV = (1 << 12), - CURL_VERSION_CURLDEBUG = (1 << 13), - CURL_VERSION_TLSAUTH_SRP = (1 << 14), - CURL_VERSION_NTLM_WB = (1 << 15), - CURL_VERSION_HTTP2 = (1 << 16), - CURL_VERSION_GSSAPI = (1 << 17), - CURL_VERSION_KERBEROS5 = (1 << 18), - CURL_VERSION_UNIX_SOCKETS = (1 << 19), - CURL_VERSION_PSL = (1 << 20), - }; - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_GetSupportedFeatures")] - internal static extern CurlFeatures GetSupportedFeatures(); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_GetSupportsHttp2Multiplexing")] - internal static extern bool GetSupportsHttp2Multiplexing(); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_GetVersionDescription")] - internal static extern string GetVersionDescription(); - - [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_GetSslVersionDescription")] - internal static extern string GetSslVersionDescription(); - - internal const string OpenSsl10Description = "openssl/1.0"; - internal const string SecureTransportDescription = "SecureTransport"; - internal const string LibreSslDescription = "LibreSSL"; - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssApiException.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssApiException.cs index 88c07619c4..2defe1a735 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssApiException.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssApiException.cs @@ -3,8 +3,6 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; -using System.Diagnostics; using System.Runtime.InteropServices; internal static partial class Interop @@ -13,22 +11,19 @@ internal static partial class NetSecurityNative { internal sealed class GssApiException : Exception { - private readonly Status _minorStatus; + internal Status MinorStatus { get; private set; } - public Status MinorStatus - { - get { return _minorStatus;} - } + internal GssApiException() { } - public GssApiException(string message) : base(message) - { - } + internal GssApiException(string message) : base(message) { } + + internal GssApiException(string message, Exception innerException) : base(message, innerException) { } - public GssApiException(Status majorStatus, Status minorStatus) + internal GssApiException(Status majorStatus, Status minorStatus) : base(GetGssApiDisplayStatus(majorStatus, minorStatus)) { HResult = (int)majorStatus; - _minorStatus = minorStatus; + MinorStatus = minorStatus; } private static string GetGssApiDisplayStatus(Status majorStatus, Status minorStatus) @@ -43,13 +38,12 @@ private static string GetGssApiDisplayStatus(Status majorStatus, Status minorSta private static string GetGssApiDisplayStatus(Status status, bool isMinor) { - GssBuffer displayBuffer = default(GssBuffer); + GssBuffer displayBuffer = default; try { - Interop.NetSecurityNative.Status minStat; - Interop.NetSecurityNative.Status displayCallStatus = isMinor ? - DisplayMinorStatus(out minStat, status, ref displayBuffer): + Status displayCallStatus = isMinor ? + DisplayMinorStatus(out Status minStat, status, ref displayBuffer) : DisplayMajorStatus(out minStat, status, ref displayBuffer); return (Status.GSS_S_COMPLETE != displayCallStatus) ? null : Marshal.PtrToStringAnsi(displayBuffer._data); } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs index f70aabfb68..80a32e6c5a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs @@ -5,7 +5,6 @@ using System; using System.Diagnostics; using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; internal static partial class Interop { @@ -32,7 +31,7 @@ internal int Copy(byte[] destination, int offset) int destinationAvailable = destination.Length - offset; // amount of space in the given buffer if (sourceLength > destinationAvailable) { - throw new NetSecurityNative.GssApiException(StringsHelper.Format(Strings.net_context_buffer_too_small, sourceLength, destinationAvailable)); + throw new GssApiException(StringsHelper.Format(Strings.net_context_buffer_too_small, sourceLength, destinationAvailable)); } Marshal.Copy(_data, destination, offset, sourceLength); @@ -56,7 +55,7 @@ public void Dispose() { if (_data != IntPtr.Zero) { - Interop.NetSecurityNative.ReleaseGssBuffer(_data, _length); + ReleaseGssBuffer(_data, _length); _data = IntPtr.Zero; } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs index ab08863b9f..e3e3e3759b 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.cs @@ -5,56 +5,55 @@ using System; using System.Diagnostics; using System.Runtime.InteropServices; -using System.Text; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class NetSecurityNative { - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ReleaseGssBuffer")] + [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ReleaseGssBuffer")] internal static extern void ReleaseGssBuffer( IntPtr bufferPtr, ulong length); - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_DisplayMinorStatus")] + [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_DisplayMinorStatus")] internal static extern Status DisplayMinorStatus( out Status minorStatus, Status statusValue, ref GssBuffer buffer); - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_DisplayMajorStatus")] + [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_DisplayMajorStatus")] internal static extern Status DisplayMajorStatus( out Status minorStatus, Status statusValue, ref GssBuffer buffer); - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ImportUserName")] + [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ImportUserName", CharSet = CharSet.Unicode)] internal static extern Status ImportUserName( out Status minorStatus, string inputName, int inputNameByteCount, out SafeGssNameHandle outputName); - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ImportPrincipalName")] + [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ImportPrincipalName", CharSet = CharSet.Unicode)] internal static extern Status ImportPrincipalName( out Status minorStatus, string inputName, int inputNameByteCount, out SafeGssNameHandle outputName); - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ReleaseName")] + [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ReleaseName")] internal static extern Status ReleaseName( out Status minorStatus, ref IntPtr inputName); - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_InitiateCredSpNego")] + [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_InitiateCredSpNego")] internal static extern Status InitiateCredSpNego( out Status minorStatus, SafeGssNameHandle desiredName, out SafeGssCredHandle outputCredHandle); - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_InitiateCredWithPassword")] + [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_InitiateCredWithPassword", CharSet = CharSet.Unicode)] internal static extern Status InitiateCredWithPassword( out Status minorStatus, bool isNtlm, @@ -63,12 +62,12 @@ internal static extern Status InitiateCredWithPassword( int passwordLen, out SafeGssCredHandle outputCredHandle); - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ReleaseCred")] + [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_ReleaseCred")] internal static extern Status ReleaseCred( out Status minorStatus, ref IntPtr credHandle); - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_InitSecContext")] + [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_InitSecContext")] internal static extern Status InitSecContext( out Status minorStatus, SafeGssCredHandle initiatorCredHandle, @@ -82,69 +81,11 @@ internal static extern Status InitSecContext( out uint retFlags, out int isNtlmUsed); - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_AcceptSecContext")] - internal static extern Status AcceptSecContext( - out Status minorStatus, - ref SafeGssContextHandle acceptContextHandle, - byte[] inputBytes, - int inputLength, - ref GssBuffer token); - - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_DeleteSecContext")] + [DllImport(Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_DeleteSecContext")] internal static extern Status DeleteSecContext( out Status minorStatus, ref IntPtr contextHandle); - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_Wrap")] - private static extern Status Wrap( - out Status minorStatus, - SafeGssContextHandle contextHandle, - bool isEncrypt, - byte[] inputBytes, - int offset, - int count, - ref GssBuffer outBuffer); - - [DllImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_Unwrap")] - private static extern Status Unwrap( - out Status minorStatus, - SafeGssContextHandle contextHandle, - byte[] inputBytes, - int offset, - int count, - ref GssBuffer outBuffer); - - internal static Status WrapBuffer( - out Status minorStatus, - SafeGssContextHandle contextHandle, - bool isEncrypt, - byte[] inputBytes, - int offset, - int count, - ref GssBuffer outBuffer) - { - Debug.Assert(inputBytes != null, "inputBytes must be valid value"); - Debug.Assert(offset >= 0 && offset <= inputBytes.Length, "offset must be valid"); - Debug.Assert(count >= 0 && count <= (inputBytes.Length - offset), "count must be valid"); - - return Wrap(out minorStatus, contextHandle, isEncrypt, inputBytes, offset, count, ref outBuffer); - } - - internal static Status UnwrapBuffer( - out Status minorStatus, - SafeGssContextHandle contextHandle, - byte[] inputBytes, - int offset, - int count, - ref GssBuffer outBuffer) - { - Debug.Assert(inputBytes != null, "inputBytes must be valid value"); - Debug.Assert(offset >= 0 && offset <= inputBytes.Length, "offset must be valid"); - Debug.Assert(count >= 0 && count <= inputBytes.Length, "count must be valid"); - - return Unwrap(out minorStatus, contextHandle, inputBytes, offset, count, ref outBuffer); - } - internal enum Status : uint { GSS_S_COMPLETE = 0, diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.GetIntegerBytes.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.GetIntegerBytes.cs deleted file mode 100644 index 692abb2ab4..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.GetIntegerBytes.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Text; - -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetAsn1IntegerDerSize")] - private static extern int GetAsn1IntegerDerSize(SafeSharedAsn1IntegerHandle i); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EncodeAsn1Integer")] - private static extern int EncodeAsn1Integer(SafeSharedAsn1IntegerHandle i, byte[] buf); - - internal static byte[] GetAsn1IntegerBytes(SafeSharedAsn1IntegerHandle asn1Integer) - { - CheckValidOpenSslHandle(asn1Integer); - - // OpenSSL stores negative numbers in their two's complement (positive) form, but - // sets an internal negative bit. - // - // If the number was positive, but could sign-test as negative, DER puts in a leading - // 0x00 byte, which reading OpenSSL's data directly won't have. - // - // So to ensure we're getting a set of bytes compatible with BigInteger (though with the - // wrong endianness here), DER encode it, then use the DER reader to skip past the tag - // and length. - byte[] derEncoded = OpenSslEncode( - handle => GetAsn1IntegerDerSize(handle), - (handle, buf) => EncodeAsn1Integer(handle, buf), - asn1Integer); - - DerSequenceReader reader = DerSequenceReader.CreateForPayload(derEncoded); - return reader.ReadIntegerBytes(); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.Nid.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.Nid.cs deleted file mode 100644 index afc79ae504..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.Nid.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Crypto - { - internal const int NID_undef = 0; - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ObjSn2Nid", CharSet = CharSet.Ansi)] - internal static extern int ObjSn2Nid(string sn); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.cs deleted file mode 100644 index 5bd2e8b9b4..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ASN1.cs +++ /dev/null @@ -1,113 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Cryptography; - -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ObjTxt2Obj", CharSet = CharSet.Ansi)] - internal static extern SafeAsn1ObjectHandle ObjTxt2Obj(string s); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ObjObj2Txt")] - private static extern unsafe int ObjObj2Txt(byte* buf, int buf_len, IntPtr a); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetObjectDefinitionByName", CharSet = CharSet.Ansi)] - private static extern IntPtr CryptoNative_GetObjectDefinitionByName(string friendlyName); - internal static IntPtr GetObjectDefinitionByName(string friendlyName) - { - IntPtr ret = CryptoNative_GetObjectDefinitionByName(friendlyName); - if (ret == IntPtr.Zero) - { - ErrClearError(); - } - - return ret; - } - - // Returns shared pointers, should not be tracked as a SafeHandle. - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ObjNid2Obj")] - internal static extern IntPtr ObjNid2Obj(int nid); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1ObjectFree")] - internal static extern void Asn1ObjectFree(IntPtr o); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeAsn1BitString")] - internal static extern SafeAsn1BitStringHandle DecodeAsn1BitString(byte[] buf, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1BitStringFree")] - internal static extern void Asn1BitStringFree(IntPtr o); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeAsn1OctetString")] - internal static extern SafeAsn1OctetStringHandle DecodeAsn1OctetString(byte[] buf, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1OctetStringNew")] - internal static extern SafeAsn1OctetStringHandle Asn1OctetStringNew(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1OctetStringSet")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool Asn1OctetStringSet(SafeAsn1OctetStringHandle o, byte[] d, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1OctetStringFree")] - internal static extern void Asn1OctetStringFree(IntPtr o); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Asn1StringFree")] - internal static extern void Asn1StringFree(IntPtr o); - - internal static unsafe string GetOidValue(IntPtr asn1ObjectPtr) - { - // OBJ_obj2txt returns the number of bytes that should have been in the answer, but it does not accept - // a NULL buffer. The documentation says "A buffer length of 80 should be more than enough to handle - // any OID encountered in practice", so start with a buffer of size 80, and try again if required. - const int StackCapacity = 80; - byte* bufStack = stackalloc byte[StackCapacity]; - - int bytesNeeded = ObjObj2Txt(bufStack, StackCapacity, asn1ObjectPtr); - - if (bytesNeeded < 0) - { - throw CreateOpenSslCryptographicException(); - } - - Debug.Assert(bytesNeeded != 0, "OBJ_obj2txt reported a zero-length response"); - - if (bytesNeeded < StackCapacity) - { - return Marshal.PtrToStringAnsi((IntPtr)bufStack, bytesNeeded); - } - - // bytesNeeded does not count the \0 which will be written on the end (based on OpenSSL 1.0.1f), - // so make sure to leave room for it. - int initialBytesNeeded = bytesNeeded; - byte[] bufHeap = new byte[bytesNeeded + 1]; - fixed (byte* buf = &bufHeap[0]) - { - bytesNeeded = ObjObj2Txt(buf, bufHeap.Length, asn1ObjectPtr); - - if (bytesNeeded < 0) - { - throw CreateOpenSslCryptographicException(); - } - - Debug.Assert( - bytesNeeded == initialBytesNeeded, - "OBJ_obj2txt changed the required number of bytes for the realloc call"); - - if (bytesNeeded > initialBytesNeeded) - { - // OBJ_obj2txt is demanding yet more memory - throw new CryptographicException(); - } - - return Marshal.PtrToStringAnsi((IntPtr)buf, bytesNeeded); - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.BIO.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.BIO.cs deleted file mode 100644 index ffa82ef001..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.BIO.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Text; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_CreateMemoryBio")] - internal static extern SafeBioHandle CreateMemoryBio(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioNewFile")] - internal static extern SafeBioHandle BioNewFile(string filename, string mode); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioDestroy")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool BioDestroy(IntPtr a); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioGets")] - internal static extern int BioGets(SafeBioHandle b, byte[] buf, int size); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioRead")] - internal static extern int BioRead(SafeBioHandle b, byte[] data, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")] - internal static extern int BioWrite(SafeBioHandle b, byte[] data, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetMemoryBioSize")] - internal static extern int GetMemoryBioSize(SafeBioHandle bio); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioCtrlPending")] - internal static extern int BioCtrlPending(SafeBioHandle bio); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Bignum.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Bignum.cs deleted file mode 100644 index 6faf7f8915..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Bignum.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BigNumDestroy")] - internal static extern void BigNumDestroy(IntPtr a); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BigNumFromBinary")] - private static extern IntPtr BigNumFromBinary(byte[] s, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BigNumToBinary")] - private static extern unsafe int BigNumToBinary(SafeBignumHandle a, byte* to); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetBigNumBytes")] - private static extern int GetBigNumBytes(SafeBignumHandle a); - - private static IntPtr CreateBignumPtr(byte[] bigEndianValue) - { - if (bigEndianValue == null) - { - return IntPtr.Zero; - } - - IntPtr ret = BigNumFromBinary(bigEndianValue, bigEndianValue.Length); - - if (ret == IntPtr.Zero) - { - throw CreateOpenSslCryptographicException(); - } - - return ret; - } - - internal static SafeBignumHandle CreateBignum(byte[] bigEndianValue) - { - IntPtr handle = CreateBignumPtr(bigEndianValue); - return new SafeBignumHandle(handle, true); - } - - internal static byte[] ExtractBignum(IntPtr bignum, int targetSize) - { - // Given that the only reference held to bignum is an IntPtr, create an unowned SafeHandle - // to ensure that we don't destroy the key after extraction. - using (SafeBignumHandle handle = new SafeBignumHandle(bignum, ownsHandle: false)) - { - return ExtractBignum(handle, targetSize); - } - } - - private static unsafe byte[] ExtractBignum(SafeBignumHandle bignum, int targetSize) - { - if (bignum == null || bignum.IsInvalid) - { - return null; - } - - int compactSize = GetBigNumBytes(bignum); - - if (targetSize < compactSize) - { - targetSize = compactSize; - } - - // OpenSSL BIGNUM values do not record leading zeroes. - // Windows Crypt32 does. - // - // Since RSACryptoServiceProvider already checks that RSAParameters.DP.Length is - // exactly half of RSAParameters.Modulus.Length, we need to left-pad (big-endian) - // the array with zeroes. - int offset = targetSize - compactSize; - - byte[] buf = new byte[targetSize]; - - fixed (byte* to = buf) - { - byte* start = to + offset; - BigNumToBinary(bignum, start); - } - - return buf; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Crypto.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Crypto.cs deleted file mode 100644 index cfcac7d7dc..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Crypto.cs +++ /dev/null @@ -1,183 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Security.Cryptography.X509Certificates; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - private delegate int NegativeSizeReadMethod(THandle handle, byte[] buf, int cBuf); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioTell")] - internal static extern int CryptoNative_BioTell(SafeBioHandle bio); - - internal static int BioTell(SafeBioHandle bio) - { - int ret = CryptoNative_BioTell(bio); - if (ret < 0) - { - throw CreateOpenSslCryptographicException(); - } - - return ret; - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioSeek")] - internal static extern int BioSeek(SafeBioHandle bio, int pos); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509Thumbprint")] - private static extern int GetX509Thumbprint(SafeX509Handle x509, byte[] buf, int cBuf); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509NameRawBytes")] - private static extern int GetX509NameRawBytes(IntPtr x509Name, byte[] buf, int cBuf); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ReadX509AsDerFromBio")] - internal static extern SafeX509Handle ReadX509AsDerFromBio(SafeBioHandle bio); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509NotBefore")] - internal static extern IntPtr GetX509NotBefore(SafeX509Handle x509); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509NotAfter")] - internal static extern IntPtr GetX509NotAfter(SafeX509Handle x509); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509CrlNextUpdate")] - internal static extern IntPtr GetX509CrlNextUpdate(SafeX509CrlHandle crl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509Version")] - internal static extern int GetX509Version(SafeX509Handle x509); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509SignatureAlgorithm")] - internal static extern IntPtr GetX509SignatureAlgorithm(SafeX509Handle x509); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509PublicKeyAlgorithm")] - internal static extern IntPtr GetX509PublicKeyAlgorithm(SafeX509Handle x509); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509PublicKeyParameterBytes")] - private static extern int GetX509PublicKeyParameterBytes(SafeX509Handle x509, byte[] buf, int cBuf); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509PublicKeyBytes")] - internal static extern IntPtr GetX509PublicKeyBytes(SafeX509Handle x509); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509EkuFieldCount")] - internal static extern int GetX509EkuFieldCount(SafeEkuExtensionHandle eku); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509EkuField")] - internal static extern IntPtr GetX509EkuField(SafeEkuExtensionHandle eku, int loc); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509NameInfo")] - internal static extern SafeBioHandle GetX509NameInfo(SafeX509Handle x509, int nameType, [MarshalAs(UnmanagedType.Bool)] bool forIssuer); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetAsn1StringBytes")] - private static extern int GetAsn1StringBytes(IntPtr asn1, byte[] buf, int cBuf); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PushX509StackField")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool PushX509StackField(SafeX509StackHandle stack, SafeX509Handle x509); - - internal static string GetX509RootStorePath() - { - return Marshal.PtrToStringAnsi(GetX509RootStorePath_private()); - } - - internal static string GetX509RootStoreFile() - { - return Marshal.PtrToStringAnsi(GetX509RootStoreFile_private()); - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509RootStorePath")] - private static extern IntPtr GetX509RootStorePath_private(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509RootStoreFile")] - private static extern IntPtr GetX509RootStoreFile_private(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SetX509ChainVerifyTime")] - private static extern int SetX509ChainVerifyTime( - SafeX509StoreCtxHandle ctx, - int year, - int month, - int day, - int hour, - int minute, - int second, - [MarshalAs(UnmanagedType.Bool)] bool isDst); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_CheckX509IpAddress")] - internal static extern int CheckX509IpAddress(SafeX509Handle x509, [In]byte[] addressBytes, int addressLen, string hostname, int cchHostname); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_CheckX509Hostname")] - internal static extern int CheckX509Hostname(SafeX509Handle x509, string hostname, int cchHostname); - - internal static byte[] GetAsn1StringBytes(IntPtr asn1) - { - return GetDynamicBuffer((ptr, buf, i) => GetAsn1StringBytes(ptr, buf, i), asn1); - } - - internal static byte[] GetX509Thumbprint(SafeX509Handle x509) - { - return GetDynamicBuffer((handle, buf, i) => GetX509Thumbprint(handle, buf, i), x509); - } - - internal static X500DistinguishedName LoadX500Name(IntPtr namePtr) - { - CheckValidOpenSslHandle(namePtr); - - byte[] buf = GetDynamicBuffer((ptr, buf1, i) => GetX509NameRawBytes(ptr, buf1, i), namePtr); - return new X500DistinguishedName(buf); - } - - internal static byte[] GetX509PublicKeyParameterBytes(SafeX509Handle x509) - { - return GetDynamicBuffer((handle, buf, i) => GetX509PublicKeyParameterBytes(handle, buf, i), x509); - } - - internal static void SetX509ChainVerifyTime(SafeX509StoreCtxHandle ctx, DateTime verifyTime) - { - // OpenSSL is going to convert our input time to universal, so we should be in Local or - // Unspecified (local-assumed). - Debug.Assert(verifyTime.Kind != DateTimeKind.Utc, "UTC verifyTime should have been normalized to Local"); - - int succeeded = SetX509ChainVerifyTime( - ctx, - verifyTime.Year, - verifyTime.Month, - verifyTime.Day, - verifyTime.Hour, - verifyTime.Minute, - verifyTime.Second, - verifyTime.IsDaylightSavingTime()); - - if (succeeded != 1) - { - throw Interop.Crypto.CreateOpenSslCryptographicException(); - } - } - - private static byte[] GetDynamicBuffer(NegativeSizeReadMethod method, THandle handle) - { - int negativeSize = method(handle, null, 0); - - if (negativeSize > 0) - { - throw Interop.Crypto.CreateOpenSslCryptographicException(); - } - - byte[] bytes = new byte[-negativeSize]; - - int ret = method(handle, bytes, bytes.Length); - - if (ret != 1) - { - throw Interop.Crypto.CreateOpenSslCryptographicException(); - } - - return bytes; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Dsa.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Dsa.cs deleted file mode 100644 index 8d69e89577..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Dsa.cs +++ /dev/null @@ -1,176 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DsaCreate")] - internal static extern SafeDsaHandle DsaCreate(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DsaUpRef")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DsaUpRef(IntPtr dsa); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DsaDestroy")] - internal static extern void DsaDestroy(IntPtr dsa); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DsaGenerateKey")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DsaGenerateKey(out SafeDsaHandle dsa, int bits); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DsaSizeSignature")] - private static extern int DsaSizeSignature(SafeDsaHandle dsa); - - /// - /// Return the maximum size of the DER-encoded key in bytes. - /// - internal static int DsaEncodedSignatureSize(SafeDsaHandle dsa) - { - int size = DsaSizeSignature(dsa); - return size; - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DsaSizeQ")] - private static extern int DsaSizeQ(SafeDsaHandle dsa); - - /// - /// Return the size of the 'r' or 's' signature fields in bytes. - /// - internal static int DsaSignatureFieldSize(SafeDsaHandle dsa) - { - int size = DsaSizeQ(dsa); - Debug.Assert(size * 2 < DsaEncodedSignatureSize(dsa)); - return size; - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DsaSizeP")] - private static extern int DsaSizeP(SafeDsaHandle dsa); - - /// - /// Return the size of the key in bytes. - /// - internal static int DsaKeySize(SafeDsaHandle dsa) - { - int keySize = DsaSizeP(dsa); - - // Assume an even multiple of 8 bytes \ 64 bits (OpenSsl also makes the same assumption) - keySize = (keySize + 7) / 8 * 8; - return keySize; - } - - internal static bool DsaSign(SafeDsaHandle dsa, ReadOnlySpan hash, int hashLength, ReadOnlySpan refSignature, out int outSignatureLength) => - DsaSign(dsa, ref MemoryMarshal.GetReference(hash), hashLength, ref MemoryMarshal.GetReference(refSignature), out outSignatureLength); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DsaSign")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool DsaSign(SafeDsaHandle dsa, ref byte hash, int hashLength, ref byte refSignature, out int outSignatureLength); - - internal static bool DsaVerify(SafeDsaHandle dsa, ReadOnlySpan hash, ReadOnlySpan signature) - { - bool ret = DsaVerify( - dsa, - ref MemoryMarshal.GetReference(hash), - hash.Length, - ref MemoryMarshal.GetReference(signature), - signature.Length); - - // Error queue already cleaned on the native function. - - return ret; - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DsaVerify")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool DsaVerify(SafeDsaHandle dsa, ref byte hash, int hashLength, ref byte signature, int signatureLength); - - internal static DSAParameters ExportDsaParameters(SafeDsaHandle key, bool includePrivateParameters) - { - Debug.Assert( - key != null && !key.IsInvalid, - "Callers should check the key is invalid and throw an exception with a message"); - - if (key == null || key.IsInvalid) - { - throw new CryptographicException(); - } - - IntPtr p_bn, q_bn, g_bn, y_bn, x_bn; // these are not owned - int p_cb, q_cb, g_cb, y_cb, x_cb; - - bool refAdded = false; - try - { - key.DangerousAddRef(ref refAdded); // Protect access to the *_bn variables - - if (!GetDsaParameters(key, - out p_bn, out p_cb, - out q_bn, out q_cb, - out g_bn, out g_cb, - out y_bn, out y_cb, - out x_bn, out x_cb)) - { - throw new CryptographicException(); - } - - // Match Windows semantics where p, g and y have same length - int pgy_cb = GetMax(p_cb, g_cb, y_cb); - - // Match Windows semantics where q and x have same length - int qx_cb = GetMax(q_cb, x_cb); - - DSAParameters dsaParameters = new DSAParameters - { - P = Crypto.ExtractBignum(p_bn, pgy_cb), - Q = Crypto.ExtractBignum(q_bn, qx_cb), - G = Crypto.ExtractBignum(g_bn, pgy_cb), - Y = Crypto.ExtractBignum(y_bn, pgy_cb), - }; - - if (includePrivateParameters) - { - dsaParameters.X = Crypto.ExtractBignum(x_bn, qx_cb); - } - - return dsaParameters; - } - finally - { - if (refAdded) - key.DangerousRelease(); - } - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetDsaParameters")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool GetDsaParameters( - SafeDsaHandle key, - out IntPtr p, out int p_cb, - out IntPtr q, out int q_cb, - out IntPtr g, out int g_cb, - out IntPtr y, out int y_cb, - out IntPtr x, out int x_cb); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DsaKeyCreateByExplicitParameters")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DsaKeyCreateByExplicitParameters( - out SafeDsaHandle dsa, - byte[] p, - int pLength, - byte[] q, - int qLength, - byte[] g, - int gLength, - byte[] y, - int yLength, - byte[] x, - int xLength); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ERR.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ERR.cs deleted file mode 100644 index 95d24bc12d..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.ERR.cs +++ /dev/null @@ -1,123 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Text; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ErrClearError")] - internal static extern ulong ErrClearError(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ErrGetError")] - internal static extern ulong ErrGetError(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ErrGetErrorAlloc")] - private static extern ulong ErrGetErrorAlloc([MarshalAs(UnmanagedType.Bool)] out bool isAllocFailure); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ErrPeekError")] - internal static extern ulong ErrPeekError(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ErrPeekLastError")] - internal static extern ulong ErrPeekLastError(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ErrReasonErrorString")] - internal static extern IntPtr ErrReasonErrorString(ulong error); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ErrErrorStringN")] - private static extern unsafe void ErrErrorStringN(ulong e, byte* buf, int len); - - private static unsafe string ErrErrorStringN(ulong error) - { - var buffer = new byte[1024]; - fixed (byte* buf = &buffer[0]) - { - ErrErrorStringN(error, buf, buffer.Length); - return Marshal.PtrToStringAnsi((IntPtr)buf); - } - } - - internal static Exception CreateOpenSslCryptographicException() - { - // The Windows cryptography library reports error codes through - // Marshal.GetLastWin32Error, which has a single value when the - // function exits, last writer wins. - // - // OpenSSL maintains an error queue. Calls to ERR_get_error read - // values out of the queue in the order that ERR_set_error wrote - // them. Nothing enforces that a single call into an OpenSSL - // function will guarantee at-most one error being set. - // - // In order to maintain parity in how error flows look between the - // Windows code and the OpenSSL-calling code, drain the queue - // whenever an Exception is desired, and report the exception - // related to the last value in the queue. - bool isAllocFailure; - ulong error = ErrGetErrorAlloc(out isAllocFailure); - ulong lastRead = error; - bool lastIsAllocFailure = isAllocFailure; - - // 0 (there's no named constant) is only returned when the calls - // to ERR_get_error exceed the calls to ERR_set_error. - while (lastRead != 0) - { - error = lastRead; - isAllocFailure = lastIsAllocFailure; - - lastRead = ErrGetErrorAlloc(out lastIsAllocFailure); - } - - // If we're in an error flow which results in an Exception, but - // no calls to ERR_set_error were made, throw the unadorned - // CryptographicException. - if (error == 0) - { - return new CryptographicException(); - } - - if (isAllocFailure) - { - return new OutOfMemoryException(); - } - - // Even though ErrGetError returns ulong (C++ unsigned long), we - // really only expect error codes in the UInt32 range - Debug.Assert(error <= uint.MaxValue, "ErrGetError should only return error codes in the UInt32 range."); - - // If there was an error code, and it wasn't something handled specially, - // use the OpenSSL error string as the message to a CryptographicException. - return new OpenSslCryptographicException(unchecked((int)error), ErrErrorStringN(error)); - } - - internal static void CheckValidOpenSslHandle(SafeHandle handle) - { - if (handle == null || handle.IsInvalid) - { - throw CreateOpenSslCryptographicException(); - } - } - - internal static void CheckValidOpenSslHandle(IntPtr handle) - { - if (handle == IntPtr.Zero) - { - throw CreateOpenSslCryptographicException(); - } - } - - private sealed class OpenSslCryptographicException : CryptographicException - { - internal OpenSslCryptographicException(int errorCode, string message) - : base(message) - { - HResult = errorCode; - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EVP.Cipher.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EVP.Cipher.cs deleted file mode 100644 index 44cbc146b1..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EVP.Cipher.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherCreate2")] - internal static extern SafeEvpCipherCtxHandle EvpCipherCreate( - IntPtr cipher, - byte[] key, - int keyLength, - int effectivekeyLength, - byte[] iv, - int enc); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherDestroy")] - internal static extern void EvpCipherDestroy(IntPtr ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherReset")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool EvpCipherReset(SafeEvpCipherCtxHandle ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherCtxSetPadding")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool EvpCipherCtxSetPadding(SafeEvpCipherCtxHandle x, int padding); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherUpdate")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool EvpCipherUpdate( - SafeEvpCipherCtxHandle ctx, - byte* @out, - out int outl, - byte* @in, - int inl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpCipherFinalEx")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern unsafe bool EvpCipherFinalEx( - SafeEvpCipherCtxHandle ctx, - byte* outm, - out int outl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes128Ecb")] - internal static extern IntPtr EvpAes128Ecb(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes128Cbc")] - internal static extern IntPtr EvpAes128Cbc(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes192Ecb")] - internal static extern IntPtr EvpAes192Ecb(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes192Cbc")] - internal static extern IntPtr EvpAes192Cbc(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes256Ecb")] - internal static extern IntPtr EvpAes256Ecb(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpAes256Cbc")] - internal static extern IntPtr EvpAes256Cbc(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpDesCbc")] - internal static extern IntPtr EvpDesCbc(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpDesEcb")] - internal static extern IntPtr EvpDesEcb(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpDes3Cbc")] - internal static extern IntPtr EvpDes3Cbc(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpDes3Ecb")] - internal static extern IntPtr EvpDes3Ecb(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpRC2Cbc")] - internal static extern IntPtr EvpRC2Cbc(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpRC2Ecb")] - internal static extern IntPtr EvpRC2Ecb(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EVP.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EVP.cs deleted file mode 100644 index 67a9b54230..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EVP.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpMdCtxCreate")] - internal extern static SafeEvpMdCtxHandle EvpMdCtxCreate(IntPtr type); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpMdCtxDestroy")] - internal extern static void EvpMdCtxDestroy(IntPtr ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpDigestReset")] - internal extern static int EvpDigestReset(SafeEvpMdCtxHandle ctx, IntPtr type); - - internal static int EvpDigestUpdate(SafeEvpMdCtxHandle ctx, ReadOnlySpan d, int cnt) => - EvpDigestUpdate(ctx, ref MemoryMarshal.GetReference(d), cnt); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpDigestUpdate")] - private extern static int EvpDigestUpdate(SafeEvpMdCtxHandle ctx, ref byte d, int cnt); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpDigestFinalEx")] - internal extern static int EvpDigestFinalEx(SafeEvpMdCtxHandle ctx, ref byte md, ref uint s); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpMdSize")] - internal extern static int EvpMdSize(IntPtr md); - - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpMd5")] - internal extern static IntPtr EvpMd5(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpSha1")] - internal extern static IntPtr EvpSha1(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpSha256")] - internal extern static IntPtr EvpSha256(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpSha384")] - internal extern static IntPtr EvpSha384(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpSha512")] - internal extern static IntPtr EvpSha512(); - - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetMaxMdSize")] - private extern static int GetMaxMdSize(); - - internal static readonly int EVP_MAX_MD_SIZE = GetMaxMdSize(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs deleted file mode 100644 index f2b0bfc192..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs +++ /dev/null @@ -1,338 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using Microsoft.Win32.SafeHandles; -using System; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyGetCurveType")] - internal static extern ECCurve.ECCurveType EcKeyGetCurveType(SafeEcKeyHandle key); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByKeyParameters", CharSet = CharSet.Ansi)] - private static extern int EcKeyCreateByKeyParameters( - out SafeEcKeyHandle key, - string oid, - byte[] qx, int qxLength, - byte[] qy, int qyLength, - byte[] d, int dLength); - - internal static SafeEcKeyHandle EcKeyCreateByKeyParameters( - string oid, - byte[] qx, int qxLength, - byte[] qy, int qyLength, - byte[] d, int dLength) - { - SafeEcKeyHandle key; - int rc = EcKeyCreateByKeyParameters(out key, oid, qx, qxLength, qy, qyLength, d, dLength); - if (rc == -1) - { - key?.Dispose(); - Interop.Crypto.ErrClearError(); - - throw new PlatformNotSupportedException(Strings.Format(Strings.Cryptography_CurveNotSupported, oid)); - } - return key; - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByExplicitParameters")] - internal static extern SafeEcKeyHandle EcKeyCreateByExplicitParameters( - ECCurve.ECCurveType curveType, - byte[] qx, int qxLength, - byte[] qy, int qyLength, - byte[] d, int dLength, - byte[] p, int pLength, - byte[] a, int aLength, - byte[] b, int bLength, - byte[] gx, int gxLength, - byte[] gy, int gyLength, - byte[] order, int nLength, - byte[] cofactor, int cofactorLength, - byte[] seed, int seedLength); - - internal static SafeEcKeyHandle EcKeyCreateByExplicitCurve(ECCurve curve) - { - byte[] p; - if (curve.IsPrime) - { - p = curve.Prime; - } - else if (curve.IsCharacteristic2) - { - p = curve.Polynomial; - } - else - { - throw new PlatformNotSupportedException(Strings.Format(Strings.Cryptography_CurveNotSupported, curve.CurveType.ToString())); - } - - SafeEcKeyHandle key = Interop.Crypto.EcKeyCreateByExplicitParameters( - curve.CurveType, - null, 0, - null, 0, - null, 0, - p, p.Length, - curve.A, curve.A.Length, - curve.B, curve.B.Length, - curve.G.X, curve.G.X.Length, - curve.G.Y, curve.G.Y.Length, - curve.Order, curve.Order.Length, - curve.Cofactor, curve.Cofactor.Length, - curve.Seed, curve.Seed == null ? 0 : curve.Seed.Length); - - if (key == null || key.IsInvalid) - { - if (key != null) - key.Dispose(); - throw Interop.Crypto.CreateOpenSslCryptographicException(); - } - - // EcKeyCreateByExplicitParameters may have polluted the error queue, but key was good in the end. - // Clean up the error queue. - Interop.Crypto.ErrClearError(); - - return key; - } - - - [DllImport(Libraries.CryptoNative)] - private static extern int CryptoNative_GetECKeyParameters( - SafeEcKeyHandle key, - bool includePrivate, - out SafeBignumHandle qx_bn, out int x_cb, - out SafeBignumHandle qy_bn, out int y_cb, - out IntPtr d_bn_not_owned, out int d_cb); - - internal static ECParameters GetECKeyParameters( - SafeEcKeyHandle key, - bool includePrivate) - { - SafeBignumHandle qx_bn, qy_bn, d_bn; - IntPtr d_bn_not_owned; - int qx_cb, qy_cb, d_cb; - ECParameters parameters = new ECParameters(); - - bool refAdded = false; - try - { - key.DangerousAddRef(ref refAdded); // Protect access to d_bn_not_owned - int rc = CryptoNative_GetECKeyParameters( - key, - includePrivate, - out qx_bn, out qx_cb, - out qy_bn, out qy_cb, - out d_bn_not_owned, out d_cb); - - if (rc == -1) - { - throw new CryptographicException(Strings.Cryptography_CSP_NoPrivateKey); - } - else if (rc != 1) - { - throw Interop.Crypto.CreateOpenSslCryptographicException(); - } - - using (qx_bn) - using (qy_bn) - using (d_bn = new SafeBignumHandle(d_bn_not_owned, false)) - { - // Match Windows semantics where qx, qy, and d have same length - int keySizeBits = EcKeyGetSize(key); - int expectedSize = (keySizeBits + 7) / 8; - int cbKey = GetMax(qx_cb, qy_cb, d_cb); - - Debug.Assert( - cbKey <= expectedSize, - $"Expected output size was {expectedSize}, which a parameter exceeded. qx={qx_cb}, qy={qy_cb}, d={d_cb}"); - - cbKey = GetMax(cbKey, expectedSize); - - parameters.Q = new ECPoint - { - X = Crypto.ExtractBignum(qx_bn, cbKey), - Y = Crypto.ExtractBignum(qy_bn, cbKey) - }; - parameters.D = d_cb == 0 ? null : Crypto.ExtractBignum(d_bn, cbKey); - } - } - finally - { - if (refAdded) - key.DangerousRelease(); - } - - return parameters; - } - - [DllImport(Libraries.CryptoNative)] - private static extern int CryptoNative_GetECCurveParameters( - SafeEcKeyHandle key, - bool includePrivate, - out ECCurve.ECCurveType curveType, - out SafeBignumHandle qx, out int x_cb, - out SafeBignumHandle qy, out int y_cb, - out IntPtr d_bn_not_owned, out int d_cb, - out SafeBignumHandle p, out int P_cb, - out SafeBignumHandle a, out int A_cb, - out SafeBignumHandle b, out int B_cb, - out SafeBignumHandle gx, out int Gx_cb, - out SafeBignumHandle gy, out int Gy_cb, - out SafeBignumHandle order, out int order_cb, - out SafeBignumHandle cofactor, out int cofactor_cb, - out SafeBignumHandle seed, out int seed_cb); - - internal static ECParameters GetECCurveParameters( - SafeEcKeyHandle key, - bool includePrivate) - { - ECCurve.ECCurveType curveType; - SafeBignumHandle qx_bn, qy_bn, p_bn, a_bn, b_bn, gx_bn, gy_bn, order_bn, cofactor_bn, seed_bn; - IntPtr d_bn_not_owned; - int qx_cb, qy_cb, p_cb, a_cb, b_cb, gx_cb, gy_cb, order_cb, cofactor_cb, seed_cb, d_cb; - - bool refAdded = false; - try - { - key.DangerousAddRef(ref refAdded); // Protect access to d_bn_not_owned - int rc = CryptoNative_GetECCurveParameters( - key, - includePrivate, - out curveType, - out qx_bn, out qx_cb, - out qy_bn, out qy_cb, - out d_bn_not_owned, out d_cb, - out p_bn, out p_cb, - out a_bn, out a_cb, - out b_bn, out b_cb, - out gx_bn, out gx_cb, - out gy_bn, out gy_cb, - out order_bn, out order_cb, - out cofactor_bn, out cofactor_cb, - out seed_bn, out seed_cb); - - if (rc == -1) - { - throw new CryptographicException(Strings.Cryptography_CSP_NoPrivateKey); - } - else if (rc != 1) - { - throw Interop.Crypto.CreateOpenSslCryptographicException(); - } - - using (qx_bn) - using (qy_bn) - using (p_bn) - using (a_bn) - using (b_bn) - using (gx_bn) - using (gy_bn) - using (order_bn) - using (cofactor_bn) - using (seed_bn) - using (var d_h = new SafeBignumHandle(d_bn_not_owned, false)) - { - int cbFieldLength; - int pFieldLength; - if (curveType == ECCurve.ECCurveType.Characteristic2) - { - // Match Windows semantics where a,b,gx,gy,qx,qy have same length - // Treat length of m separately as it is not tied to other fields for Char2 (Char2 not supported by Windows) - cbFieldLength = GetMax(new[] { a_cb, b_cb, gx_cb, gy_cb, qx_cb, qy_cb }); - pFieldLength = p_cb; - } - else - { - // Match Windows semantics where p,a,b,gx,gy,qx,qy have same length - cbFieldLength = GetMax(new[] { p_cb, a_cb, b_cb, gx_cb, gy_cb, qx_cb, qy_cb }); - pFieldLength = cbFieldLength; - } - - // Match Windows semantics where order and d have same length - int cbSubgroupOrder = GetMax(order_cb, d_cb); - - // Copy values to ECParameters - ECParameters parameters = new ECParameters(); - parameters.Q = new ECPoint - { - X = Crypto.ExtractBignum(qx_bn, cbFieldLength), - Y = Crypto.ExtractBignum(qy_bn, cbFieldLength) - }; - parameters.D = d_cb == 0 ? null : Crypto.ExtractBignum(d_h, cbSubgroupOrder); - - var curve = parameters.Curve; - curve.CurveType = curveType; - curve.A = Crypto.ExtractBignum(a_bn, cbFieldLength); - curve.B = Crypto.ExtractBignum(b_bn, cbFieldLength); - curve.G = new ECPoint - { - X = Crypto.ExtractBignum(gx_bn, cbFieldLength), - Y = Crypto.ExtractBignum(gy_bn, cbFieldLength) - }; - curve.Order = Crypto.ExtractBignum(order_bn, cbSubgroupOrder); - - if (curveType == ECCurve.ECCurveType.Characteristic2) - { - curve.Polynomial = Crypto.ExtractBignum(p_bn, pFieldLength); - } - else - { - curve.Prime = Crypto.ExtractBignum(p_bn, pFieldLength); - } - - // Optional parameters - curve.Cofactor = cofactor_cb == 0 ? null : Crypto.ExtractBignum(cofactor_bn, cofactor_cb); - curve.Seed = seed_cb == 0 ? null : Crypto.ExtractBignum(seed_bn, seed_cb); - - parameters.Curve = curve; - return parameters; - } - } - finally - { - if (refAdded) - key.DangerousRelease(); - } - } - - /// - /// Return the maximum value in the array; assumes non-negative values. - /// - private static int GetMax(int[] values) - { - int max = 0; - - foreach (var i in values) - { - Debug.Assert(i >= 0); - if (i > max) - max = i; - } - - return max; - } - - /// - /// Return the maximum value in the array; assumes non-negative values. - /// - private static int GetMax(int value1, int value2) - { - Debug.Assert(value1 >= 0); - Debug.Assert(value2 >= 0); - return (value1 > value2 ? value1 : value2); - } - - /// - /// Return the maximum value in the array; assumes non-negative values. - /// - private static int GetMax(int value1, int value2, int value3) - { - return GetMax(GetMax(value1, value2), value3); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.cs deleted file mode 100644 index 17c1232f24..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - internal static bool EcDsaSign(ReadOnlySpan dgst, int dlen, Span sig, [In, Out] ref int siglen, SafeEcKeyHandle ecKey) => - EcDsaSign(ref MemoryMarshal.GetReference(dgst), dlen, ref MemoryMarshal.GetReference(sig), ref siglen, ecKey); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcDsaSign")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool EcDsaSign(ref byte dgst, int dlen, ref byte sig, [In, Out] ref int siglen, SafeEcKeyHandle ecKey); - - internal static int EcDsaVerify(ReadOnlySpan dgst, ReadOnlySpan sigbuf, SafeEcKeyHandle ecKey) - { - int ret = EcDsaVerify( - ref MemoryMarshal.GetReference(dgst), - dgst.Length, - ref MemoryMarshal.GetReference(sigbuf), - sigbuf.Length, - ecKey); - - if (ret < 0) - { - ErrClearError(); - } - - return ret; - } - - /*- - * returns - * 1: correct signature - * 0: incorrect signature - * -1: error - */ - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcDsaVerify")] - private static extern int EcDsaVerify(ref byte dgst, int dgst_len, ref byte sigbuf, int sig_len, SafeEcKeyHandle ecKey); - - // returns the maximum length of a DER encoded ECDSA signature created with this key. - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcDsaSize")] - private static extern int CryptoNative_EcDsaSize(SafeEcKeyHandle ecKey); - - internal static int EcDsaSize(SafeEcKeyHandle ecKey) - { - int ret = CryptoNative_EcDsaSize(ecKey); - - if (ret == 0) - { - throw CreateOpenSslCryptographicException(); - } - - return ret; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcKey.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcKey.cs deleted file mode 100644 index b9e7c91d9e..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcKey.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Win32.SafeHandles; -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByOid")] - private static extern SafeEcKeyHandle CryptoNative_EcKeyCreateByOid(string oid); - internal static SafeEcKeyHandle EcKeyCreateByOid(string oid) - { - SafeEcKeyHandle handle = CryptoNative_EcKeyCreateByOid(oid); - if (handle == null || handle.IsInvalid) - { - ErrClearError(); - } - - return handle; - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyDestroy")] - internal static extern void EcKeyDestroy(IntPtr a); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyGenerateKey")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool EcKeyGenerateKey(SafeEcKeyHandle eckey); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyUpRef")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool EcKeyUpRef(IntPtr r); - - [DllImport(Libraries.CryptoNative)] - private static extern int CryptoNative_EcKeyGetSize(SafeEcKeyHandle ecKey, out int keySize); - internal static int EcKeyGetSize(SafeEcKeyHandle key) - { - int keySize; - int rc = CryptoNative_EcKeyGetSize(key, out keySize); - if (rc == 1) - { - return keySize; - } - throw Interop.Crypto.CreateOpenSslCryptographicException(); - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyGetCurveName2")] - private static extern int CryptoNative_EcKeyGetCurveName(SafeEcKeyHandle ecKey, out int nid); - - internal static string EcKeyGetCurveName(SafeEcKeyHandle key) - { - int nidCurveName; - int rc = CryptoNative_EcKeyGetCurveName(key, out nidCurveName); - if (rc == 1) - { - if (nidCurveName == Interop.Crypto.NID_undef) - { - Debug.Fail("Key is invalid or doesn't have a curve"); - return string.Empty; - } - - IntPtr objCurveName = Interop.Crypto.ObjNid2Obj(nidCurveName); - if (objCurveName != IntPtr.Zero) - { - return Interop.Crypto.GetOidValue(objCurveName); - } - } - throw Interop.Crypto.CreateOpenSslCryptographicException(); - } - - internal static bool EcKeyHasCurveName(SafeEcKeyHandle key) - { - int nidCurveName; - int rc = CryptoNative_EcKeyGetCurveName(key, out nidCurveName); - if (rc == 1) - { - // Key is invalid or doesn't have a curve - return (nidCurveName != Interop.Crypto.NID_undef); - } - throw Interop.Crypto.CreateOpenSslCryptographicException(); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Encode.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Encode.cs deleted file mode 100644 index 27861a263e..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Encode.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Cryptography; - -internal static partial class Interop -{ - internal static partial class Crypto - { - internal delegate int GetEncodedSizeFunc(THandle handle); - - internal delegate int EncodeFunc(THandle handle, byte[] buf); - - internal static byte[] OpenSslEncode(GetEncodedSizeFunc getSize, EncodeFunc encode, THandle handle) - where THandle : SafeHandle - { - int size = getSize(handle); - - if (size < 1) - { - throw Crypto.CreateOpenSslCryptographicException(); - } - - byte[] data = new byte[size]; - - int size2 = encode(handle, data); - if (size2 < 1) - { - Debug.Fail( - $"{nameof(OpenSslEncode)}: {nameof(getSize)} succeeded ({size}) and {nameof(encode)} failed ({size2})"); - - // If it ever happens, ensure the error queue gets cleared. - // And since it didn't write the data, reporting an exception is good too. - throw CreateOpenSslCryptographicException(); - } - - Debug.Assert(size == size2); - - return data; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Dsa.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Dsa.cs deleted file mode 100644 index 6c1d3cddc1..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Dsa.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPkeyGetDsa")] - internal static extern SafeDsaHandle EvpPkeyGetDsa(SafeEvpPKeyHandle pkey); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPkeySetDsa")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool EvpPkeySetDsa(SafeEvpPKeyHandle pkey, SafeDsaHandle key); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.EcKey.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.EcKey.cs deleted file mode 100644 index 70dfa425d5..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.EcKey.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPkeyGetEcKey")] - internal static extern SafeEcKeyHandle EvpPkeyGetEcKey(SafeEvpPKeyHandle pkey); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPkeySetEcKey")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool EvpPkeySetEcKey(SafeEvpPKeyHandle pkey, SafeEcKeyHandle key); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Ecdh.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Ecdh.cs deleted file mode 100644 index 74967f6104..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Ecdh.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPKeyCtxCreate")] - internal static extern SafeEvpPKeyCtxHandle EvpPKeyCtxCreate(SafeEvpPKeyHandle pkey, SafeEvpPKeyHandle peerkey, out uint secretLength); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPKeyDeriveSecretAgreement")] - private static extern int EvpPKeyDeriveSecretAgreement( - ref byte secret, - uint secretLength, - SafeEvpPKeyCtxHandle ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPKeyCtxDestroy")] - internal static extern void EvpPKeyCtxDestroy(IntPtr ctx); - - internal static void EvpPKeyDeriveSecretAgreement(SafeEvpPKeyCtxHandle ctx, Span destination) - { - Debug.Assert(ctx != null); - Debug.Assert(!ctx.IsInvalid); - - int ret = EvpPKeyDeriveSecretAgreement( - ref MemoryMarshal.GetReference(destination), - (uint)destination.Length, - ctx); - - if (ret != 1) - { - throw CreateOpenSslCryptographicException(); - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Rsa.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Rsa.cs deleted file mode 100644 index 1f61a826a9..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.Rsa.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPkeyGetRsa")] - internal static extern SafeRsaHandle EvpPkeyGetRsa(SafeEvpPKeyHandle pkey); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPkeySetRsa")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool EvpPkeySetRsa(SafeEvpPKeyHandle pkey, SafeRsaHandle rsa); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.cs deleted file mode 100644 index 2eff6bfcd1..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Security.Cryptography; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPkeyCreate")] - internal static extern SafeEvpPKeyHandle EvpPkeyCreate(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPkeyDestroy")] - internal static extern void EvpPkeyDestroy(IntPtr pkey); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_UpRefEvpPkey")] - internal static extern int UpRefEvpPkey(SafeEvpPKeyHandle handle); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Hmac.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Hmac.cs deleted file mode 100644 index 6849b4f2e0..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Hmac.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_HmacCreate")] - internal extern static SafeHmacCtxHandle HmacCreate(ref byte key, int keyLen, IntPtr md); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_HmacDestroy")] - internal extern static void HmacDestroy(IntPtr ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_HmacReset")] - internal extern static int HmacReset(SafeHmacCtxHandle ctx); - - internal static int HmacUpdate(SafeHmacCtxHandle ctx, ReadOnlySpan data, int len) => - HmacUpdate(ctx, ref MemoryMarshal.GetReference(data), len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_HmacUpdate")] - private extern static int HmacUpdate(SafeHmacCtxHandle ctx, ref byte data, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_HmacFinal")] - internal extern static int HmacFinal(SafeHmacCtxHandle ctx, ref byte data, ref int len); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Initialization.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Initialization.cs deleted file mode 100644 index 7f105dec44..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Initialization.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - // Initialization of libcrypto threading support is done in a static constructor. - // This enables a project simply to include this file, and any usage of any of - // the System.Security.Cryptography.Native functions will trigger - // initialization of the threading support. - - internal static partial class Crypto - { - static Crypto() - { - CryptoInitializer.Initialize(); - } - } - - internal static class CryptoInitializer - { - static CryptoInitializer() - { - if (EnsureOpenSslInitialized() != 0) - { - // Ideally this would be a CryptographicException, but we use - // OpenSSL in libraries lower than System.Security.Cryptography. - // It's not a big deal, though: this will already be wrapped in a - // TypeLoadException, and this failing means something is very - // wrong with the system's configuration and any code using - // these libraries will be unable to operate correctly. - throw new InvalidOperationException(); - } - } - - internal static void Initialize() - { - // No-op that exists to provide a hook for other static constructors. - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EnsureOpenSslInitialized")] - private static extern int EnsureOpenSslInitialized(); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.LookupFriendlyNameByOid.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.LookupFriendlyNameByOid.cs deleted file mode 100644 index 37c1dd40e6..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.LookupFriendlyNameByOid.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_LookupFriendlyNameByOid")] - internal static extern int LookupFriendlyNameByOid(string oidValue, ref IntPtr friendlyNamePtr); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs deleted file mode 100644 index 108b6a64e6..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs +++ /dev/null @@ -1,558 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Buffers; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Net.Http; -using System.Net.Security; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Security.Authentication; -using System.Security.Authentication.ExtendedProtection; -using System.Security.Cryptography; -using System.Security.Cryptography.X509Certificates; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class OpenSsl - { - private static readonly Ssl.SslCtxSetVerifyCallback s_verifyClientCertificate = VerifyClientCertificate; - private unsafe static readonly Ssl.SslCtxSetAlpnCallback s_alpnServerCallback = AlpnServerSelectCallback; - private static readonly IdnMapping s_idnMapping = new IdnMapping(); - - #region internal methods - internal static SafeChannelBindingHandle QueryChannelBinding(SafeSslHandle context, ChannelBindingKind bindingType) - { - Debug.Assert( - bindingType != ChannelBindingKind.Endpoint, - "Endpoint binding should be handled by EndpointChannelBindingToken"); - - SafeChannelBindingHandle bindingHandle; - switch (bindingType) - { - case ChannelBindingKind.Unique: - bindingHandle = new SafeChannelBindingHandle(bindingType); - QueryUniqueChannelBinding(context, bindingHandle); - break; - - default: - // Keeping parity with windows, we should return null in this case. - bindingHandle = null; - break; - } - - return bindingHandle; - } - - internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, SslAuthenticationOptions sslAuthenticationOptions) - { - SafeSslHandle context = null; - - // Always use SSLv23_method, regardless of protocols. It supports negotiating to the highest - // mutually supported version and can thus handle any of the set protocols, and we then use - // SetProtocolOptions to ensure we only allow the ones requested. - using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(Ssl.SslMethods.SSLv23_method)) - { - if (innerContext.IsInvalid) - { - throw CreateSslException(Strings.net_allocate_ssl_context_failed); - } - - // Configure allowed protocols. It's ok to use DangerousGetHandle here without AddRef/Release as we just - // create the handle, it's rooted by the using, no one else has a reference to it, etc. - Ssl.SetProtocolOptions(innerContext.DangerousGetHandle(), protocols); - - // The logic in SafeSslHandle.Disconnect is simple because we are doing a quiet - // shutdown (we aren't negotiating for session close to enable later session - // restoration). - // - // If you find yourself wanting to remove this line to enable bidirectional - // close-notify, you'll probably need to rewrite SafeSslHandle.Disconnect(). - // https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html - Ssl.SslCtxSetQuietShutdown(innerContext); - - if (!Ssl.SetEncryptionPolicy(innerContext, policy)) - { - Crypto.ErrClearError(); - throw new PlatformNotSupportedException(Strings.Format(Strings.net_ssl_encryptionpolicy_notsupported, policy)); - } - - bool hasCertificateAndKey = - certHandle != null && !certHandle.IsInvalid - && certKeyHandle != null && !certKeyHandle.IsInvalid; - - if (hasCertificateAndKey) - { - SetSslCertificate(innerContext, certHandle, certKeyHandle); - } - - if (sslAuthenticationOptions.IsServer && sslAuthenticationOptions.RemoteCertRequired) - { - Ssl.SslCtxSetVerify(innerContext, s_verifyClientCertificate); - } - - GCHandle alpnHandle = default; - try - { - if (sslAuthenticationOptions.ApplicationProtocols != null) - { - if (sslAuthenticationOptions.IsServer) - { - alpnHandle = GCHandle.Alloc(sslAuthenticationOptions.ApplicationProtocols); - Interop.Ssl.SslCtxSetAlpnSelectCb(innerContext, s_alpnServerCallback, GCHandle.ToIntPtr(alpnHandle)); - } - else - { - if (Interop.Ssl.SslCtxSetAlpnProtos(innerContext, sslAuthenticationOptions.ApplicationProtocols) != 0) - { - throw CreateSslException(Strings.net_alpn_config_failed); - } - } - } - - context = SafeSslHandle.Create(innerContext, sslAuthenticationOptions.IsServer); - Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create"); - if (context.IsInvalid) - { - context.Dispose(); - throw CreateSslException(Strings.net_allocate_ssl_context_failed); - } - - if (!sslAuthenticationOptions.IsServer) - { - // The IdnMapping converts unicode input into the IDNA punycode sequence. - string punyCode = s_idnMapping.GetAscii(sslAuthenticationOptions.TargetHost); - - // Similar to windows behavior, set SNI on openssl by default for client context, ignore errors. - if (!Ssl.SslSetTlsExtHostName(context, punyCode)) - { - Crypto.ErrClearError(); - } - } - - if (hasCertificateAndKey) - { - bool hasCertReference = false; - try - { - certHandle.DangerousAddRef(ref hasCertReference); - using (X509Certificate2 cert = new X509Certificate2(certHandle.DangerousGetHandle())) - { - using (X509Chain chain = TLSCertificateExtensions.BuildNewChain(cert, includeClientApplicationPolicy: false)) - { - if (chain != null && !Ssl.AddExtraChainCertificates(context, chain)) - throw CreateSslException(Strings.net_ssl_use_cert_failed); - } - } - } - finally - { - if (hasCertReference) - certHandle.DangerousRelease(); - } - } - - context.AlpnHandle = alpnHandle; - } - catch - { - if (alpnHandle.IsAllocated) - { - alpnHandle.Free(); - } - - throw; - } - } - - return context; - } - - internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount) - { - sendBuf = null; - sendCount = 0; - - if ((recvBuf != null) && (recvCount > 0)) - { - if (BioWrite(context.InputBio, recvBuf, recvOffset, recvCount) <= 0) - { - // Make sure we clear out the error that is stored in the queue - throw Crypto.CreateOpenSslCryptographicException(); - } - } - - int retVal = Ssl.SslDoHandshake(context); - if (retVal != 1) - { - Exception innerError; - Ssl.SslErrorCode error = GetSslError(context, retVal, out innerError); - - if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ)) - { - throw new SslException(Strings.Format(Strings.net_ssl_handshake_failed_error, error), innerError); - } - } - - sendCount = Crypto.BioCtrlPending(context.OutputBio); - if (sendCount > 0) - { - sendBuf = new byte[sendCount]; - - try - { - sendCount = BioRead(context.OutputBio, sendBuf, sendCount); - } - finally - { - if (sendCount <= 0) - { - // Make sure we clear out the error that is stored in the queue - Crypto.ErrClearError(); - sendBuf = null; - sendCount = 0; - } - } - } - - bool stateOk = Ssl.IsSslStateOK(context); - if (stateOk) - { - context.MarkHandshakeCompleted(); - } - return stateOk; - } - - internal static int Encrypt(SafeSslHandle context, ReadOnlyMemory input, ref byte[] output, out Ssl.SslErrorCode errorCode) - { -#if DEBUG - ulong assertNoError = Crypto.ErrPeekError(); - Debug.Assert(assertNoError == 0, "OpenSsl error queue is not empty, run: 'openssl errstr " + assertNoError.ToString("X") + "' for original error."); -#endif - errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE; - - int retVal; - unsafe - { - using (MemoryHandle handle = input.Pin()) - { - retVal = Ssl.SslWrite(context, (byte*)handle.Pointer, input.Length); - } - } - - if (retVal != input.Length) - { - errorCode = GetSslError(context, retVal, out Exception innerError); - retVal = 0; - - switch (errorCode) - { - // indicate end-of-file - case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN: - case Ssl.SslErrorCode.SSL_ERROR_WANT_READ: - break; - - default: - throw new SslException(Strings.Format(Strings.net_ssl_encrypt_failed, errorCode), innerError); - } - } - else - { - int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio); - - if (output == null || output.Length < capacityNeeded) - { - output = new byte[capacityNeeded]; - } - - retVal = BioRead(context.OutputBio, output, capacityNeeded); - if (retVal <= 0) - { - // Make sure we clear out the error that is stored in the queue - Crypto.ErrClearError(); - } - } - - return retVal; - } - - internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int offset, int count, out Ssl.SslErrorCode errorCode) - { -#if DEBUG - ulong assertNoError = Crypto.ErrPeekError(); - Debug.Assert(assertNoError == 0, "OpenSsl error queue is not empty, run: 'openssl errstr " + assertNoError.ToString("X") + "' for original error."); -#endif - errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE; - - int retVal = BioWrite(context.InputBio, outBuffer, offset, count); - - if (retVal == count) - { - unsafe - { - fixed (byte* fixedBuffer = outBuffer) - { - retVal = Ssl.SslRead(context, fixedBuffer + offset, outBuffer.Length); - } - } - - if (retVal > 0) - { - count = retVal; - } - } - - if (retVal != count) - { - Exception innerError; - errorCode = GetSslError(context, retVal, out innerError); - retVal = 0; - - switch (errorCode) - { - // indicate end-of-file - case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN: - break; - - case Ssl.SslErrorCode.SSL_ERROR_WANT_READ: - // update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ - errorCode = Ssl.IsSslRenegotiatePending(context) ? - Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE : - Ssl.SslErrorCode.SSL_ERROR_WANT_READ; - break; - - default: - throw new SslException(Strings.Format(Strings.net_ssl_decrypt_failed, errorCode), innerError); - } - } - - return retVal; - } - - internal static SafeX509Handle GetPeerCertificate(SafeSslHandle context) - { - return Ssl.SslGetPeerCertificate(context); - } - - internal static SafeSharedX509StackHandle GetPeerCertificateChain(SafeSslHandle context) - { - return Ssl.SslGetPeerCertChain(context); - } - - #endregion - - #region private methods - - private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle) - { - bool sessionReused = Ssl.SslSessionReused(context); - int certHashLength = context.IsServer ^ sessionReused ? - Ssl.SslGetPeerFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length) : - Ssl.SslGetFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length); - - if (0 == certHashLength) - { - throw CreateSslException(Strings.net_ssl_get_channel_binding_token_failed); - } - - bindingHandle.SetCertHashLength(certHashLength); - } - - private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr) - { - // Full validation is handled after the handshake in VerifyCertificateProperties and the - // user callback. It's also up to those handlers to decide if a null certificate - // is appropriate. So just return success to tell OpenSSL that the cert is acceptable, - // we'll process it after the handshake finishes. - const int OpenSslSuccess = 1; - return OpenSslSuccess; - } - - private static unsafe int AlpnServerSelectCallback(IntPtr ssl, out byte* outp, out byte outlen, byte* inp, uint inlen, IntPtr arg) - { - outp = null; - outlen = 0; - - GCHandle protocolHandle = GCHandle.FromIntPtr(arg); - if (!(protocolHandle.Target is List protocolList)) - { - return Ssl.SSL_TLSEXT_ERR_NOACK; - } - - try - { - for (int i = 0; i < protocolList.Count; i++) - { - Span clientList = new Span(inp, (int)inlen); - while (clientList.Length > 0) - { - byte length = clientList[0]; - Span clientProto = clientList.Slice(1, length); - if (clientProto.SequenceEqual(protocolList[i].Protocol.Span)) - { - fixed (byte* p = &MemoryMarshal.GetReference(clientProto)) outp = p; - outlen = length; - return Ssl.SSL_TLSEXT_ERR_OK; - } - - clientList = clientList.Slice(1 + length); - } - } - } - catch - { - // No common application protocol was negotiated, set the target on the alpnHandle to null. - // It is ok to clear the handle value here, this results in handshake failure, so the SslStream object is disposed. - protocolHandle.Target = null; - - return Ssl.SSL_TLSEXT_ERR_NOACK; - } - - // No common application protocol was negotiated, set the target on the alpnHandle to null. - // It is ok to clear the handle value here, this results in handshake failure, so the SslStream object is disposed. - protocolHandle.Target = null; - - return Ssl.SSL_TLSEXT_ERR_NOACK; - } - - private static int BioRead(SafeBioHandle bio, byte[] buffer, int count) - { - Debug.Assert(buffer != null); - Debug.Assert(count >= 0); - Debug.Assert(buffer.Length >= count); - - int bytes = Crypto.BioRead(bio, buffer, count); - if (bytes != count) - { - throw CreateSslException(Strings.net_ssl_read_bio_failed_error); - } - return bytes; - } - - private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int count) - { - Debug.Assert(buffer != null); - Debug.Assert(offset >= 0); - Debug.Assert(count >= 0); - Debug.Assert(buffer.Length >= offset + count); - - int bytes; - unsafe - { - fixed (byte* bufPtr = buffer) - { - bytes = Ssl.BioWrite(bio, bufPtr + offset, count); - } - } - - if (bytes != count) - { - throw CreateSslException(Strings.net_ssl_write_bio_failed_error); - } - return bytes; - } - - private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result, out Exception innerError) - { - ErrorInfo lastErrno = Sys.GetLastErrorInfo(); // cache it before we make more P/Invoke calls, just in case we need it - - Ssl.SslErrorCode retVal = Ssl.SslGetError(context, result); - switch (retVal) - { - case Ssl.SslErrorCode.SSL_ERROR_SYSCALL: - // Some I/O error occurred - innerError = - Crypto.ErrPeekError() != 0 ? Crypto.CreateOpenSslCryptographicException() : // crypto error queue not empty - result == 0 ? new EndOfStreamException() : // end of file that violates protocol - result == -1 && lastErrno.Error != Error.SUCCESS ? new IOException(lastErrno.GetErrorMessage(), lastErrno.RawErrno) : // underlying I/O error - null; // no additional info available - break; - - case Ssl.SslErrorCode.SSL_ERROR_SSL: - // OpenSSL failure occurred. The error queue contains more details, when building the exception the queue will be cleared. - innerError = Interop.Crypto.CreateOpenSslCryptographicException(); - break; - - default: - // No additional info available. - innerError = null; - break; - } - return retVal; - } - - private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr) - { - Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid"); - Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid"); - - int retVal = Ssl.SslCtxUseCertificate(contextPtr, certPtr); - - if (1 != retVal) - { - throw CreateSslException(Strings.net_ssl_use_cert_failed); - } - - retVal = Ssl.SslCtxUsePrivateKey(contextPtr, keyPtr); - - if (1 != retVal) - { - throw CreateSslException(Strings.net_ssl_use_private_key_failed); - } - - //check private key - retVal = Ssl.SslCtxCheckPrivateKey(contextPtr); - - if (1 != retVal) - { - throw CreateSslException(Strings.net_ssl_check_private_key_failed); - } - } - - internal static SslException CreateSslException(string message) - { - // Capture last error to be consistent with CreateOpenSslCryptographicException - ulong errorVal = Crypto.ErrPeekLastError(); - Crypto.ErrClearError(); - string msg = Strings.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal))); - return new SslException(msg, (int)errorVal); - } - - #endregion - - #region Internal class - - internal sealed class SslException : Exception - { - public SslException(string inputMessage) - : base(inputMessage) - { - } - - public SslException(string inputMessage, Exception ex) - : base(inputMessage, ex) - { - } - - public SslException(string inputMessage, int error) - : this(inputMessage) - { - HResult = error; - } - - public SslException(int error) - : this(Strings.Format(Strings.net_generic_operation_failed, error)) - { - HResult = error; - } - } - - #endregion - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSslVersion.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSslVersion.cs deleted file mode 100644 index b5c6960d94..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSslVersion.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class OpenSsl - { - private static Version s_opensslVersion; - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_OpenSslVersionNumber")] - private static extern uint OpenSslVersionNumber(); - - internal static Version OpenSslVersion - { - get - { - if (s_opensslVersion == null) - { - uint versionNumber = OpenSslVersionNumber(); - s_opensslVersion = new Version((int)(versionNumber >> 28), (int)((versionNumber >> 20) & 0xff), (int)((versionNumber >> 12) & 0xff)); - } - - return s_opensslVersion; - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Pkcs12.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Pkcs12.cs deleted file mode 100644 index 1be561006f..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Pkcs12.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodePkcs12")] - internal static extern unsafe SafePkcs12Handle DecodePkcs12(byte[] buf, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodePkcs12FromBio")] - internal static extern SafePkcs12Handle DecodePkcs12FromBio(SafeBioHandle bio); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Pkcs12Destroy")] - internal static extern void Pkcs12Destroy(IntPtr p12); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Pkcs12Create", CharSet = CharSet.Ansi)] - internal static extern SafePkcs12Handle Pkcs12Create( - SafePasswordHandle pass, - SafeEvpPKeyHandle pkey, - SafeX509Handle cert, - SafeX509StackHandle ca); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetPkcs12DerSize")] - internal static extern int GetPkcs12DerSize(SafePkcs12Handle p12); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EncodePkcs12")] - internal static extern int EncodePkcs12(SafePkcs12Handle p12, byte[] buf); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Pkcs12Parse")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool Pkcs12Parse( - SafePkcs12Handle p12, - SafePasswordHandle pass, - out SafeEvpPKeyHandle pkey, - out SafeX509Handle cert, - out SafeX509StackHandle ca); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Pkcs7.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Pkcs7.cs deleted file mode 100644 index d05ec4cadc..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Pkcs7.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PemReadBioPkcs7")] - internal static extern SafePkcs7Handle PemReadBioPkcs7(SafeBioHandle bp); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodePkcs7")] - internal static extern SafePkcs7Handle DecodePkcs7(byte[] buf, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_D2IPkcs7Bio")] - internal static extern SafePkcs7Handle D2IPkcs7Bio(SafeBioHandle bp); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Pkcs7CreateCertificateCollection")] - internal static extern SafePkcs7Handle Pkcs7CreateCertificateCollection(SafeX509StackHandle certs); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Pkcs7Destroy")] - internal static extern void Pkcs7Destroy(IntPtr p7); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetPkcs7Certificates")] - private static extern int GetPkcs7Certificates(SafePkcs7Handle p7, out SafeSharedX509StackHandle certs); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Pkcs7AddCertificate")] - internal static extern bool Pkcs7AddCertificate(SafePkcs7Handle p7, IntPtr x509); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetPkcs7DerSize")] - internal static extern int GetPkcs7DerSize(SafePkcs7Handle p7); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EncodePkcs7")] - internal static extern int EncodePkcs7(SafePkcs7Handle p7, byte[] buf); - - internal static SafeSharedX509StackHandle GetPkcs7Certificates(SafePkcs7Handle p7) - { - if (p7 == null || p7.IsInvalid) - { - return SafeSharedX509StackHandle.InvalidHandle; - } - - SafeSharedX509StackHandle certs; - int result = GetPkcs7Certificates(p7, out certs); - - if (result != 1) - { - throw Interop.Crypto.CreateOpenSslCryptographicException(); - } - - // Track the parent relationship for the interior pointer so lifetime is well-managed. - certs.SetParent(p7); - - return certs; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.RAND.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.RAND.cs deleted file mode 100644 index 2643abe6f6..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.RAND.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Crypto - { - internal unsafe static bool GetRandomBytes(byte* pbBuffer, int count) - { - Debug.Assert(count >= 0); - - return CryptoNative_GetRandomBytes(pbBuffer, count); - } - - [DllImport(Libraries.CryptoNative)] - [return: MarshalAs(UnmanagedType.Bool)] - private unsafe static extern bool CryptoNative_GetRandomBytes(byte* buf, int num); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Rsa.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Rsa.cs deleted file mode 100644 index 296b9f18b5..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Rsa.cs +++ /dev/null @@ -1,217 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaCreate")] - internal static extern SafeRsaHandle RsaCreate(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaUpRef")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool RsaUpRef(IntPtr rsa); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaDestroy")] - internal static extern void RsaDestroy(IntPtr rsa); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeRsaPublicKey")] - internal static extern SafeRsaHandle DecodeRsaPublicKey(byte[] buf, int len); - - internal static int RsaPublicEncrypt( - int flen, - ReadOnlySpan from, - Span to, - SafeRsaHandle rsa, - RsaPadding padding) => - RsaPublicEncrypt(flen, ref MemoryMarshal.GetReference(from), ref MemoryMarshal.GetReference(to), rsa, padding); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaPublicEncrypt")] - private extern static int RsaPublicEncrypt( - int flen, - ref byte from, - ref byte to, - SafeRsaHandle rsa, - RsaPadding padding); - - internal static int RsaPrivateDecrypt( - int flen, - ReadOnlySpan from, - Span to, - SafeRsaHandle rsa, - RsaPadding padding) => - RsaPrivateDecrypt(flen, ref MemoryMarshal.GetReference(from), ref MemoryMarshal.GetReference(to), rsa, padding); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaPrivateDecrypt")] - private extern static int RsaPrivateDecrypt( - int flen, - ref byte from, - ref byte to, - SafeRsaHandle rsa, - RsaPadding padding); - - internal static int RsaSignPrimitive( - ReadOnlySpan from, - Span to, - SafeRsaHandle rsa) => - RsaSignPrimitive(from.Length, ref MemoryMarshal.GetReference(from), ref MemoryMarshal.GetReference(to), rsa); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaSignPrimitive")] - private static extern int RsaSignPrimitive( - int flen, - ref byte from, - ref byte to, - SafeRsaHandle rsa); - - internal static int RsaVerificationPrimitive( - ReadOnlySpan from, - Span to, - SafeRsaHandle rsa) => - RsaVerificationPrimitive(from.Length, ref MemoryMarshal.GetReference(from), ref MemoryMarshal.GetReference(to), rsa); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaVerificationPrimitive")] - private static extern int RsaVerificationPrimitive( - int flen, - ref byte from, - ref byte to, - SafeRsaHandle rsa); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaSize")] - internal static extern int RsaSize(SafeRsaHandle rsa); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaGenerateKeyEx")] - internal static extern int RsaGenerateKeyEx(SafeRsaHandle rsa, int bits, SafeBignumHandle e); - - internal static bool RsaSign(int type, ReadOnlySpan m, int m_len, Span sigret, out int siglen, SafeRsaHandle rsa) => - RsaSign(type, ref MemoryMarshal.GetReference(m), m_len, ref MemoryMarshal.GetReference(sigret), out siglen, rsa); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaSign")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool RsaSign(int type, ref byte m, int m_len, ref byte sigret, out int siglen, SafeRsaHandle rsa); - - internal static bool RsaVerify(int type, ReadOnlySpan m, ReadOnlySpan sigbuf, SafeRsaHandle rsa) - { - bool ret = RsaVerify( - type, - ref MemoryMarshal.GetReference(m), - m.Length, - ref MemoryMarshal.GetReference(sigbuf), - sigbuf.Length, - rsa); - - if (!ret) - { - ErrClearError(); - } - - return ret; - } - - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaVerify")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool RsaVerify(int type, ref byte m, int m_len, ref byte sigbuf, int siglen, SafeRsaHandle rsa); - - internal static RSAParameters ExportRsaParameters(SafeRsaHandle key, bool includePrivateParameters) - { - Debug.Assert( - key != null && !key.IsInvalid, - "Callers should check the key is invalid and throw an exception with a message"); - - if (key == null || key.IsInvalid) - { - throw new CryptographicException(); - } - - bool addedRef = false; - - try - { - key.DangerousAddRef(ref addedRef); - - IntPtr n, e, d, p, dmp1, q, dmq1, iqmp; - if (!GetRsaParameters(key, out n, out e, out d, out p, out dmp1, out q, out dmq1, out iqmp)) - { - throw new CryptographicException(); - } - - int modulusSize = Crypto.RsaSize(key); - - // RSACryptoServiceProvider expects P, DP, Q, DQ, and InverseQ to all - // be padded up to half the modulus size. - int halfModulus = modulusSize / 2; - - RSAParameters rsaParameters = new RSAParameters - { - Modulus = Crypto.ExtractBignum(n, modulusSize), - Exponent = Crypto.ExtractBignum(e, 0), - }; - - if (includePrivateParameters) - { - rsaParameters.D = Crypto.ExtractBignum(d, modulusSize); - rsaParameters.P = Crypto.ExtractBignum(p, halfModulus); - rsaParameters.DP = Crypto.ExtractBignum(dmp1, halfModulus); - rsaParameters.Q = Crypto.ExtractBignum(q, halfModulus); - rsaParameters.DQ = Crypto.ExtractBignum(dmq1, halfModulus); - rsaParameters.InverseQ = Crypto.ExtractBignum(iqmp, halfModulus); - } - - return rsaParameters; - } - finally - { - if (addedRef) - key.DangerousRelease(); - } - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetRsaParameters")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool GetRsaParameters( - SafeRsaHandle key, - out IntPtr n, - out IntPtr e, - out IntPtr d, - out IntPtr p, - out IntPtr dmp1, - out IntPtr q, - out IntPtr dmq1, - out IntPtr iqmp); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SetRsaParameters")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool SetRsaParameters( - SafeRsaHandle key, - byte[] n, - int nLength, - byte[] e, - int eLength, - byte[] d, - int dLength, - byte[] p, - int pLength, - byte[] dmp1, - int dmp1Length, - byte[] q, - int qLength, - byte[] dmq1, - int dmq1Length, - byte[] iqmp, - int iqmpLength); - - internal enum RsaPadding : int - { - Pkcs1 = 0, - OaepSHA1 = 1, - NoPadding = 2, - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SetProtocolOptions.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SetProtocolOptions.cs deleted file mode 100644 index 25cf9cb8f3..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SetProtocolOptions.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Win32.SafeHandles; -using System; -using System.Runtime.InteropServices; -using System.Security.Authentication; - -internal static partial class Interop -{ - internal static partial class Ssl - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SetProtocolOptions")] - internal static extern void SetProtocolOptions(IntPtr ctx, SslProtocols protocols); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs deleted file mode 100644 index 8e9db6fb66..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs +++ /dev/null @@ -1,341 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Cryptography.X509Certificates; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Ssl - { - internal const int SSL_TLSEXT_ERR_OK = 0; - internal const int OPENSSL_NPN_NEGOTIATED = 1; - internal const int SSL_TLSEXT_ERR_NOACK = 3; - - internal delegate int SslCtxSetVerifyCallback(int preverify_ok, IntPtr x509_ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EnsureLibSslInitialized")] - internal static extern void EnsureLibSslInitialized(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV2_3Method")] - internal static extern IntPtr SslV2_3Method(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCreate")] - internal static extern SafeSslHandle SslCreate(SafeSslContextHandle ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")] - internal static extern SslErrorCode SslGetError(SafeSslHandle ssl, int ret); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")] - internal static extern SslErrorCode SslGetError(IntPtr ssl, int ret); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetQuietShutdown")] - internal static extern void SslSetQuietShutdown(SafeSslHandle ssl, int mode); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDestroy")] - internal static extern void SslDestroy(IntPtr ssl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetConnectState")] - internal static extern void SslSetConnectState(SafeSslHandle ssl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetAcceptState")] - internal static extern void SslSetAcceptState(SafeSslHandle ssl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetVersion")] - private static extern IntPtr SslGetVersion(SafeSslHandle ssl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetTlsExtHostName")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool SslSetTlsExtHostName(SafeSslHandle ssl, string host); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGet0AlpnSelected")] - internal static extern void SslGetAlpnSelected(SafeSslHandle ssl, out IntPtr protocol, out int len); - - internal static byte[] SslGetAlpnSelected(SafeSslHandle ssl) - { - IntPtr protocol; - int len; - SslGetAlpnSelected(ssl, out protocol, out len); - - if (len == 0) - return null; - - byte[] result = new byte[len]; - Marshal.Copy(protocol, result, 0, len); - return result; - } - - internal static string GetProtocolVersion(SafeSslHandle ssl) - { - return Marshal.PtrToStringAnsi(SslGetVersion(ssl)); - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetSslConnectionInfo")] - internal static extern bool GetSslConnectionInfo( - SafeSslHandle ssl, - out int dataCipherAlg, - out int keyExchangeAlg, - out int dataHashAlg, - out int dataKeySize, - out int hashKeySize); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslWrite")] - internal static extern unsafe int SslWrite(SafeSslHandle ssl, byte* buf, int num); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRead")] - internal static extern unsafe int SslRead(SafeSslHandle ssl, byte* buf, int num); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslRenegotiatePending")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool IsSslRenegotiatePending(SafeSslHandle ssl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")] - internal static extern int SslShutdown(IntPtr ssl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")] - internal static extern int SslShutdown(SafeSslHandle ssl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetBio")] - internal static extern void SslSetBio(SafeSslHandle ssl, SafeBioHandle rbio, SafeBioHandle wbio); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDoHandshake")] - internal static extern int SslDoHandshake(SafeSslHandle ssl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslStateOK")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool IsSslStateOK(SafeSslHandle ssl); - - // NOTE: this is just an (unsafe) overload to the BioWrite method from Interop.Bio.cs. - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")] - internal static extern unsafe int BioWrite(SafeBioHandle b, byte* data, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertificate")] - internal static extern SafeX509Handle SslGetPeerCertificate(SafeSslHandle ssl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertChain")] - internal static extern SafeSharedX509StackHandle SslGetPeerCertChain(SafeSslHandle ssl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerFinished")] - internal static extern int SslGetPeerFinished(SafeSslHandle ssl, IntPtr buf, int count); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetFinished")] - internal static extern int SslGetFinished(SafeSslHandle ssl, IntPtr buf, int count); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSessionReused")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool SslSessionReused(SafeSslHandle ssl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslAddExtraChainCert")] - internal static extern bool SslAddExtraChainCert(SafeSslHandle ssl, SafeX509Handle x509); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetClientCAList")] - private static extern SafeSharedX509NameStackHandle SslGetClientCAList_private(SafeSslHandle ssl); - - internal static SafeSharedX509NameStackHandle SslGetClientCAList(SafeSslHandle ssl) - { - Crypto.CheckValidOpenSslHandle(ssl); - - SafeSharedX509NameStackHandle handle = SslGetClientCAList_private(ssl); - - if (!handle.IsInvalid) - { - handle.SetParent(ssl); - } - - return handle; - } - - internal static bool AddExtraChainCertificates(SafeSslHandle sslContext, X509Chain chain) - { - Debug.Assert(chain != null, "X509Chain should not be null"); - Debug.Assert(chain.ChainElements.Count > 0, "chain.Build should have already been called"); - - for (int i = chain.ChainElements.Count - 2; i > 0; i--) - { - SafeX509Handle dupCertHandle = Crypto.X509UpRef(chain.ChainElements[i].Certificate.Handle); - Crypto.CheckValidOpenSslHandle(dupCertHandle); - if (!SslAddExtraChainCert(sslContext, dupCertHandle)) - { - Crypto.ErrClearError(); - dupCertHandle.Dispose(); // we still own the safe handle; clean it up - return false; - } - dupCertHandle.SetHandleAsInvalid(); // ownership has been transferred to sslHandle; do not free via this safe handle - } - - return true; - } - - internal static class SslMethods - { - internal static readonly IntPtr SSLv23_method = SslV2_3Method(); - } - - internal enum SslErrorCode - { - SSL_ERROR_NONE = 0, - SSL_ERROR_SSL = 1, - SSL_ERROR_WANT_READ = 2, - SSL_ERROR_WANT_WRITE = 3, - SSL_ERROR_SYSCALL = 5, - SSL_ERROR_ZERO_RETURN = 6, - - // NOTE: this SslErrorCode value doesn't exist in OpenSSL, but - // we use it to distinguish when a renegotiation is pending. - // Choosing an arbitrarily large value that shouldn't conflict - // with any actual OpenSSL error codes - SSL_ERROR_RENEGOTIATE = 29304 - } - } -} - -namespace Microsoft.Win32.SafeHandles -{ - internal sealed class SafeSslHandle : SafeHandle - { - private SafeBioHandle _readBio; - private SafeBioHandle _writeBio; - private bool _isServer; - private bool _handshakeCompleted = false; - - public GCHandle AlpnHandle; - - public bool IsServer - { - get { return _isServer; } - } - - public SafeBioHandle InputBio - { - get - { - return _readBio; - } - } - - public SafeBioHandle OutputBio - { - get - { - return _writeBio; - } - } - - internal void MarkHandshakeCompleted() - { - _handshakeCompleted = true; - } - - public static SafeSslHandle Create(SafeSslContextHandle context, bool isServer) - { - SafeBioHandle readBio = Interop.Crypto.CreateMemoryBio(); - SafeBioHandle writeBio = Interop.Crypto.CreateMemoryBio(); - SafeSslHandle handle = Interop.Ssl.SslCreate(context); - if (readBio.IsInvalid || writeBio.IsInvalid || handle.IsInvalid) - { - readBio.Dispose(); - writeBio.Dispose(); - handle.Dispose(); // will make IsInvalid==true if it's not already - return handle; - } - handle._isServer = isServer; - - // SslSetBio will transfer ownership of the BIO handles to the SSL context - try - { - readBio.TransferOwnershipToParent(handle); - writeBio.TransferOwnershipToParent(handle); - handle._readBio = readBio; - handle._writeBio = writeBio; - Interop.Ssl.SslSetBio(handle, readBio, writeBio); - } - catch (Exception exc) - { - // The only way this should be able to happen without thread aborts is if we hit OOMs while - // manipulating the safe handles, in which case we may leak the bio handles. - Debug.Fail("Unexpected exception while transferring SafeBioHandle ownership to SafeSslHandle", exc.ToString()); - throw; - } - - if (isServer) - { - Interop.Ssl.SslSetAcceptState(handle); - } - else - { - Interop.Ssl.SslSetConnectState(handle); - } - return handle; - } - - public override bool IsInvalid - { - get { return handle == IntPtr.Zero; } - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - _readBio?.Dispose(); - _writeBio?.Dispose(); - } - - if (AlpnHandle.IsAllocated) - { - AlpnHandle.Free(); - } - - base.Dispose(disposing); - } - - protected override bool ReleaseHandle() - { - if (_handshakeCompleted) - { - Disconnect(); - } - - IntPtr h = handle; - SetHandle(IntPtr.Zero); - Interop.Ssl.SslDestroy(h); // will free the handles underlying _readBio and _writeBio - - return true; - } - - private void Disconnect() - { - Debug.Assert(!IsInvalid, "Expected a valid context in Disconnect"); - - int retVal = Interop.Ssl.SslShutdown(handle); - - // Here, we are ignoring checking for <0 return values from Ssl_Shutdown, - // since the underlying memory bio is already disposed, we are not - // interested in reading or writing to it. - if (retVal == 0) - { - // Do a bi-directional shutdown. - retVal = Interop.Ssl.SslShutdown(handle); - } - - if (retVal < 0) - { - // Clean up the errors - Interop.Crypto.ErrClearError(); - } - } - - private SafeSslHandle() : base(IntPtr.Zero, true) - { - } - - internal SafeSslHandle(IntPtr validSslPointer, bool ownsHandle) : base(IntPtr.Zero, ownsHandle) - { - handle = validSslPointer; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs deleted file mode 100644 index e796f7c661..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Net.Security; -using System.Runtime.InteropServices; -using System.Text; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Ssl - { - internal delegate int AppVerifyCallback(IntPtr storeCtx, IntPtr arg); - internal delegate int ClientCertCallback(IntPtr ssl, out IntPtr x509, out IntPtr pkey); - internal unsafe delegate int SslCtxSetAlpnCallback(IntPtr ssl, out byte* outp, out byte outlen, byte* inp, uint inlen, IntPtr arg); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCtxCreate")] - internal static extern SafeSslContextHandle SslCtxCreate(IntPtr method); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCtxDestroy")] - internal static extern void SslCtxDestroy(IntPtr ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCtxSetCertVerifyCallback")] - internal static extern void SslCtxSetCertVerifyCallback(IntPtr ctx, AppVerifyCallback cb, IntPtr arg); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCtxSetClientCertCallback")] - internal static extern void SslCtxSetClientCertCallback(IntPtr ctx, ClientCertCallback callback); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCtxSetAlpnProtos")] - internal static extern int SslCtxSetAlpnProtos(SafeSslContextHandle ctx, IntPtr protos, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCtxSetAlpnSelectCb")] - internal static unsafe extern void SslCtxSetAlpnSelectCb(SafeSslContextHandle ctx, SslCtxSetAlpnCallback callback, IntPtr arg); - - internal static unsafe int SslCtxSetAlpnProtos(SafeSslContextHandle ctx, List protocols) - { - byte[] buffer = ConvertAlpnProtocolListToByteArray(protocols); - fixed (byte* b = buffer) - { - return SslCtxSetAlpnProtos(ctx, (IntPtr)b, buffer.Length); - } - } - - internal static byte[] ConvertAlpnProtocolListToByteArray(List applicationProtocols) - { - int protocolSize = 0; - foreach (SslApplicationProtocol protocol in applicationProtocols) - { - if (protocol.Protocol.Length == 0 || protocol.Protocol.Length > byte.MaxValue) - { - throw new ArgumentException(Strings.net_ssl_app_protocols_invalid, nameof(applicationProtocols)); - } - - protocolSize += protocol.Protocol.Length + 1; - } - - byte[] buffer = new byte[protocolSize]; - var offset = 0; - foreach (SslApplicationProtocol protocol in applicationProtocols) - { - buffer[offset++] = (byte)(protocol.Protocol.Length); - protocol.Protocol.Span.CopyTo(new Span(buffer).Slice(offset)); - offset += protocol.Protocol.Length; - } - - return buffer; - } - } -} - -namespace Microsoft.Win32.SafeHandles -{ - internal sealed class SafeSslContextHandle : SafeHandle - { - private SafeSslContextHandle() - : base(IntPtr.Zero, true) - { - } - - internal SafeSslContextHandle(IntPtr handle, bool ownsHandle) - : base(handle, ownsHandle) - { - } - - public override bool IsInvalid - { - get { return handle == IntPtr.Zero; } - } - - protected override bool ReleaseHandle() - { - Interop.Ssl.SslCtxDestroy(handle); - SetHandle(IntPtr.Zero); - return true; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtxOptions.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtxOptions.cs deleted file mode 100644 index 4c4721f412..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtxOptions.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Net.Security; -using System.Runtime.InteropServices; -using System.Security.Authentication; -using System.Security.Authentication.ExtendedProtection; -using System.Security.Cryptography; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Ssl - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCtxUseCertificate")] - internal static extern int SslCtxUseCertificate(SafeSslContextHandle ctx, SafeX509Handle certPtr); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCtxUsePrivateKey")] - internal static extern int SslCtxUsePrivateKey(SafeSslContextHandle ctx, SafeEvpPKeyHandle keyPtr); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCtxCheckPrivateKey")] - internal static extern int SslCtxCheckPrivateKey(SafeSslContextHandle ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCtxSetQuietShutdown")] - internal static extern void SslCtxSetQuietShutdown(SafeSslContextHandle ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCtxSetVerify")] - internal static extern void SslCtxSetVerify(SafeSslContextHandle ctx, SslCtxSetVerifyCallback callback); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SetEncryptionPolicy")] - internal static extern bool SetEncryptionPolicy(SafeSslContextHandle ctx, EncryptionPolicy policy); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509.cs deleted file mode 100644 index c7f88e63d5..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509.cs +++ /dev/null @@ -1,214 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Security.Cryptography.X509Certificates; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - internal delegate int X509StoreVerifyCallback(int ok, IntPtr ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509EvpPublicKey")] - internal static extern SafeEvpPKeyHandle GetX509EvpPublicKey(SafeX509Handle x509); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeX509Crl")] - internal static extern SafeX509CrlHandle DecodeX509Crl(byte[] buf, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeX509")] - internal static extern SafeX509Handle DecodeX509(byte[] buf, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509DerSize")] - internal static extern int GetX509DerSize(SafeX509Handle x); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EncodeX509")] - internal static extern int EncodeX509(SafeX509Handle x, byte[] buf); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509Destroy")] - internal static extern void X509Destroy(IntPtr a); - - /// - /// Clone the input certificate into a new object. - /// - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509Duplicate")] - internal static extern SafeX509Handle X509Duplicate(IntPtr handle); - - /// - /// Clone the input certificate into a new object. - /// - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509Duplicate")] - internal static extern SafeX509Handle X509Duplicate(SafeX509Handle handle); - - /// - /// Increment the native reference count of the certificate to protect against - /// a free from another pointer-holder. - /// - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509UpRef")] - internal static extern SafeX509Handle X509UpRef(IntPtr handle); - - /// - /// Increment the native reference count of the certificate to protect against - /// a free from another pointer-holder. - /// - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509UpRef")] - internal static extern SafeX509Handle X509UpRef(SafeX509Handle handle); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PemReadX509FromBio")] - internal static extern SafeX509Handle PemReadX509FromBio(SafeBioHandle bio); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetSerialNumber")] - private static extern SafeSharedAsn1IntegerHandle X509GetSerialNumber_private(SafeX509Handle x); - - internal static SafeSharedAsn1IntegerHandle X509GetSerialNumber(SafeX509Handle x) - { - CheckValidOpenSslHandle(x); - - return SafeInteriorHandle.OpenInteriorHandle( - handle => X509GetSerialNumber_private(handle), - x); - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetIssuerName")] - internal static extern IntPtr X509GetIssuerName(SafeX509Handle x); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetSubjectName")] - internal static extern IntPtr X509GetSubjectName(SafeX509Handle x); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509CheckPurpose")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool X509CheckPurpose(SafeX509Handle x, int id, int ca); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509CheckIssued")] - internal static extern int X509CheckIssued(SafeX509Handle issuer, SafeX509Handle subject); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509IssuerNameHash")] - internal static extern ulong X509IssuerNameHash(SafeX509Handle x); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetExtCount")] - internal static extern int X509GetExtCount(SafeX509Handle x); - - // Returns a pointer already being tracked by the SafeX509Handle, shouldn't be SafeHandle tracked/freed. - // Bounds checking is in place for "loc", IntPtr.Zero is returned on violations. - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetExt")] - internal static extern IntPtr X509GetExt(SafeX509Handle x, int loc); - - // Returns a pointer already being tracked by a SafeX509Handle, shouldn't be SafeHandle tracked/freed. - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509ExtensionGetOid")] - internal static extern IntPtr X509ExtensionGetOid(IntPtr ex); - - // Returns a pointer already being tracked by a SafeX509Handle, shouldn't be SafeHandle tracked/freed. - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509ExtensionGetData")] - internal static extern IntPtr X509ExtensionGetData(IntPtr ex); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509ExtensionGetCritical")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool X509ExtensionGetCritical(IntPtr ex); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCreate")] - internal static extern SafeX509StoreHandle X509StoreCreate(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreDestory")] - internal static extern void X509StoreDestory(IntPtr v); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreAddCert")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool X509StoreAddCert(SafeX509StoreHandle ctx, SafeX509Handle x); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreAddCrl")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool X509StoreAddCrl(SafeX509StoreHandle ctx, SafeX509CrlHandle x); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreSetRevocationFlag")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool X509StoreSetRevocationFlag(SafeX509StoreHandle ctx, X509RevocationFlag revocationFlag); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxInit")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool X509StoreCtxInit( - SafeX509StoreCtxHandle ctx, - SafeX509StoreHandle store, - SafeX509Handle x509, - SafeX509StackHandle extraCerts); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509VerifyCert")] - internal static extern int X509VerifyCert(SafeX509StoreCtxHandle ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxGetError")] - internal static extern X509VerifyStatusCode X509StoreCtxGetError(SafeX509StoreCtxHandle ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxGetErrorDepth")] - internal static extern int X509StoreCtxGetErrorDepth(SafeX509StoreCtxHandle ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxSetVerifyCallback")] - internal static extern void X509StoreCtxSetVerifyCallback(SafeX509StoreCtxHandle ctx, X509StoreVerifyCallback callback); - - internal static string GetX509VerifyCertErrorString(X509VerifyStatusCode n) - { - return Marshal.PtrToStringAnsi(X509VerifyCertErrorString(n)); - } - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509VerifyCertErrorString")] - private static extern IntPtr X509VerifyCertErrorString(X509VerifyStatusCode n); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509CrlDestroy")] - internal static extern void X509CrlDestroy(IntPtr a); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PemWriteBioX509Crl")] - internal static extern int PemWriteBioX509Crl(SafeBioHandle bio, SafeX509CrlHandle crl); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PemReadBioX509Crl")] - internal static extern SafeX509CrlHandle PemReadBioX509Crl(SafeBioHandle bio); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509SubjectPublicKeyInfoDerSize")] - internal static extern int GetX509SubjectPublicKeyInfoDerSize(SafeX509Handle x509); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EncodeX509SubjectPublicKeyInfo")] - internal static extern int EncodeX509SubjectPublicKeyInfo(SafeX509Handle x509, byte[] buf); - - internal enum X509VerifyStatusCode : int - { - X509_V_OK = 0, - X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 2, - X509_V_ERR_UNABLE_TO_GET_CRL = 3, - X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5, - X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6, - X509_V_ERR_CERT_SIGNATURE_FAILURE = 7, - X509_V_ERR_CRL_SIGNATURE_FAILURE = 8, - X509_V_ERR_CERT_NOT_YET_VALID = 9, - X509_V_ERR_CERT_HAS_EXPIRED = 10, - X509_V_ERR_CRL_NOT_YET_VALID = 11, - X509_V_ERR_CRL_HAS_EXPIRED = 12, - X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = 13, - X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = 14, - X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD = 15, - X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD = 16, - X509_V_ERR_OUT_OF_MEM = 17, - X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 18, - X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN = 19, - X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20, - X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21, - X509_V_ERR_CERT_CHAIN_TOO_LONG = 22, - X509_V_ERR_CERT_REVOKED = 23, - X509_V_ERR_INVALID_CA = 24, - X509_V_ERR_PATH_LENGTH_EXCEEDED = 25, - X509_V_ERR_INVALID_PURPOSE = 26, - X509_V_ERR_CERT_UNTRUSTED = 27, - X509_V_ERR_CERT_REJECTED = 28, - X509_V_ERR_KEYUSAGE_NO_CERTSIGN = 32, - X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER = 33, - X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION = 34, - X509_V_ERR_KEYUSAGE_NO_CRL_SIGN = 35, - X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION = 36, - X509_V_ERR_INVALID_NON_CA = 37, - X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = 39, - X509_V_ERR_INVALID_EXTENSION = 41, - X509_V_ERR_INVALID_POLICY_EXTENSION = 42, - X509_V_ERR_NO_EXPLICIT_POLICY = 43, - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509Ext.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509Ext.cs deleted file mode 100644 index c57d75d99d..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509Ext.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509ExtensionCreateByObj")] - internal static extern SafeX509ExtensionHandle X509ExtensionCreateByObj( - SafeAsn1ObjectHandle oid, - [MarshalAs(UnmanagedType.Bool)] bool isCritical, - SafeAsn1OctetStringHandle data); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509ExtensionDestroy")] - internal static extern int X509ExtensionDestroy(IntPtr x); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509V3ExtPrint")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool X509V3ExtPrint(SafeBioHandle buf, SafeX509ExtensionHandle ext); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeX509BasicConstraints2Extension")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DecodeX509BasicConstraints2Extension( - byte[] encoded, - int encodedLength, - [MarshalAs(UnmanagedType.Bool)] out bool certificateAuthority, - [MarshalAs(UnmanagedType.Bool)] out bool hasPathLengthConstraint, - out int pathLengthConstraint); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeExtendedKeyUsage")] - internal static extern SafeEkuExtensionHandle DecodeExtendedKeyUsage(byte[] buf, int len); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ExtendedKeyUsageDestory")] - internal static extern void ExtendedKeyUsageDestory(IntPtr a); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509Name.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509Name.cs deleted file mode 100644 index 70097d7db2..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509Name.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Security; -using System.Security.Cryptography.X509Certificates; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509NameStackFieldCount")] - internal static extern int GetX509NameStackFieldCount(SafeSharedX509NameStackHandle sk); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509NameStackField")] - private static extern SafeSharedX509NameHandle GetX509NameStackField_private(SafeSharedX509NameStackHandle sk, - int loc); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509NameRawBytes")] - private static extern int GetX509NameRawBytes(SafeSharedX509NameHandle x509Name, byte[] buf, int cBuf); - - internal static X500DistinguishedName LoadX500Name(SafeSharedX509NameHandle namePtr) - { - CheckValidOpenSslHandle(namePtr); - - byte[] buf = GetDynamicBuffer((ptr, buf1, i) => GetX509NameRawBytes(ptr, buf1, i), namePtr); - return new X500DistinguishedName(buf); - } - - internal static SafeSharedX509NameHandle GetX509NameStackField(SafeSharedX509NameStackHandle sk, int loc) - { - CheckValidOpenSslHandle(sk); - - return SafeInteriorHandle.OpenInteriorHandle( - (handle, i) => GetX509NameStackField_private(handle, i), - sk, - loc); - } - } -} - -namespace Microsoft.Win32.SafeHandles -{ - /// - /// Represents access to a X509_NAME* which is a member of a structure tracked - /// by another SafeHandle. - /// - internal sealed class SafeSharedX509NameHandle : SafeInteriorHandle - { - private SafeSharedX509NameHandle() : - base(IntPtr.Zero, ownsHandle: true) - { - } - } - - /// - /// Represents access to a STACK_OF(X509_NAME)* which is a member of a structure tracked - /// by another SafeHandle. - /// - internal sealed class SafeSharedX509NameStackHandle : SafeInteriorHandle - { - private SafeSharedX509NameStackHandle() : - base(IntPtr.Zero, ownsHandle: true) - { - } - } -} - diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509Stack.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509Stack.cs deleted file mode 100644 index 7853e8e638..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509Stack.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_NewX509Stack")] - internal static extern SafeX509StackHandle NewX509Stack(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RecursiveFreeX509Stack")] - internal static extern void RecursiveFreeX509Stack(IntPtr stack); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509StackFieldCount")] - internal static extern int GetX509StackFieldCount(SafeX509StackHandle stack); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509StackFieldCount")] - internal static extern int GetX509StackFieldCount(SafeSharedX509StackHandle stack); - - /// - /// Gets a pointer to a certificate within a STACK_OF(X509). This pointer will later - /// be freed, so it should be cloned via new X509Certificate2(IntPtr) - /// - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509StackField")] - internal static extern IntPtr GetX509StackField(SafeX509StackHandle stack, int loc); - - /// - /// Gets a pointer to a certificate within a STACK_OF(X509). This pointer will later - /// be freed, so it should be cloned via new X509Certificate2(IntPtr) - /// - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509StackField")] - internal static extern IntPtr GetX509StackField(SafeSharedX509StackHandle stack, int loc); - } -} - -namespace Microsoft.Win32.SafeHandles -{ - internal sealed class SafeX509StackHandle : SafeHandle - { - private SafeX509StackHandle() : - base(IntPtr.Zero, ownsHandle: true) - { - } - - protected override bool ReleaseHandle() - { - Interop.Crypto.RecursiveFreeX509Stack(handle); - SetHandle(IntPtr.Zero); - return true; - } - - public override bool IsInvalid - { - get { return handle == IntPtr.Zero; } - } - } - - /// - /// Represents access to a STACK_OF(X509)* which is a member of a structure tracked - /// by another SafeHandle. - /// - internal sealed class SafeSharedX509StackHandle : SafeInteriorHandle - { - internal static readonly SafeSharedX509StackHandle InvalidHandle = new SafeSharedX509StackHandle(); - - private SafeSharedX509StackHandle() : - base(IntPtr.Zero, ownsHandle: true) - { - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509StoreCtx.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509StoreCtx.cs deleted file mode 100644 index 0da65d10ce..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509StoreCtx.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Crypto - { - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxCreate")] - internal static extern SafeX509StoreCtxHandle X509StoreCtxCreate(); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxDestroy")] - internal static extern void X509StoreCtxDestroy(IntPtr v); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxGetChain")] - internal static extern SafeX509StackHandle X509StoreCtxGetChain(SafeX509StoreCtxHandle ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxGetSharedUntrusted")] - private static extern SafeSharedX509StackHandle X509StoreCtxGetSharedUntrusted_private(SafeX509StoreCtxHandle ctx); - - [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxGetTargetCert")] - internal static extern IntPtr X509StoreCtxGetTargetCert(SafeX509StoreCtxHandle ctx); - - internal static SafeSharedX509StackHandle X509StoreCtxGetSharedUntrusted(SafeX509StoreCtxHandle ctx) - { - return SafeInteriorHandle.OpenInteriorHandle( - x => X509StoreCtxGetSharedUntrusted_private(x), - ctx); - } - } -} - -namespace Microsoft.Win32.SafeHandles -{ - internal sealed class SafeX509StoreCtxHandle : SafeHandle - { - private SafeX509StoreCtxHandle() : - base(IntPtr.Zero, ownsHandle: true) - { - } - - internal SafeX509StoreCtxHandle(IntPtr handle, bool ownsHandle) : - base(handle, ownsHandle) - { - } - - protected override bool ReleaseHandle() - { - Interop.Crypto.X509StoreCtxDestroy(handle); - SetHandle(IntPtr.Zero); - return true; - } - - public override bool IsInvalid - { - get { return handle == IntPtr.Zero; } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/libdl/Interop.dlopen.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/libdl/Interop.dlopen.cs deleted file mode 100644 index 4a4c31f035..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/libdl/Interop.dlopen.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal partial class Interop -{ - internal partial class Libdl - { - public const int RTLD_NOW = 0x002; - - [DllImport(Libraries.Libdl)] - public static extern IntPtr dlopen(string fileName, int flag); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/libdl/Interop.dlsym.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/libdl/Interop.dlsym.cs deleted file mode 100644 index 2ea7a98e98..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/libdl/Interop.dlsym.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; - -internal partial class Interop -{ - internal partial class Libdl - { - [DllImport(Libraries.Libdl)] - public static extern IntPtr dlsym(IntPtr handle, string symbol); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/Interop.Errors.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/Interop.Errors.cs index 7836b049eb..2e0c3553f2 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/Interop.Errors.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/Interop.Errors.cs @@ -7,80 +7,9 @@ internal partial class Interop // https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx internal partial class Errors { - internal const int ERROR_SUCCESS = 0x0; - internal const int ERROR_INVALID_FUNCTION = 0x1; internal const int ERROR_FILE_NOT_FOUND = 0x2; - internal const int ERROR_PATH_NOT_FOUND = 0x3; - internal const int ERROR_ACCESS_DENIED = 0x5; internal const int ERROR_INVALID_HANDLE = 0x6; - internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8; - internal const int ERROR_INVALID_DATA = 0xD; - internal const int ERROR_INVALID_DRIVE = 0xF; - internal const int ERROR_NO_MORE_FILES = 0x12; - internal const int ERROR_NOT_READY = 0x15; - internal const int ERROR_BAD_COMMAND = 0x16; - internal const int ERROR_BAD_LENGTH = 0x18; internal const int ERROR_SHARING_VIOLATION = 0x20; - internal const int ERROR_LOCK_VIOLATION = 0x21; - internal const int ERROR_HANDLE_EOF = 0x26; - internal const int ERROR_BAD_NETPATH = 0x35; - internal const int ERROR_NETWORK_ACCESS_DENIED = 0x41; - internal const int ERROR_BAD_NET_NAME = 0x43; - internal const int ERROR_FILE_EXISTS = 0x50; internal const int ERROR_INVALID_PARAMETER = 0x57; - internal const int ERROR_BROKEN_PIPE = 0x6D; - internal const int ERROR_SEM_TIMEOUT = 0x79; - internal const int ERROR_CALL_NOT_IMPLEMENTED = 0x78; - internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; - internal const int ERROR_INVALID_NAME = 0x7B; - internal const int ERROR_NEGATIVE_SEEK = 0x83; - internal const int ERROR_DIR_NOT_EMPTY = 0x91; - internal const int ERROR_BAD_PATHNAME = 0xA1; - internal const int ERROR_LOCK_FAILED = 0xA7; - internal const int ERROR_BUSY = 0xAA; - internal const int ERROR_ALREADY_EXISTS = 0xB7; - internal const int ERROR_BAD_EXE_FORMAT = 0xC1; - internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB; - internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; - internal const int ERROR_EXE_MACHINE_TYPE_MISMATCH = 0xD8; - internal const int ERROR_PIPE_BUSY = 0xE7; - internal const int ERROR_NO_DATA = 0xE8; - internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9; - internal const int ERROR_MORE_DATA = 0xEA; - internal const int ERROR_NO_MORE_ITEMS = 0x103; - internal const int ERROR_DIRECTORY = 0x10B; - internal const int ERROR_PARTIAL_COPY = 0x12B; - internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216; - internal const int ERROR_PIPE_CONNECTED = 0x217; - internal const int ERROR_PIPE_LISTENING = 0x218; - internal const int ERROR_OPERATION_ABORTED = 0x3E3; - internal const int ERROR_IO_INCOMPLETE = 0x3E4; - internal const int ERROR_IO_PENDING = 0x3E5; - internal const int ERROR_NO_TOKEN = 0x3f0; - internal const int ERROR_DLL_INIT_FAILED = 0x45A; - internal const int ERROR_COUNTER_TIMEOUT = 0x461; - internal const int ERROR_NO_ASSOCIATION = 0x483; - internal const int ERROR_DDE_FAIL = 0x484; - internal const int ERROR_DLL_NOT_FOUND = 0x485; - internal const int ERROR_NOT_FOUND = 0x490; - internal const int ERROR_NETWORK_UNREACHABLE = 0x4CF; - internal const int ERROR_NON_ACCOUNT_SID = 0x4E9; - internal const int ERROR_NOT_ALL_ASSIGNED = 0x514; - internal const int ERROR_UNKNOWN_REVISION = 0x519; - internal const int ERROR_INVALID_OWNER = 0x51B; - internal const int ERROR_INVALID_PRIMARY_GROUP = 0x51C; - internal const int ERROR_NO_SUCH_PRIVILEGE = 0x521; - internal const int ERROR_PRIVILEGE_NOT_HELD = 0x522; - internal const int ERROR_INVALID_ACL = 0x538; - internal const int ERROR_INVALID_SECURITY_DESCR = 0x53A; - internal const int ERROR_INVALID_SID = 0x539; - internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542; - internal const int ERROR_CANT_OPEN_ANONYMOUS = 0x543; - internal const int ERROR_NO_SECURITY_ON_OBJECT = 0x546; - internal const int ERROR_CLASS_ALREADY_EXISTS = 0x582; - internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 0x6FD; - internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 0x717; - internal const int EFail = unchecked((int)0x80004005); - internal const int E_FILENOTFOUND = unchecked((int)0x80070002); } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/Interop.Libraries.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/Interop.Libraries.cs index f130aa1bfb..879bb0a38d 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/Interop.Libraries.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/Interop.Libraries.cs @@ -6,35 +6,9 @@ internal static partial class Interop { internal static partial class Libraries { - internal const string Advapi32 = "advapi32.dll"; - internal const string BCrypt = "BCrypt.dll"; - internal const string CoreComm_L1_1_1 = "api-ms-win-core-comm-l1-1-1.dll"; - internal const string CoreComm_L1_1_2 = "api-ms-win-core-comm-l1-1-2.dll"; internal const string Crypt32 = "crypt32.dll"; - internal const string CryptUI = "cryptui.dll"; - internal const string Error_L1 = "api-ms-win-core-winrt-error-l1-1-0.dll"; - internal const string HttpApi = "httpapi.dll"; - internal const string IpHlpApi = "iphlpapi.dll"; internal const string Kernel32 = "kernel32.dll"; - internal const string Memory_L1_3 = "api-ms-win-core-memory-l1-1-3.dll"; - internal const string Mswsock = "mswsock.dll"; - internal const string NCrypt = "ncrypt.dll"; internal const string NtDll = "ntdll.dll"; - internal const string Odbc32 = "odbc32.dll"; - internal const string Ole32 = "ole32.dll"; - internal const string OleAut32 = "oleaut32.dll"; - internal const string PerfCounter = "perfcounter.dll"; - internal const string RoBuffer = "api-ms-win-core-winrt-robuffer-l1-1-0.dll"; - internal const string Secur32 = "secur32.dll"; - internal const string Shell32 = "shell32.dll"; internal const string SspiCli = "sspicli.dll"; - internal const string User32 = "user32.dll"; - internal const string Version = "version.dll"; - internal const string WebSocket = "websocket.dll"; - internal const string WinHttp = "winhttp.dll"; - internal const string Ws2_32 = "ws2_32.dll"; - internal const string Wtsapi32 = "wtsapi32.dll"; - internal const string CompressionNative = "clrcompression.dll"; - internal const string CoreWinRT = "api-ms-win-core-winrt-l1-1-0.dll"; } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.GetTokenInformation_void.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.GetTokenInformation_void.cs deleted file mode 100644 index 3430c2d2c0..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.GetTokenInformation_void.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Win32.SafeHandles; -using System; -using System.Runtime.InteropServices; - -internal static partial class Interop -{ - internal static partial class Advapi32 - { - [DllImport(Interop.Libraries.Advapi32, SetLastError = true)] - internal unsafe static extern bool GetTokenInformation( - SafeAccessTokenHandle TokenHandle, - TOKEN_INFORMATION_CLASS TokenInformationClass, - void* TokenInformation, - uint TokenInformationLength, - out uint ReturnLength); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.OpenProcessToken_IntPtr.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.OpenProcessToken_IntPtr.cs deleted file mode 100644 index d93e162dfb..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.OpenProcessToken_IntPtr.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Microsoft.Win32.SafeHandles; -using System.Runtime.InteropServices; -using System; -using System.Security.Principal; - -internal partial class Interop -{ - internal partial class Advapi32 - { - [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern bool OpenProcessToken( - IntPtr ProcessToken, - TokenAccessLevels DesiredAccess, - out SafeTokenHandle TokenHandle); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.OpenProcessToken_SafeAccessTokenHandle.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.OpenProcessToken_SafeAccessTokenHandle.cs deleted file mode 100644 index 3bf14f03e7..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.OpenProcessToken_SafeAccessTokenHandle.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Security.Principal; -using Microsoft.Win32.SafeHandles; - -internal static partial class Interop -{ - internal static partial class Advapi32 - { - [DllImport(Interop.Libraries.Advapi32, SetLastError = true)] - internal static extern bool OpenProcessToken(IntPtr ProcessToken, TokenAccessLevels DesiredAccess, out SafeAccessTokenHandle TokenHandle); - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.TOKEN_ELEVATION.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.TOKEN_ELEVATION.cs deleted file mode 100644 index 55b49c9df3..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.TOKEN_ELEVATION.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -internal static partial class Interop -{ - internal static partial class Advapi32 - { - // https://msdn.microsoft.com/en-us/library/windows/desktop/bb530717.aspx - internal struct TOKEN_ELEVATION - { - public BOOL TokenIsElevated; - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.TOKEN_INFORMATION_CLASS.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.TOKEN_INFORMATION_CLASS.cs deleted file mode 100644 index 89c36b694a..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/advapi32/Interop.TOKEN_INFORMATION_CLASS.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -internal static partial class Interop -{ - internal static partial class Advapi32 - { - /// - /// TOKEN_INFORMATION_CLASS enumeration. - /// - internal enum TOKEN_INFORMATION_CLASS : uint - { - TokenUser = 1, - TokenGroups, - TokenPrivileges, - TokenOwner, - TokenPrimaryGroup, - TokenDefaultDacl, - TokenSource, - TokenType, - TokenImpersonationLevel, - TokenStatistics, - TokenRestrictedSids, - TokenSessionId, - TokenGroupsAndPrivileges, - TokenSessionReference, - TokenSandBoxInert, - TokenAuditPolicy, - TokenOrigin, - TokenElevationType, - TokenLinkedToken, - TokenElevation, - TokenHasRestrictions, - TokenAccessInformation, - TokenVirtualizationAllowed, - TokenVirtualizationEnabled, - TokenIntegrityLevel, - TokenUIAccess, - TokenMandatoryPolicy, - TokenLogonSid, - TokenIsAppContainer, - TokenCapabilities, - TokenAppContainerSid, - TokenAppContainerNumber, - TokenUserClaimAttributes, - TokenDeviceClaimAttributes, - TokenRestrictedUserClaimAttributes, - TokenRestrictedDeviceClaimAttributes, - TokenDeviceGroups, - TokenRestrictedDeviceGroups, - TokenSecurityAttributes, - TokenIsRestricted, - MaxTokenInfoClass - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/kernel32/Interop.FileOperations.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/kernel32/Interop.FileOperations.cs deleted file mode 100644 index 8576834ea8..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/kernel32/Interop.FileOperations.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -internal partial class Interop -{ - internal partial class Kernel32 - { - internal partial class IOReparseOptions - { - internal const uint IO_REPARSE_TAG_FILE_PLACEHOLDER = 0x80000015; - internal const uint IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003; - } - - internal partial class FileOperations - { - internal const int OPEN_EXISTING = 3; - internal const int COPY_FILE_FAIL_IF_EXISTS = 0x00000001; - - internal const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000; - internal const int FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000; - internal const int FILE_FLAG_OVERLAPPED = 0x40000000; - - internal const int FILE_LIST_DIRECTORY = 0x0001; - } - - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/Interop.SSPI.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/Interop.SSPI.cs index 34bed7ce31..8ceed0e870 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/Interop.SSPI.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Windows/sspicli/Interop.SSPI.cs @@ -20,23 +20,23 @@ internal static partial class SspiCli [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct CredHandle { - private IntPtr dwLower; - private IntPtr dwUpper; + private IntPtr _dwLower; + private IntPtr _dwUpper; public bool IsZero { - get { return dwLower == IntPtr.Zero && dwUpper == IntPtr.Zero; } + get { return _dwLower == IntPtr.Zero && _dwUpper == IntPtr.Zero; } } internal void SetToInvalid() { - dwLower = IntPtr.Zero; - dwUpper = IntPtr.Zero; + _dwLower = IntPtr.Zero; + _dwUpper = IntPtr.Zero; } public override string ToString() { - { return dwLower.ToString("x") + ":" + dwUpper.ToString("x"); } + { return _dwLower.ToString("x") + ":" + _dwUpper.ToString("x"); } } } @@ -201,7 +201,7 @@ internal struct SCHANNEL_CRED public int dwMinimumCipherStrength; public int dwMaximumCipherStrength; public int dwSessionLifespan; - public SCHANNEL_CRED.Flags dwFlags; + public Flags dwFlags; public int reserved; [Flags] @@ -243,7 +243,7 @@ public SecBufferDesc(int count) } } - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern int EncryptMessage( ref CredHandle contextHandle, [In] uint qualityOfProtection, @@ -251,7 +251,7 @@ internal static extern int EncryptMessage( [In] uint sequenceNumber ); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int DecryptMessage( [In] ref CredHandle contextHandle, [In, Out] ref SecBufferDesc inputOutput, @@ -259,26 +259,26 @@ internal static extern unsafe int DecryptMessage( uint* qualityOfProtection ); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern int QuerySecurityContextToken( ref CredHandle phContext, [Out] out SecurityContextTokenHandle handle); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern int FreeContextBuffer( [In] IntPtr contextBuffer); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern int FreeCredentialsHandle( ref CredHandle handlePtr ); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern int DeleteSecurityContext( ref CredHandle handlePtr ); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int AcceptSecurityContext( ref CredHandle credentialHandle, [In] void* inContextPtr, @@ -291,25 +291,25 @@ internal static extern unsafe int AcceptSecurityContext( out long timeStamp ); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int QueryContextAttributesW( ref CredHandle contextHandle, [In] ContextAttribute attribute, [In] void* buffer); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int SetContextAttributesW( ref CredHandle contextHandle, [In] ContextAttribute attribute, [In] byte[] buffer, [In] int bufferSize); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern int EnumerateSecurityPackagesW( [Out] out int pkgnum, [Out] out SafeFreeContextBuffer_SECURITY handle); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe int AcquireCredentialsHandleW( [In] string principal, [In] string moduleName, @@ -322,7 +322,7 @@ internal static extern unsafe int AcquireCredentialsHandleW( [Out] out long timeStamp ); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe int AcquireCredentialsHandleW( [In] string principal, [In] string moduleName, @@ -335,7 +335,7 @@ internal static extern unsafe int AcquireCredentialsHandleW( [Out] out long timeStamp ); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe int AcquireCredentialsHandleW( [In] string principal, [In] string moduleName, @@ -348,7 +348,7 @@ internal static extern unsafe int AcquireCredentialsHandleW( [Out] out long timeStamp ); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int InitializeSecurityContextW( ref CredHandle credentialHandle, [In] void* inContextPtr, @@ -364,23 +364,23 @@ internal static extern unsafe int InitializeSecurityContextW( out long timeStamp ); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int CompleteAuthToken( [In] void* inContextPtr, [In, Out] ref SecBufferDesc inputBuffers ); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe int ApplyControlToken( [In] void* inContextPtr, [In, Out] ref SecBufferDesc inputBuffers ); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, SetLastError = true)] internal static extern unsafe SECURITY_STATUS SspiFreeAuthIdentity( [In] IntPtr authData); - [DllImport(Interop.Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] + [DllImport(Libraries.SspiCli, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal static extern unsafe SECURITY_STATUS SspiEncodeStringsAsAuthIdentity( [In] string userName, [In] string domainName, diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs index 6daf3f2191..6921ef6aba 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; +using static Interop.NetSecurityNative; namespace Microsoft.Win32.SafeHandles { @@ -17,15 +18,13 @@ internal sealed class SafeGssNameHandle : SafeHandle public static SafeGssNameHandle CreateUser(string name) { Debug.Assert(!string.IsNullOrEmpty(name), "Invalid user name passed to SafeGssNameHandle create"); - SafeGssNameHandle retHandle; - Interop.NetSecurityNative.Status minorStatus; - Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.ImportUserName( - out minorStatus, name, Encoding.UTF8.GetByteCount(name), out retHandle); + Status status = ImportUserName( + out Status minorStatus, name, Encoding.UTF8.GetByteCount(name), out SafeGssNameHandle retHandle); - if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) + if (status != Status.GSS_S_COMPLETE) { retHandle.Dispose(); - throw new Interop.NetSecurityNative.GssApiException(status, minorStatus); + throw new GssApiException(status, minorStatus); } return retHandle; @@ -34,15 +33,13 @@ public static SafeGssNameHandle CreateUser(string name) public static SafeGssNameHandle CreatePrincipal(string name) { Debug.Assert(!string.IsNullOrEmpty(name), "Invalid principal passed to SafeGssNameHandle create"); - SafeGssNameHandle retHandle; - Interop.NetSecurityNative.Status minorStatus; - Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.ImportPrincipalName( - out minorStatus, name, Encoding.UTF8.GetByteCount(name), out retHandle); + Status status = ImportPrincipalName( + out Status minorStatus, name, Encoding.UTF8.GetByteCount(name), out SafeGssNameHandle retHandle); - if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) + if (status != Status.GSS_S_COMPLETE) { retHandle.Dispose(); - throw new Interop.NetSecurityNative.GssApiException(status, minorStatus); + throw new GssApiException(status, minorStatus); } return retHandle; @@ -55,16 +52,12 @@ public override bool IsInvalid protected override bool ReleaseHandle() { - Interop.NetSecurityNative.Status minorStatus; - Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.ReleaseName(out minorStatus, ref handle); + Status status = ReleaseName(out _, ref handle); SetHandle(IntPtr.Zero); - return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE; + return status == Status.GSS_S_COMPLETE; } - private SafeGssNameHandle() - : base(IntPtr.Zero, true) - { - } + private SafeGssNameHandle() : base(IntPtr.Zero, true) { } } /// @@ -86,21 +79,21 @@ public static SafeGssCredHandle Create(string username, string password, bool is SafeGssCredHandle retHandle = null; using (SafeGssNameHandle userHandle = SafeGssNameHandle.CreateUser(username)) { - Interop.NetSecurityNative.Status status; - Interop.NetSecurityNative.Status minorStatus; + Status status; + Status minorStatus; if (string.IsNullOrEmpty(password)) { - status = Interop.NetSecurityNative.InitiateCredSpNego(out minorStatus, userHandle, out retHandle); + status = InitiateCredSpNego(out minorStatus, userHandle, out retHandle); } else { - status = Interop.NetSecurityNative.InitiateCredWithPassword(out minorStatus, isNtlmOnly, userHandle, password, Encoding.UTF8.GetByteCount(password), out retHandle); + status = InitiateCredWithPassword(out minorStatus, isNtlmOnly, userHandle, password, Encoding.UTF8.GetByteCount(password), out retHandle); } - if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) + if (status != Status.GSS_S_COMPLETE) { retHandle.Dispose(); - throw new Interop.NetSecurityNative.GssApiException(status, minorStatus); + throw new GssApiException(status, minorStatus); } } @@ -119,19 +112,15 @@ public override bool IsInvalid protected override bool ReleaseHandle() { - Interop.NetSecurityNative.Status minorStatus; - Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.ReleaseCred(out minorStatus, ref handle); + Status status = ReleaseCred(out _, ref handle); SetHandle(IntPtr.Zero); - return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE; + return status == Status.GSS_S_COMPLETE; } } internal sealed class SafeGssContextHandle : SafeHandle { - public SafeGssContextHandle() - : base(IntPtr.Zero, true) - { - } + public SafeGssContextHandle() : base(IntPtr.Zero, true) { } public override bool IsInvalid { @@ -140,10 +129,9 @@ public override bool IsInvalid protected override bool ReleaseHandle() { - Interop.NetSecurityNative.Status minorStatus; - Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.DeleteSecContext(out minorStatus, ref handle); + Status status = DeleteSecContext(out _, ref handle); SetHandle(IntPtr.Zero); - return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE; + return status == Status.GSS_S_COMPLETE; } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs index a759af1db0..fa46535d05 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs @@ -2,15 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.IO; -using System.Security; -using System.Security.Principal; -using System.Threading; using System.ComponentModel; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Security.Authentication; -using System.Security.Authentication.ExtendedProtection; using Microsoft.Win32.SafeHandles; namespace System.Net.Security @@ -26,74 +19,6 @@ internal static partial class NegotiateStreamPal // defined in winerror.h private const int NTE_FAIL = unchecked((int)0x80090020); - internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext) - { - throw new PlatformNotSupportedException(Strings.net_nego_server_not_supported); - } - - internal static string QueryContextAuthenticationPackage(SafeDeleteContext securityContext) - { - SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext; - return negoContext.IsNtlmUsed ? NegotiationInfoClass.NTLM : NegotiationInfoClass.Kerberos; - } - - static byte[] GssWrap( - SafeGssContextHandle context, - bool encrypt, - byte[] buffer, - int offset, - int count) - { - Debug.Assert((buffer != null) && (buffer.Length > 0), "Invalid input buffer passed to Encrypt"); - Debug.Assert((offset >= 0) && (offset < buffer.Length), "Invalid input offset passed to Encrypt"); - Debug.Assert((count >= 0) && (count <= (buffer.Length - offset)), "Invalid input count passed to Encrypt"); - - Interop.NetSecurityNative.GssBuffer encryptedBuffer = default(Interop.NetSecurityNative.GssBuffer); - try - { - Interop.NetSecurityNative.Status minorStatus; - Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.WrapBuffer(out minorStatus, context, encrypt, buffer, offset, count, ref encryptedBuffer); - if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) - { - throw new Interop.NetSecurityNative.GssApiException(status, minorStatus); - } - - return encryptedBuffer.ToByteArray(); - } - finally - { - encryptedBuffer.Dispose(); - } - } - - private static int GssUnwrap( - SafeGssContextHandle context, - byte[] buffer, - int offset, - int count) - { - Debug.Assert((buffer != null) && (buffer.Length > 0), "Invalid input buffer passed to Decrypt"); - Debug.Assert((offset >= 0) && (offset <= buffer.Length), "Invalid input offset passed to Decrypt"); - Debug.Assert((count >= 0) && (count <= (buffer.Length - offset)), "Invalid input count passed to Decrypt"); - - Interop.NetSecurityNative.GssBuffer decryptedBuffer = default(Interop.NetSecurityNative.GssBuffer); - try - { - Interop.NetSecurityNative.Status minorStatus; - Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.UnwrapBuffer(out minorStatus, context, buffer, offset, count, ref decryptedBuffer); - if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) - { - throw new Interop.NetSecurityNative.GssApiException(status, minorStatus); - } - - return decryptedBuffer.Copy(buffer, offset); - } - finally - { - decryptedBuffer.Dispose(); - } - } - private static bool GssInitSecurityContext( ref SafeGssContextHandle context, SafeGssCredHandle credential, @@ -116,7 +41,7 @@ private static bool GssInitSecurityContext( context = new SafeGssContextHandle(); } - Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer); + Interop.NetSecurityNative.GssBuffer token = default; Interop.NetSecurityNative.Status status; try @@ -259,22 +184,6 @@ internal static SecurityStatusPal InitializeSecurityContext( return status; } - internal static SecurityStatusPal AcceptSecurityContext( - SafeFreeCredentials credentialsHandle, - ref SafeDeleteContext securityContext, - ContextFlagsPal requestedContextFlags, - SecurityBuffer[] inSecurityBufferArray, - SecurityBuffer outSecurityBuffer, - ref ContextFlagsPal contextFlags) - { - throw new PlatformNotSupportedException(Strings.net_nego_server_not_supported); - } - - internal static Win32Exception CreateExceptionFromError(SecurityStatusPal statusCode) - { - return new Win32Exception(NTE_FAIL, (statusCode.Exception != null) ? statusCode.Exception.Message : statusCode.ErrorCode.ToString()); - } - internal static int QueryMaxTokenSize(string package) { // This value is not used on Unix @@ -313,104 +222,5 @@ internal static SafeFreeCredentials AcquireCredentialsHandle(string package, boo throw new Win32Exception(NTE_FAIL, ex.Message); } } - - internal static SecurityStatusPal CompleteAuthToken( - ref SafeDeleteContext securityContext, - SecurityBuffer[] inSecurityBufferArray) - { - return new SecurityStatusPal(SecurityStatusPalErrorCode.OK); - } - - internal static int Encrypt( - SafeDeleteContext securityContext, - byte[] buffer, - int offset, - int count, - bool isConfidential, - bool isNtlm, - ref byte[] output, - uint sequenceNumber) - { - SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext) securityContext; - byte[] tempOutput = GssWrap(gssContext.GssContext, isConfidential, buffer, offset, count); - - // Create space for prefixing with the length - const int prefixLength = 4; - output = new byte[tempOutput.Length + prefixLength]; - Array.Copy(tempOutput, 0, output, prefixLength, tempOutput.Length); - int resultSize = tempOutput.Length; - unchecked - { - output[0] = (byte)((resultSize) & 0xFF); - output[1] = (byte)(((resultSize) >> 8) & 0xFF); - output[2] = (byte)(((resultSize) >> 16) & 0xFF); - output[3] = (byte)(((resultSize) >> 24) & 0xFF); - } - - return resultSize + 4; - } - - internal static int Decrypt( - SafeDeleteContext securityContext, - byte[] buffer, - int offset, - int count, - bool isConfidential, - bool isNtlm, - out int newOffset, - uint sequenceNumber) - { - if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length)) - { - NetEventSource.Fail(securityContext, "Argument 'offset' out of range"); - throw new ArgumentOutOfRangeException(nameof(offset)); - } - - if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset)) - { - NetEventSource.Fail(securityContext, "Argument 'count' out of range."); - throw new ArgumentOutOfRangeException(nameof(count)); - } - - newOffset = offset; - return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer, offset, count); - } - - internal static int VerifySignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count) - { - if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length)) - { - NetEventSource.Fail(securityContext, "Argument 'offset' out of range"); - throw new ArgumentOutOfRangeException(nameof(offset)); - } - - if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset)) - { - NetEventSource.Fail(securityContext, "Argument 'count' out of range."); - throw new ArgumentOutOfRangeException(nameof(count)); - } - - return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer, offset, count); - } - - internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, ref byte[] output) - { - SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext)securityContext; - byte[] tempOutput = GssWrap(gssContext.GssContext, false, buffer, offset, count); - // Create space for prefixing with the length - const int prefixLength = 4; - output = new byte[tempOutput.Length + prefixLength]; - Array.Copy(tempOutput, 0, output, prefixLength, tempOutput.Length); - int resultSize = tempOutput.Length; - unchecked - { - output[0] = (byte)((resultSize) & 0xFF); - output[1] = (byte)(((resultSize) >> 8) & 0xFF); - output[2] = (byte)(((resultSize) >> 16) & 0xFF); - output[3] = (byte)(((resultSize) >> 24) & 0xFF); - } - - return resultSize + 4; - } } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/Unix/SafeDeleteNegoContext.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/Unix/SafeDeleteNegoContext.cs index 9b07e53e5e..b98e9ac80b 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/Unix/SafeDeleteNegoContext.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/Unix/SafeDeleteNegoContext.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Text; using Microsoft.Win32.SafeHandles; namespace System.Net.Security diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/Unix/SafeFreeCredentials.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/Unix/SafeFreeCredentials.cs index 245f0f24cf..51d6869a8d 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/Unix/SafeFreeCredentials.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/Unix/SafeFreeCredentials.cs @@ -2,9 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics; using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; +using Microsoft.Win32.SafeHandles; namespace System.Net.Security { @@ -37,7 +36,7 @@ internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid // // Static cache will return the target handle if found the reference in the table. // - internal SafeFreeCredentials Target; + internal SafeFreeCredentials _target; internal static SafeCredentialReference CreateReference(SafeFreeCredentials target) { @@ -55,19 +54,19 @@ private SafeCredentialReference(SafeFreeCredentials target) : base() // its dispose should be postponed bool ignore = false; target.DangerousAddRef(ref ignore); - Target = target; + _target = target; SetHandle(new IntPtr(0)); // make this handle valid } protected override bool ReleaseHandle() { - SafeFreeCredentials target = Target; + SafeFreeCredentials target = _target; if (target != null) { target.DangerousRelease(); } - Target = null; + _target = null; return true; } } diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/Unix/SafeFreeNegoCredentials.cs b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/Unix/SafeFreeNegoCredentials.cs index ab8cf2fea0..217c787619 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/Unix/SafeFreeNegoCredentials.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Common/src/System/Net/Security/Unix/SafeFreeNegoCredentials.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Text; using Microsoft.Win32.SafeHandles; namespace System.Net.Security diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj index 4bd8bb5c1d..ff1db9b5e6 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj @@ -473,9 +473,6 @@ Common\Interop\Windows\kernel32\Interop.DeviceIoControl.cs - - Common\Interop\Windows\kernel32\Interop.FileOperations.cs - Common\Interop\Windows\Kernel32\Interop.IoControlTransferType.cs diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIProxy.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIProxy.cs index b578cb6364..f25b8ac2d6 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIProxy.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIProxy.cs @@ -5,7 +5,6 @@ using System; using System.Diagnostics; using System.IO; -using System.Linq; using System.Net; using System.Net.Security; using System.Net.Sockets; @@ -21,6 +20,7 @@ internal class SNIProxy private const int DefaultSqlServerPort = 1433; private const int DefaultSqlServerDacPort = 1434; private const string SqlServerSpnHeader = "MSSQLSvc"; + private const int MaxTokenSize = 0; internal class SspiClientContextResult { @@ -29,13 +29,11 @@ internal class SspiClientContextResult internal const uint KerberosTicketMissing = 2; } - public static readonly SNIProxy Singleton = new SNIProxy(); + internal static readonly SNIProxy s_singleton = new SNIProxy(); - /// - /// Terminate SNI - /// - public void Terminate() + internal static SNIProxy GetInstance() { + return s_singleton; } /// @@ -44,7 +42,7 @@ public void Terminate() /// Connection handle /// /// SNI error code - public uint EnableSsl(SNIHandle handle, uint options) + internal uint EnableSsl(SNIHandle handle, uint options) { try { @@ -61,7 +59,7 @@ public uint EnableSsl(SNIHandle handle, uint options) /// /// Connection handle /// SNI error code - public uint DisableSsl(SNIHandle handle) + internal uint DisableSsl(SNIHandle handle) { handle.DisableSsl(); return TdsEnums.SNI_SUCCESS; @@ -75,7 +73,7 @@ public uint DisableSsl(SNIHandle handle) /// Send buffer /// Service Principal Name buffer /// SNI error code - public void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, byte[] receivedBuff, ref byte[] sendBuff, byte[] serverName) + internal void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, byte[] receivedBuff, ref byte[] sendBuff, byte[] serverName) { SafeDeleteContext securityContext = sspiClientContextStatus.SecurityContext; ContextFlagsPal contextFlags = sspiClientContextStatus.ContextFlags; @@ -88,7 +86,7 @@ public void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus credentialsHandle = NegotiateStreamPal.AcquireDefaultCredential(securityPackage, false); } - SecurityBuffer[] inSecurityBufferArray = null; + SecurityBuffer[] inSecurityBufferArray; if (receivedBuff != null) { inSecurityBufferArray = new SecurityBuffer[] { new SecurityBuffer(receivedBuff, SecurityBufferType.SECBUFFER_TOKEN) }; @@ -98,7 +96,7 @@ public void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus inSecurityBufferArray = Array.Empty(); } - int tokenSize = NegotiateStreamPal.QueryMaxTokenSize(securityPackage); + int tokenSize = MaxTokenSize; SecurityBuffer outSecurityBuffer = new SecurityBuffer(tokenSize, SecurityBufferType.SECBUFFER_TOKEN); ContextFlagsPal requestedContextFlags = ContextFlagsPal.Connection @@ -121,7 +119,7 @@ public void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus statusCode.ErrorCode == SecurityStatusPalErrorCode.CompAndContinue) { inSecurityBufferArray = new SecurityBuffer[] { outSecurityBuffer }; - statusCode = NegotiateStreamPal.CompleteAuthToken(ref securityContext, inSecurityBufferArray); + statusCode = new SecurityStatusPal(SecurityStatusPalErrorCode.OK); outSecurityBuffer.token = null; } @@ -164,23 +162,13 @@ private static bool IsErrorStatus(SecurityStatusPalErrorCode errorCode) errorCode != SecurityStatusPalErrorCode.Renegotiate; } - /// - /// Initialize SSPI - /// - /// Max length of SSPI packet - /// SNI error code - public uint InitializeSspiPackage(ref uint maxLength) - { - throw new PlatformNotSupportedException(); - } - /// /// Set connection buffer size /// /// SNI handle /// Buffer size /// SNI error code - public uint SetConnectionBufferSize(SNIHandle handle, uint bufferSize) + internal uint SetConnectionBufferSize(SNIHandle handle, uint bufferSize) { handle.SetBufferSize((int)bufferSize); return TdsEnums.SNI_SUCCESS; @@ -193,7 +181,7 @@ public uint SetConnectionBufferSize(SNIHandle handle, uint bufferSize) /// Destination byte array where data packets are copied to /// Length of data packets /// SNI error status - public uint PacketGetData(SNIPacket packet, byte[] inBuff, ref uint dataSize) + internal uint PacketGetData(SNIPacket packet, byte[] inBuff, ref uint dataSize) { int dataSizeInt = 0; packet.GetData(inBuff, ref dataSizeInt); @@ -209,7 +197,7 @@ public uint PacketGetData(SNIPacket packet, byte[] inBuff, ref uint dataSize) /// SNI packet /// Timeout /// SNI error status - public uint ReadSyncOverAsync(SNIHandle handle, out SNIPacket packet, int timeout) + internal uint ReadSyncOverAsync(SNIHandle handle, out SNIPacket packet, int timeout) { return handle.Receive(out packet, timeout); } @@ -220,7 +208,7 @@ public uint ReadSyncOverAsync(SNIHandle handle, out SNIPacket packet, int timeou /// SNI handle /// Client connection ID /// SNI error status - public uint GetConnectionId(SNIHandle handle, ref Guid clientConnectionId) + internal uint GetConnectionId(SNIHandle handle, ref Guid clientConnectionId) { clientConnectionId = handle.ConnectionId; @@ -234,7 +222,7 @@ public uint GetConnectionId(SNIHandle handle, ref Guid clientConnectionId) /// SNI packet /// true if synchronous, false if asynchronous /// SNI error status - public uint WritePacket(SNIHandle handle, SNIPacket packet, bool sync) + internal uint WritePacket(SNIHandle handle, SNIPacket packet, bool sync) { uint result; if (sync) @@ -266,7 +254,7 @@ public uint WritePacket(SNIHandle handle, SNIPacket packet, bool sync) /// Used for DNS Cache /// Used for DNS Cache /// SNI handle - public SNIHandle CreateConnectionHandle(object callbackObject, string fullServerName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool parallel, bool isIntegratedSecurity, string cachedFQDN, ref SQLDNSInfo pendingDNSInfo) + internal SNIHandle CreateConnectionHandle(object callbackObject, string fullServerName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool parallel, bool isIntegratedSecurity, string cachedFQDN, ref SQLDNSInfo pendingDNSInfo) { instanceName = new byte[1]; @@ -288,7 +276,7 @@ public SNIHandle CreateConnectionHandle(object callbackObject, string fullServer } SNIHandle sniHandle = null; - switch (details.ConnectionProtocol) + switch (details._connectionProtocol) { case DataSource.Protocol.Admin: case DataSource.Protocol.None: // default to using tcp if no protocol is provided @@ -299,7 +287,7 @@ public SNIHandle CreateConnectionHandle(object callbackObject, string fullServer sniHandle = CreateNpHandle(details, timerExpire, callbackObject, parallel); break; default: - Debug.Fail($"Unexpected connection protocol: {details.ConnectionProtocol}"); + Debug.Fail($"Unexpected connection protocol: {details._connectionProtocol}"); break; } @@ -333,7 +321,7 @@ private static byte[] GetSqlServerSPN(DataSource dataSource) postfix = dataSource.InstanceName; } // For handling tcp: format - else if (dataSource.ConnectionProtocol == DataSource.Protocol.TCP) + else if (dataSource._connectionProtocol == DataSource.Protocol.TCP) { postfix = DefaultSqlServerPort.ToString(); } @@ -396,7 +384,7 @@ private SNITCPHandle CreateTcpHandle(DataSource details, long timerExpire, objec } int port = -1; - bool isAdminConnection = details.ConnectionProtocol == DataSource.Protocol.Admin; + bool isAdminConnection = details._connectionProtocol == DataSource.Protocol.Admin; if (details.IsSsrpRequired) { try @@ -449,7 +437,7 @@ private SNINpHandle CreateNpHandle(DataSource details, long timerExpire, object /// SNI handle /// Packet /// SNI error status - public uint ReadAsync(SNIHandle handle, out SNIPacket packet) + internal uint ReadAsync(SNIHandle handle, out SNIPacket packet) { packet = null; return handle.ReceiveAsync(ref packet); @@ -461,7 +449,7 @@ public uint ReadAsync(SNIHandle handle, out SNIPacket packet) /// SNI packet /// Data /// Length - public void PacketSetData(SNIPacket packet, byte[] data, int length) + internal void PacketSetData(SNIPacket packet, byte[] data, int length) { packet.AppendData(data, length); } @@ -471,7 +459,7 @@ public void PacketSetData(SNIPacket packet, byte[] data, int length) /// /// /// SNI error status - public uint CheckConnection(SNIHandle handle) + internal uint CheckConnection(SNIHandle handle) { return handle.CheckConnection(); } @@ -480,7 +468,7 @@ public uint CheckConnection(SNIHandle handle) /// Get last SNI error on this thread /// /// - public SNIError GetLastError() + internal SNIError GetLastError() { return SNILoadHandle.SingletonInstance.LastError; } @@ -524,10 +512,13 @@ private string GetLocalDBDataSource(string fullServerName, out bool error) internal class DataSource { private const char CommaSeparator = ','; - private const char BackSlashSeparator = '\\'; + private const char SemiColon = ':'; + private const char BackSlashCharacter = '\\'; + private const string DefaultHostName = "localhost"; private const string DefaultSqlServerInstanceName = "mssqlserver"; private const string PipeBeginning = @"\\"; + private const string Slash = @"/"; private const string PipeToken = "pipe"; private const string LocalDbHost = "(localdb)"; private const string NamedPipeInstanceNameHeader = "mssql$"; @@ -535,7 +526,7 @@ internal class DataSource internal enum Protocol { TCP, NP, None, Admin }; - internal Protocol ConnectionProtocol = Protocol.None; + internal Protocol _connectionProtocol = Protocol.None; /// /// Provides the HostName of the server to connect to for TCP protocol. @@ -551,17 +542,17 @@ internal enum Protocol { TCP, NP, None, Admin }; /// /// Provides the inferred Instance Name from Server Data Source /// - public string InstanceName { get; internal set; } + internal string InstanceName { get; private set; } /// /// Provides the pipe name in case of Named Pipes /// - public string PipeName { get; internal set; } + internal string PipeName { get; private set; } /// /// Provides the HostName to connect to in case of Named pipes Data Source /// - public string PipeHostName { get; internal set; } + internal string PipeHostName { get; private set; } private string _workingDataSource; private string _dataSourceAfterTrimmingProtocol; @@ -574,31 +565,31 @@ private DataSource(string dataSource) // Remove all whitespaces from the datasource and all operations will happen on lower case. _workingDataSource = dataSource.Trim().ToLowerInvariant(); - int firstIndexOfColon = _workingDataSource.IndexOf(':'); + int firstIndexOfColon = _workingDataSource.IndexOf(SemiColon); PopulateProtocol(); - _dataSourceAfterTrimmingProtocol = (firstIndexOfColon > -1) && ConnectionProtocol != DataSource.Protocol.None + _dataSourceAfterTrimmingProtocol = (firstIndexOfColon > -1) && _connectionProtocol != Protocol.None ? _workingDataSource.Substring(firstIndexOfColon + 1).Trim() : _workingDataSource; - if (_dataSourceAfterTrimmingProtocol.Contains("/")) // Pipe paths only allow back slashes + if (_dataSourceAfterTrimmingProtocol.Contains(Slash)) // Pipe paths only allow back slashes { - if (ConnectionProtocol == DataSource.Protocol.None) + if (_connectionProtocol == Protocol.None) ReportSNIError(SNIProviders.INVALID_PROV); - else if (ConnectionProtocol == DataSource.Protocol.NP) + else if (_connectionProtocol == Protocol.NP) ReportSNIError(SNIProviders.NP_PROV); - else if (ConnectionProtocol == DataSource.Protocol.TCP) + else if (_connectionProtocol == Protocol.TCP) ReportSNIError(SNIProviders.TCP_PROV); } } private void PopulateProtocol() { - string[] splitByColon = _workingDataSource.Split(':'); + string[] splitByColon = _workingDataSource.Split(SemiColon); if (splitByColon.Length <= 1) { - ConnectionProtocol = DataSource.Protocol.None; + _connectionProtocol = Protocol.None; } else { @@ -606,29 +597,29 @@ private void PopulateProtocol() switch (splitByColon[0].Trim()) { case TdsEnums.TCP: - ConnectionProtocol = DataSource.Protocol.TCP; + _connectionProtocol = Protocol.TCP; break; case TdsEnums.NP: - ConnectionProtocol = DataSource.Protocol.NP; + _connectionProtocol = Protocol.NP; break; case TdsEnums.ADMIN: - ConnectionProtocol = DataSource.Protocol.Admin; + _connectionProtocol = Protocol.Admin; break; default: // None of the supported protocols were found. This may be a IPv6 address - ConnectionProtocol = DataSource.Protocol.None; + _connectionProtocol = Protocol.None; break; } } } - public static string GetLocalDBInstance(string dataSource, out bool error) + internal static string GetLocalDBInstance(string dataSource, out bool error) { string instanceName = null; string workingDataSource = dataSource.ToLowerInvariant(); - string[] tokensByBackSlash = workingDataSource.Split(BackSlashSeparator); + string[] tokensByBackSlash = workingDataSource.Split(BackSlashCharacter); error = false; @@ -650,7 +641,7 @@ public static string GetLocalDBInstance(string dataSource, out bool error) return instanceName; } - public static DataSource ParseServerName(string dataSource) + internal static DataSource ParseServerName(string dataSource) { DataSource details = new DataSource(dataSource); @@ -682,19 +673,19 @@ private void InferLocalServerName() // If Server name is empty or localhost, then use "localhost" if (string.IsNullOrEmpty(ServerName) || IsLocalHost(ServerName)) { - ServerName = ConnectionProtocol == DataSource.Protocol.Admin ? + ServerName = _connectionProtocol == Protocol.Admin ? Environment.MachineName : DefaultHostName; } } private bool InferConnectionDetails() { - string[] tokensByCommaAndSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashSeparator, ','); + string[] tokensByCommaAndSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashCharacter, CommaSeparator); ServerName = tokensByCommaAndSlash[0].Trim(); - int commaIndex = _dataSourceAfterTrimmingProtocol.IndexOf(','); + int commaIndex = _dataSourceAfterTrimmingProtocol.IndexOf(CommaSeparator); - int backSlashIndex = _dataSourceAfterTrimmingProtocol.IndexOf(BackSlashSeparator); + int backSlashIndex = _dataSourceAfterTrimmingProtocol.IndexOf(PipeBeginning); // Check the parameters. The parameters are Comma separated in the Data Source. The parameter we really care about is the port // If Comma exists, the try to get the port number @@ -712,11 +703,11 @@ private bool InferConnectionDetails() } // For Tcp and Only Tcp are parameters allowed. - if (ConnectionProtocol == DataSource.Protocol.None) + if (_connectionProtocol == Protocol.None) { - ConnectionProtocol = DataSource.Protocol.TCP; + _connectionProtocol = Protocol.TCP; } - else if (ConnectionProtocol != DataSource.Protocol.TCP) + else if (_connectionProtocol != Protocol.TCP) { // Parameter has been specified for non-TCP protocol. This is not allowed. ReportSNIError(SNIProviders.INVALID_PROV); @@ -774,10 +765,10 @@ private void ReportSNIError(SNIProviders provider) private bool InferNamedPipesInformation() { // If we have a datasource beginning with a pipe or we have already determined that the protocol is Named Pipe - if (_dataSourceAfterTrimmingProtocol.StartsWith(PipeBeginning) || ConnectionProtocol == Protocol.NP) + if (_dataSourceAfterTrimmingProtocol.StartsWith(PipeBeginning) || _connectionProtocol == Protocol.NP) { // If the data source is "np:servername" - if (!_dataSourceAfterTrimmingProtocol.Contains(BackSlashSeparator)) + if (!_dataSourceAfterTrimmingProtocol.Contains(PipeBeginning)) { PipeHostName = ServerName = _dataSourceAfterTrimmingProtocol; InferLocalServerName(); @@ -787,7 +778,7 @@ private bool InferNamedPipesInformation() try { - string[] tokensByBackSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashSeparator); + string[] tokensByBackSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashCharacter); // The datasource is of the format \\host\pipe\sql\query [0]\[1]\[2]\[3]\[4]\[5] // It would at least have 6 parts. @@ -846,11 +837,11 @@ private bool InferNamedPipesInformation() } // DataSource is something like "\\pipename" - if (ConnectionProtocol == DataSource.Protocol.None) + if (_connectionProtocol == Protocol.None) { - ConnectionProtocol = DataSource.Protocol.NP; + _connectionProtocol = Protocol.NP; } - else if (ConnectionProtocol != DataSource.Protocol.NP) + else if (_connectionProtocol != Protocol.NP) { // In case the path began with a "\\" and protocol was not Named Pipes ReportSNIError(SNIProviders.NP_PROV); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Unix.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Unix.cs index 1c875f5813..692633efd6 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Unix.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Unix.cs @@ -26,7 +26,7 @@ private void WaitForSSLHandShakeToComplete(ref uint error, ref int protocolVersi private SNIErrorDetails GetSniErrorDetails() { SNIErrorDetails details; - SNIError sniError = SNIProxy.Singleton.GetLastError(); + SNIError sniError = SNIProxy.GetInstance().GetLastError(); details.sniErrorNumber = sniError.sniError; details.errorMessage = sniError.errorMessage; details.nativeError = sniError.nativeError; diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Windows.cs index d5ddb5d47d..07846127d7 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Windows.cs @@ -95,7 +95,7 @@ private SNIErrorDetails GetSniErrorDetails() if (TdsParserStateObjectFactory.UseManagedSNI) { - SNIError sniError = SNIProxy.Singleton.GetLastError(); + SNIError sniError = SNIProxy.GetInstance().GetLastError(); details.sniErrorNumber = sniError.sniError; details.errorMessage = sniError.errorMessage; details.nativeError = sniError.nativeError; @@ -106,8 +106,7 @@ private SNIErrorDetails GetSniErrorDetails() } else { - SNINativeMethodWrapper.SNI_Error sniError; - SNINativeMethodWrapper.SNIGetLastError(out sniError); + SNINativeMethodWrapper.SNIGetLastError(out SNINativeMethodWrapper.SNI_Error sniError); details.sniErrorNumber = sniError.sniError; details.errorMessage = sniError.errorMessage; details.nativeError = sniError.nativeError; diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectManaged.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectManaged.cs index cc2430bf24..ea802107ff 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectManaged.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectManaged.cs @@ -47,11 +47,11 @@ internal SNIMarsHandle CreateMarsSession(object callbackObject, bool async) } protected override uint SNIPacketGetData(PacketHandle packet, byte[] _inBuff, ref uint dataSize) - => SNIProxy.Singleton.PacketGetData(packet.ManagedPacket, _inBuff, ref dataSize); + => SNIProxy.GetInstance().PacketGetData(packet.ManagedPacket, _inBuff, ref dataSize); internal override void CreatePhysicalSNIHandle(string serverName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool parallel, string cachedFQDN, ref SQLDNSInfo pendingDNSInfo, bool isIntegratedSecurity) { - _sessionHandle = SNIProxy.Singleton.CreateConnectionHandle(this, serverName, ignoreSniOpenTimeout, timerExpire, out instanceName, ref spnBuffer, flushCache, async, parallel, isIntegratedSecurity, cachedFQDN, ref pendingDNSInfo); + _sessionHandle = SNIProxy.GetInstance().CreateConnectionHandle(this, serverName, ignoreSniOpenTimeout, timerExpire, out instanceName, ref spnBuffer, flushCache, async, parallel, isIntegratedSecurity, cachedFQDN, ref pendingDNSInfo); if (_sessionHandle == null) { _parser.ProcessSNIError(this); @@ -121,7 +121,7 @@ internal override PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint { throw ADP.ClosedConnectionError(); } - error = SNIProxy.Singleton.ReadSyncOverAsync(handle, out SNIPacket packet, timeoutRemaining); + error = SNIProxy.GetInstance().ReadSyncOverAsync(handle, out SNIPacket packet, timeoutRemaining); return PacketHandle.FromManagedPacket(packet); } @@ -142,12 +142,12 @@ internal override void ReleasePacket(PacketHandle syncReadPacket) internal override uint CheckConnection() { SNIHandle handle = Handle; - return handle == null ? TdsEnums.SNI_SUCCESS : SNIProxy.Singleton.CheckConnection(handle); + return handle == null ? TdsEnums.SNI_SUCCESS : SNIProxy.GetInstance().CheckConnection(handle); } internal override PacketHandle ReadAsync(SessionHandle handle, out uint error) { - error = SNIProxy.Singleton.ReadAsync(handle.ManagedHandle, out SNIPacket packet); + error = SNIProxy.GetInstance().ReadAsync(handle.ManagedHandle, out SNIPacket packet); return PacketHandle.FromManagedPacket(packet); } @@ -155,7 +155,7 @@ internal override PacketHandle CreateAndSetAttentionPacket() { PacketHandle packetHandle = GetResetWritePacket(TdsEnums.HEADER_LEN); #if DEBUG - Debug.Assert(packetHandle.ManagedPacket.IsActive, "rental packet is not active a serious pooling error may have occured"); + Debug.Assert(packetHandle.ManagedPacket.IsActive, "rental packet is not active a serious pooling error may have occurred"); #endif SetPacketData(packetHandle, SQL.AttentionHeader, TdsEnums.HEADER_LEN); packetHandle.ManagedPacket.IsOutOfBand = true; @@ -163,7 +163,7 @@ internal override PacketHandle CreateAndSetAttentionPacket() } internal override uint WritePacket(PacketHandle packet, bool sync) => - SNIProxy.Singleton.WritePacket(Handle, packet.ManagedPacket, sync); + SNIProxy.GetInstance().WritePacket(Handle, packet.ManagedPacket, sync); // No- Op in managed SNI internal override PacketHandle AddPacketToPendingList(PacketHandle packet) => packet; @@ -183,7 +183,7 @@ internal override PacketHandle GetResetWritePacket(int dataSize) SNIHandle handle = Handle; SNIPacket packet = handle.RentPacket(headerSize: handle.ReserveHeaderSize, dataSize: dataSize); #if DEBUG - Debug.Assert(packet.IsActive, "packet is not active, a serious pooling error may have occured"); + Debug.Assert(packet.IsActive, "packet is not active, a serious pooling error may have occurred"); #endif Debug.Assert(packet.ReservedHeaderSize == handle.ReserveHeaderSize, "failed to reserve header"); return PacketHandle.FromManagedPacket(packet); @@ -194,11 +194,11 @@ internal override void ClearAllWritePackets() Debug.Assert(_asyncWriteCount == 0, "Should not clear all write packets if there are packets pending"); } - internal override void SetPacketData(PacketHandle packet, byte[] buffer, int bytesUsed) => SNIProxy.Singleton.PacketSetData(packet.ManagedPacket, buffer, bytesUsed); + internal override void SetPacketData(PacketHandle packet, byte[] buffer, int bytesUsed) => SNIProxy.GetInstance().PacketSetData(packet.ManagedPacket, buffer, bytesUsed); - internal override uint SniGetConnectionId(ref Guid clientConnectionId) => SNIProxy.Singleton.GetConnectionId(Handle, ref clientConnectionId); + internal override uint SniGetConnectionId(ref Guid clientConnectionId) => SNIProxy.GetInstance().GetConnectionId(Handle, ref clientConnectionId); - internal override uint DisableSsl() => SNIProxy.Singleton.DisableSsl(Handle); + internal override uint DisableSsl() => SNIProxy.GetInstance().DisableSsl(Handle); internal override uint EnableMars(ref uint info) { @@ -211,9 +211,9 @@ internal override uint EnableMars(ref uint info) return TdsEnums.SNI_ERROR; } - internal override uint EnableSsl(ref uint info) => SNIProxy.Singleton.EnableSsl(Handle, info); + internal override uint EnableSsl(ref uint info) => SNIProxy.GetInstance().EnableSsl(Handle, info); - internal override uint SetConnectionBufferSize(ref uint unsignedPacketSize) => SNIProxy.Singleton.SetConnectionBufferSize(Handle, unsignedPacketSize); + internal override uint SetConnectionBufferSize(ref uint unsignedPacketSize) => SNIProxy.GetInstance().SetConnectionBufferSize(Handle, unsignedPacketSize); internal override uint GenerateSspiClientContext(byte[] receivedBuff, uint receivedLength, ref byte[] sendBuff, ref uint sendLength, byte[] _sniSpnBuffer) { @@ -221,7 +221,8 @@ internal override uint GenerateSspiClientContext(byte[] receivedBuff, uint recei { _sspiClientContextStatus = new SspiClientContextStatus(); } - SNIProxy.Singleton.GenSspiClientContext(_sspiClientContextStatus, receivedBuff, ref sendBuff, _sniSpnBuffer); + + SNIProxy.GetInstance().GenSspiClientContext(_sspiClientContextStatus, receivedBuff, ref sendBuff, _sniSpnBuffer); sendLength = (uint)(sendBuff != null ? sendBuff.Length : 0); return 0; } diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj index f812a47cd0..b6b55561ea 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj @@ -80,9 +80,6 @@ TDS - - CoreFx.Private.TestUtilities - Microsoft.DotNet.XUnitExtensions diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs index beb797abef..c21275ebde 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs @@ -24,7 +24,7 @@ public void ConnectionTest() } } - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer), nameof(PlatformDetection.IsNotArmProcess))] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArmProcess))] [ActiveIssue(4830, TestPlatforms.AnyUnix)] [PlatformSpecific(TestPlatforms.Windows)] public void IntegratedAuthConnectionTest() diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/AssemblyResourceManager.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/AssemblyResourceManager.cs index c277ca7da4..6ac9105cf5 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/AssemblyResourceManager.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/AssemblyResourceManager.cs @@ -20,7 +20,7 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests /// public class AssemblyResourceManager : DynamicObject { - private System.Reflection.Assembly _resourceAssembly; + private Assembly _resourceAssembly; public AssemblyResourceManager(Assembly assembly) { @@ -56,27 +56,19 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o private bool TryGetResourceValue(string resourceName, object[] args, out object result) { - if (PlatformDetection.IsNetNative) - { - result = string.Empty; - return true; - } - else - { - var type = _resourceAssembly.GetType("System.Strings"); - var info = type.GetProperty(resourceName, BindingFlags.NonPublic | BindingFlags.Static); + var type = _resourceAssembly.GetType("System.Strings"); + var info = type.GetProperty(resourceName, BindingFlags.NonPublic | BindingFlags.Static); - result = null; - if (info != null) + result = null; + if (info != null) + { + result = info.GetValue(null); + if (args != null) { - result = info.GetValue(null); - if (args != null) - { - result = string.Format((string)result, args); - } + result = string.Format((string)result, args); } - return result != null; } + return result != null; } } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj index 810775db77..d4a5f5f888 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj @@ -273,9 +273,6 @@ Utf8String - - CoreFx.Private.TestUtilities - diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ConnectionExceptionTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ConnectionExceptionTest.cs index 70726e4448..48a9be0b22 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ConnectionExceptionTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ConnectionExceptionTest.cs @@ -180,10 +180,9 @@ private TException VerifyConnectionFailure(Action connectAction, str TException ex = Assert.Throws(connectAction); // Some exception messages are different between Framework and Core - if (!PlatformDetection.IsFullFramework) - { - Assert.Contains(expectedExceptionMessage, ex.Message); - } +#if netfx + Assert.Contains(expectedExceptionMessage, ex.Message); +#endif Assert.True(exVerifier(ex), "FAILED Exception verifier failed on the exception."); return ex; diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/CoreFx.Private.TestUtilities.csproj b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/CoreFx.Private.TestUtilities.csproj deleted file mode 100644 index 1825cd49b0..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/CoreFx.Private.TestUtilities.csproj +++ /dev/null @@ -1,121 +0,0 @@ - - - CoreFx.Private.TestUtilities - CoreFx.Private.TestUtilities - {EBDB0247-CA43-4226-B7A1-8FEF21061D09} - netcoreapp - netfx - false - false - true - $(NoWarn);CS3021 - Test Utilities are not supported on this platform - false - Debug;Release;net46-Release;net46-Debug;netcoreapp2.1-Debug;netcoreapp2.1-Release;netcoreapp3.1-Debug;netcoreapp3.1-Release - AnyCPU;x86;x64 - $(ObjFolder)$(Configuration).$(Platform)\$(AssemblyName) - $(BinFolder)$(Configuration).$(Platform)\$(AssemblyName) - - - - - - - - - - - - - Common\System\PasteArguments.cs - - - - - - - Common\Interop\Windows\kernel32\Interop.GetCurrentProcess_IntPtr.cs - - - Common\System\PasteArguments.Windows.cs - - - Common\Interop\Windows\advapi32\Interop.OpenProcessToken_SafeAccessTokenHandle.cs - - - Common\Interop\Windows\Interop.Libraries.cs - - - Common\CoreLib\Interop\Windows\Kernel32\Interop.CloseHandle.cs - - - Common\Interop\Windows\advapi32\Interop.TOKEN_INFORMATION_CLASS.cs - - - Common\Interop\Windows\advapi32\Interop.GetTokenInformation_void.cs - - - Common\Interop\Windows\advapi32\Interop.TOKEN_ELEVATION.cs - - - Common\CoreLib\Interop\Windows\Interop.BOOL.cs - - - - - - Common\Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslVersion.cs - - - Common\System\PasteArguments.Unix.cs - - - - Common\Interop\Unix\Interop.GetEUid.cs - - - Common\Interop\Unix\Interop.Libraries.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/Resources/CoreFx.Private.TestUtilities.rd.xml b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/Resources/CoreFx.Private.TestUtilities.rd.xml deleted file mode 100644 index 05a1597d16..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/Resources/CoreFx.Private.TestUtilities.rd.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AdminHelpers.Unix.cs b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AdminHelpers.Unix.cs deleted file mode 100644 index dd20faab20..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AdminHelpers.Unix.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace System -{ - /// - /// Returns true if the current process is elevated (in Unix). - /// - public static partial class AdminHelpers - { - public unsafe static bool IsProcessElevated() - { - uint userId = Interop.Sys.GetEUid(); - return(userId == 0); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AdminHelpers.Windows.cs b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AdminHelpers.Windows.cs deleted file mode 100644 index 64173a9448..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AdminHelpers.Windows.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.ComponentModel; -using System.Runtime.InteropServices; -using System.Security.Principal; -using Microsoft.Win32.SafeHandles; - -namespace System -{ - public static partial class AdminHelpers - { - /// - /// Returns true if the current process is elevated (in Windows). - /// - public unsafe static bool IsProcessElevated() - { - IntPtr processHandle = Interop.Kernel32.GetCurrentProcess(); - SafeAccessTokenHandle token; - if (!Interop.Advapi32.OpenProcessToken(processHandle, TokenAccessLevels.Read, out token)) - { - throw new Win32Exception(Marshal.GetLastWin32Error(), "Open process token failed"); - } - - using (token) - { - Interop.Advapi32.TOKEN_ELEVATION elevation = new Interop.Advapi32.TOKEN_ELEVATION(); - uint ignore; - if (!Interop.Advapi32.GetTokenInformation( - token, - Interop.Advapi32.TOKEN_INFORMATION_CLASS.TokenElevation, - &elevation, - (uint)sizeof(Interop.Advapi32.TOKEN_ELEVATION), - out ignore)) - { - throw new Win32Exception(Marshal.GetLastWin32Error(), "Get token information failed"); - } - return elevation.TokenIsElevated != Interop.BOOL.FALSE; - } - } - - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AdminHelpers.cs b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AdminHelpers.cs deleted file mode 100644 index 526e6bd500..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AdminHelpers.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using Xunit; - -namespace System -{ - public static partial class AdminHelpers - { - /// - /// Runs the given command as sudo (for Unix). - /// - /// The command line to run as sudo - /// Returns the process exit code (0 typically means it is successful) - public static int RunAsSudo(string commandLine) - { - ProcessStartInfo startInfo = new ProcessStartInfo() - { - FileName = "sudo", - Arguments = commandLine - }; - - using (Process process = Process.Start(startInfo)) - { - Assert.True(process.WaitForExit(30000)); - return process.ExitCode; - } - } - - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/Net/PlatformDetection.Networking.cs b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/Net/PlatformDetection.Networking.cs deleted file mode 100644 index 0aa9faf541..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/Net/PlatformDetection.Networking.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System -{ - public static partial class PlatformDetection - { - // Windows 10 Insider Preview Build 16215 introduced the necessary APIs for the UAP version of - // ClientWebSocket.ReceiveAsync to consume partial message data as it arrives, without having to wait - // for "end of message" to be signaled. - public static bool ClientWebSocketPartialMessagesSupported => !IsUap || IsWindows10Version1709OrGreater; - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.NetFx.cs b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.NetFx.cs deleted file mode 100644 index b6a33810ca..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.NetFx.cs +++ /dev/null @@ -1,68 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using Xunit; -using Microsoft.Win32; -using System.Runtime.Versioning; - -namespace System -{ - public static partial class PlatformDetection - { - private static string FrameworkName => AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName; - private static Version TargetVersion => string.IsNullOrEmpty(FrameworkName) ? new Version(4, 5, 0, 0) : new FrameworkName(FrameworkName).Version; - - // The current full framework xunit runner is targeting 4.5.2 so we expect TargetsNetFx452OrLower to be true. - // When we update xunit runner in the future which may target recent framework version, TargetsNetFx452OrLower can start return - // false but we don't expect any code change though. - public static bool TargetsNetFx452OrLower => TargetVersion.CompareTo(new Version(4, 5, 3, 0)) < 0; - - public static bool IsNetfx462OrNewer => GetFrameworkVersion() >= new Version(4, 6, 2); - - public static bool IsNetfx470OrNewer => GetFrameworkVersion() >= new Version(4, 7, 0); - - public static bool IsNetfx471OrNewer => GetFrameworkVersion() >= new Version(4, 7, 1); - - public static bool IsNetfx472OrNewer => GetFrameworkVersion() >= new Version(4, 7, 2); - - public static string LibcRelease => ""; - public static string LibcVersion => ""; - - // To get the framework version we can do it throught the registry key and getting the Release value under the .NET Framework key. - // the mapping to each version can be found in: https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed - // everytime we ship a new version this method should be updated to include the new framework version. - private static Version GetFrameworkVersion() - { - using (RegistryKey ndpKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full")) - { - if (ndpKey != null) - { - int value = (int)(ndpKey.GetValue("Release") ?? 0); - if (value >= 461808) - return new Version(4, 7, 2); - if (value >= 461308) - return new Version(4, 7, 1); - if (value >= 460798) - return new Version(4, 7, 0); - if (value >= 394802) - return new Version(4, 6, 2); - if (value >= 394254) - return new Version(4, 6, 1); - if (value >= 393295) - return new Version(4, 6, 0); - if (value >= 379893) - return new Version(4, 5, 2); - if (value >= 378675) - return new Version(4, 5, 1); - if (value >= 378389) - return new Version(4, 5, 0); - - throw new NotSupportedException($"No 4.5 or later framework version detected, framework key value: {value}"); - } - - throw new NotSupportedException(@"No registry key found under 'SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full' to determine running framework version"); - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.NonNetFx.cs b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.NonNetFx.cs deleted file mode 100644 index 3d5dd55b4e..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.NonNetFx.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Runtime.InteropServices; - -namespace System -{ - public static partial class PlatformDetection - { - public static bool TargetsNetFx452OrLower => false; - public static bool IsNetfx462OrNewer => false; - public static bool IsNetfx470OrNewer => false; - public static bool IsNetfx471OrNewer => false; - public static bool IsNetfx472OrNewer => false; - - - [DllImport("libc", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] - private static extern IntPtr gnu_get_libc_release(); - - [DllImport("libc", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] - private static extern IntPtr gnu_get_libc_version(); - - /// - /// If gnulibc is available, returns the release, such as "stable". - /// Otherwise (eg., Windows, musl) returns "glibc_not_found". - /// - public static string LibcRelease - { - get - { - try - { - return Marshal.PtrToStringUTF8(gnu_get_libc_release()); - } - catch (Exception e) when (e is DllNotFoundException || e is EntryPointNotFoundException) - { - return "glibc_not_found"; - } - } - } - - /// - /// If gnulibc is available, returns the version, such as "2.22". - /// Otherwise (eg., Windows, musl) returns "glibc_not_found". (In future could run "ldd -version" for musl) - /// - public static string LibcVersion - { - get - { - try - { - return Marshal.PtrToStringUTF8(gnu_get_libc_version()); - } - catch (Exception e) when (e is DllNotFoundException || e is EntryPointNotFoundException) - { - return "glibc_not_found"; - } - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.Unix.cs b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.Unix.cs deleted file mode 100644 index 3d2ab7f404..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.Unix.cs +++ /dev/null @@ -1,244 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.IO; -using System.Xml.Linq; -using System.Runtime.InteropServices; -using System.Text; -using Xunit; - -namespace System -{ - public static partial class PlatformDetection - { - public static bool IsWindowsIoTCore => false; - public static bool IsWindows => false; - public static bool IsWindows7 => false; - public static bool IsWindows8x => false; - public static bool IsWindows10Version1607OrGreater => false; - public static bool IsWindows10Version1703OrGreater => false; - public static bool IsWindows10Version1709OrGreater => false; - public static bool IsWindows10Version1803OrGreater => false; - public static bool IsNotOneCoreUAP => true; - public static bool IsInAppContainer => false; - public static int WindowsVersion => -1; - - public static bool IsCentos6 => IsDistroAndVersion("centos", 6); - public static bool IsAlpine => IsDistroAndVersion("alpine"); - public static bool IsOpenSUSE => IsDistroAndVersion("opensuse"); - public static bool IsUbuntu => IsDistroAndVersion("ubuntu"); - public static bool IsDebian => IsDistroAndVersion("debian"); - public static bool IsDebian8 => IsDistroAndVersion("debian", 8); - public static bool IsUbuntu1404 => IsDistroAndVersion("ubuntu", 14, 4); - public static bool IsUbuntu1604 => IsDistroAndVersion("ubuntu", 16, 4); - public static bool IsUbuntu1704 => IsDistroAndVersion("ubuntu", 17, 4); - public static bool IsUbuntu1710 => IsDistroAndVersion("ubuntu", 17, 10); - public static bool IsUbuntu1710OrHigher => IsDistroAndVersionOrHigher("ubuntu", 17, 10); - public static bool IsUbuntu1804 => IsDistroAndVersion("ubuntu", 18, 04); - public static bool IsTizen => IsDistroAndVersion("tizen"); - public static bool IsFedora => IsDistroAndVersion("fedora"); - public static bool IsWindowsNanoServer => false; - public static bool IsWindowsServerCore => false; - public static bool IsWindowsAndElevated => false; - - // RedHat family covers RedHat and CentOS - public static bool IsRedHatFamily => IsRedHatFamilyAndVersion(); - public static bool IsNotRedHatFamily => !IsRedHatFamily; - public static bool IsRedHatFamily6 => IsRedHatFamilyAndVersion(6); - public static bool IsNotRedHatFamily6 => !IsRedHatFamily6; - public static bool IsRedHatFamily7 => IsRedHatFamilyAndVersion(7); - public static bool IsNotFedoraOrRedHatFamily => !IsFedora && !IsRedHatFamily; - - public static Version OSXVersion { get; } = ToVersion(Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment.OperatingSystemVersion); - - public static Version OpenSslVersion => RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? Interop.OpenSsl.OpenSslVersion : throw new PlatformNotSupportedException(); - - public static string GetDistroVersionString() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return "OSX Version=" + s_osxProductVersion.ToString(); - } - - DistroInfo v = GetDistroInfo(); - - return "Distro=" + v.Id + " VersionId=" + v.VersionId; - } - - private static readonly Version s_osxProductVersion = GetOSXProductVersion(); - - public static bool IsMacOsHighSierraOrHigher { get; } = - IsOSX && (s_osxProductVersion.Major > 10 || (s_osxProductVersion.Major == 10 && s_osxProductVersion.Minor >= 13)); - - private static readonly Version s_icuVersion = GetICUVersion(); - public static Version ICUVersion => s_icuVersion; - - private static Version GetICUVersion() - { - int ver = GlobalizationNative_GetICUVersion(); - return new Version( ver & 0xFF, - (ver >> 8) & 0xFF, - (ver >> 16) & 0xFF, - ver >> 24); - } - - static Version ToVersion(string versionString) - { - if (versionString.IndexOf('.') != -1) - return new Version(versionString); - - // minor version is required by Version - // let's default it to 0 - return new Version(int.Parse(versionString), 0); - } - - private static DistroInfo GetDistroInfo() => new DistroInfo() - { - Id = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment.OperatingSystem, - VersionId = ToVersion(Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment.OperatingSystemVersion) - }; - - private static bool IsRedHatFamilyAndVersion(int major = -1, int minor = -1, int build = -1, int revision = -1) - { - return IsDistroAndVersion((distro) => distro == "rhel" || distro == "centos", major, minor, build, revision); - } - - /// - /// Get whether the OS platform matches the given Linux distro and optional version. - /// - /// The distribution id. - /// The distro version. If omitted, compares the distro only. - /// Whether the OS platform matches the given Linux distro and optional version. - private static bool IsDistroAndVersion(string distroId, int major = -1, int minor = -1, int build = -1, int revision = -1) - { - return IsDistroAndVersion(distro => (distro == distroId), major, minor, build, revision); - } - - /// - /// Get whether the OS platform matches the given Linux distro and optional version is same or higher. - /// - /// The distribution id. - /// The distro version. If omitted, compares the distro only. - /// Whether the OS platform matches the given Linux distro and optional version is same or higher. - private static bool IsDistroAndVersionOrHigher(string distroId, int major = -1, int minor = -1, int build = -1, int revision = -1) - { - return IsDistroAndVersionOrHigher(distro => (distro == distroId), major, minor, build, revision); - } - - private static bool IsDistroAndVersion(Predicate distroPredicate, int major = -1, int minor = -1, int build = -1, int revision = -1) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - DistroInfo v = GetDistroInfo(); - if (distroPredicate(v.Id) && VersionEquivalentTo(major, minor, build, revision, v.VersionId)) - { - return true; - } - } - - return false; - } - - private static bool IsDistroAndVersionOrHigher(Predicate distroPredicate, int major = -1, int minor = -1, int build = -1, int revision = -1) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - DistroInfo v = GetDistroInfo(); - if (distroPredicate(v.Id) && VersionEquivalentToOrHigher(major, minor, build, revision, v.VersionId)) - { - return true; - } - } - - return false; - } - - private static bool VersionEquivalentTo(int major, int minor, int build, int revision, Version actualVersionId) - { - return (major == -1 || major == actualVersionId.Major) - && (minor == -1 || minor == actualVersionId.Minor) - && (build == -1 || build == actualVersionId.Build) - && (revision == -1 || revision == actualVersionId.Revision); - } - - private static bool VersionEquivalentToOrHigher(int major, int minor, int build, int revision, Version actualVersionId) - { - return - VersionEquivalentTo(major, minor, build, revision, actualVersionId) || - (actualVersionId.Major > major || - (actualVersionId.Major == major && actualVersionId.Minor > minor || - (actualVersionId.Minor == minor && actualVersionId.Build > build || - (actualVersionId.Build == build && actualVersionId.Revision > revision || - (actualVersionId.Revision == revision))))); - } - - private static Version GetOSXProductVersion() - { - try - { - if (IsOSX) - { - // - // - // ProductBuildVersion - // 17A330h - // ProductCopyright - // 1983-2017 Apple Inc. - // ProductName - // Mac OS X - // ProductUserVisibleVersion - // 10.13 - // ProductVersion - // 10.13 - // - // - - XElement dict = XDocument.Load("/System/Library/CoreServices/SystemVersion.plist").Root.Element("dict"); - if (dict != null) - { - foreach (XElement key in dict.Elements("key")) - { - if ("ProductVersion".Equals(key.Value)) - { - XElement stringElement = key.NextNode as XElement; - if (stringElement != null && stringElement.Name.LocalName.Equals("string")) - { - string versionString = stringElement.Value; - if (versionString != null) - { - return Version.Parse(versionString); - } - } - } - } - } - } - } - catch - { - } - - // In case of exception or couldn't get the version - return new Version(0, 0, 0); - } - - [DllImport("libc", SetLastError = true)] - private static extern int sysctlbyname(string ctlName, byte[] oldp, ref IntPtr oldpLen, byte[] newp, IntPtr newpLen); - - [DllImport("libc", SetLastError = true)] - internal static extern unsafe uint geteuid(); - - [DllImport("System.Globalization.Native", SetLastError = true)] - private static extern int GlobalizationNative_GetICUVersion(); - - public static bool IsSuperUser => geteuid() == 0; - - private struct DistroInfo - { - public string Id { get; set; } - public Version VersionId { get; set; } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.Windows.cs b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.Windows.cs deleted file mode 100644 index 607e52d7aa..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.Windows.cs +++ /dev/null @@ -1,272 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.IO; -using System.Runtime.InteropServices; -using System.Security; -using Microsoft.Win32; -using Xunit; - -namespace System -{ - public static partial class PlatformDetection - { - public static Version OSXVersion => throw new PlatformNotSupportedException(); - public static Version OpenSslVersion => throw new PlatformNotSupportedException(); - public static bool IsSuperUser => throw new PlatformNotSupportedException(); - public static bool IsCentos6 => false; - public static bool IsOpenSUSE => false; - public static bool IsUbuntu => false; - public static bool IsDebian => false; - public static bool IsAlpine => false; - public static bool IsDebian8 => false; - public static bool IsUbuntu1404 => false; - public static bool IsUbuntu1604 => false; - public static bool IsUbuntu1704 => false; - public static bool IsUbuntu1710 => false; - public static bool IsUbuntu1710OrHigher => false; - public static bool IsUbuntu1804 => false; - public static bool IsTizen => false; - public static bool IsNotFedoraOrRedHatFamily => true; - public static bool IsFedora => false; - public static bool IsWindowsNanoServer => (IsNotWindowsIoTCore && GetInstallationType().Equals("Nano Server", StringComparison.OrdinalIgnoreCase)); - public static bool IsWindowsServerCore => GetInstallationType().Equals("Server Core", StringComparison.OrdinalIgnoreCase); - public static int WindowsVersion => GetWindowsVersion(); - public static bool IsMacOsHighSierraOrHigher { get; } = false; - public static Version ICUVersion => new Version(0, 0, 0, 0); - public static bool IsRedHatFamily => false; - public static bool IsNotRedHatFamily => true; - public static bool IsRedHatFamily6 => false; - public static bool IsRedHatFamily7 => false; - public static bool IsNotRedHatFamily6 => true; - - public static bool IsWindows10Version1607OrGreater => - GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 14393; - public static bool IsWindows10Version1703OrGreater => - GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 15063; - public static bool IsWindows10Version1709OrGreater => - GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 16299; - public static bool IsWindows10Version1803OrGreater => - GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 17134; - - // Windows OneCoreUAP SKU doesn't have httpapi.dll - public static bool IsNotOneCoreUAP => - File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "httpapi.dll")); - - public static bool IsWindowsIoTCore - { - get - { - int productType = GetWindowsProductType(); - if ((productType == PRODUCT_IOTUAPCOMMERCIAL) || - (productType == PRODUCT_IOTUAP)) - { - return true; - } - return false; - } - } - - public static bool IsWindows => true; - public static bool IsWindows7 => GetWindowsVersion() == 6 && GetWindowsMinorVersion() == 1; - public static bool IsWindows8x => GetWindowsVersion() == 6 && (GetWindowsMinorVersion() == 2 || GetWindowsMinorVersion() == 3); - - public static string GetDistroVersionString() { return "WindowsProductType=" + GetWindowsProductType() + " WindowsInstallationType=" + GetInstallationType(); } - - private static int s_isInAppContainer = -1; - - public static bool IsInAppContainer - { - // This actually checks whether code is running in a modern app. - // Currently this is the only situation where we run in app container. - // If we want to distinguish the two cases in future, - // EnvironmentHelpers.IsAppContainerProcess in desktop code shows how to check for the AC token. - get - { - if (s_isInAppContainer != -1) - return s_isInAppContainer == 1; - - if (!IsWindows || IsWindows7) - { - s_isInAppContainer = 0; - return false; - } - - byte[] buffer = Array.Empty(); - uint bufferSize = 0; - try - { - int result = GetCurrentApplicationUserModelId(ref bufferSize, buffer); - switch (result) - { - case 15703: // APPMODEL_ERROR_NO_APPLICATION - s_isInAppContainer = 0; - break; - case 0: // ERROR_SUCCESS - case 122: // ERROR_INSUFFICIENT_BUFFER - // Success is actually insufficent buffer as we're really only looking for - // not NO_APPLICATION and we're not actually giving a buffer here. The - // API will always return NO_APPLICATION if we're not running under a - // WinRT process, no matter what size the buffer is. - s_isInAppContainer = 1; - break; - default: - throw new InvalidOperationException($"Failed to get AppId, result was {result}."); - } - } - catch (Exception e) - { - // We could catch this here, being friendly with older portable surface area should we - // desire to use this method elsewhere. - if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal)) - { - // API doesn't exist, likely pre Win8 - s_isInAppContainer = 0; - } - else - { - throw; - } - } - - return s_isInAppContainer == 1; - } - } - - private static int s_isWindowsElevated = -1; - - public static bool IsWindowsAndElevated - { - get - { - if (s_isWindowsElevated != -1) - return s_isWindowsElevated == 1; - - if (!IsWindows || IsInAppContainer) - { - s_isWindowsElevated = 0; - return false; - } - - IntPtr processToken; - Assert.True(OpenProcessToken(GetCurrentProcess(), TOKEN_READ, out processToken)); - - try - { - uint tokenInfo; - uint returnLength; - Assert.True(GetTokenInformation( - processToken, TokenElevation, out tokenInfo, sizeof(uint), out returnLength)); - - s_isWindowsElevated = tokenInfo == 0 ? 0 : 1; - } - finally - { - CloseHandle(processToken); - } - - return s_isWindowsElevated == 1; - } - } - - private static string GetInstallationType() - { - string key = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion"; - string value = ""; - - try - { - value = (string)Registry.GetValue(key, "InstallationType", defaultValue: ""); - } - catch (Exception e) when (e is SecurityException || e is InvalidCastException || e is PlatformNotSupportedException /* UAP */) - { - } - - return value; - } - - private static int GetWindowsProductType() - { - Assert.True(GetProductInfo(Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor, 0, 0, out int productType)); - return productType; - } - - private static int GetWindowsMinorVersion() - { - RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX(); - osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); - Assert.Equal(0, RtlGetVersion(out osvi)); - return (int)osvi.dwMinorVersion; - } - - private static int GetWindowsBuildNumber() - { - RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX(); - osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); - Assert.Equal(0, RtlGetVersion(out osvi)); - return (int)osvi.dwBuildNumber; - } - - private const uint TokenElevation = 20; - private const uint STANDARD_RIGHTS_READ = 0x00020000; - private const uint TOKEN_QUERY = 0x0008; - private const uint TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY; - - [DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)] - private static extern bool GetTokenInformation( - IntPtr TokenHandle, - uint TokenInformationClass, - out uint TokenInformation, - uint TokenInformationLength, - out uint ReturnLength); - - private const int PRODUCT_IOTUAP = 0x0000007B; - private const int PRODUCT_IOTUAPCOMMERCIAL = 0x00000083; - - [DllImport("kernel32.dll", SetLastError = false)] - private static extern bool GetProductInfo( - int dwOSMajorVersion, - int dwOSMinorVersion, - int dwSpMajorVersion, - int dwSpMinorVersion, - out int pdwReturnedProductType - ); - - [DllImport("ntdll.dll")] - private static extern int RtlGetVersion(out RTL_OSVERSIONINFOEX lpVersionInformation); - - [StructLayout(LayoutKind.Sequential)] - private struct RTL_OSVERSIONINFOEX - { - internal uint dwOSVersionInfoSize; - internal uint dwMajorVersion; - internal uint dwMinorVersion; - internal uint dwBuildNumber; - internal uint dwPlatformId; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - internal string szCSDVersion; - } - - private static int GetWindowsVersion() - { - RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX(); - osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); - Assert.Equal(0, RtlGetVersion(out osvi)); - return (int)osvi.dwMajorVersion; - } - - [DllImport("kernel32.dll", ExactSpelling = true)] - private static extern int GetCurrentApplicationUserModelId(ref uint applicationUserModelIdLength, byte[] applicationUserModelId); - - [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] - private static extern bool CloseHandle(IntPtr handle); - - [DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)] - private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle); - - // The process handle does NOT need closing - [DllImport("kernel32.dll", ExactSpelling = true)] - private static extern IntPtr GetCurrentProcess(); - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.cs b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.cs deleted file mode 100644 index d1b8a63e98..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/PlatformDetection.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.IO; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace System -{ - public static partial class PlatformDetection - { - // - // Do not use the " { get; } = " pattern here. Having all the initialization happen in the type initializer - // means that one exception anywhere means all tests using PlatformDetection fail. If you feel a value is worth latching, - // do it in a way that failures don't cascade. - // - - public static bool HasWindowsShell => IsWindows && IsNotWindowsServerCore && IsNotWindowsNanoServer && IsNotWindowsIoTCore; - public static bool IsUap => IsInAppContainer || IsNetNative; - public static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase); - public static bool IsNetNative => RuntimeInformation.FrameworkDescription.StartsWith(".NET Native", StringComparison.OrdinalIgnoreCase); - public static bool IsNetCore => RuntimeInformation.FrameworkDescription.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase); - public static bool IsOSX => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); - public static bool IsFreeBSD => RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD")); - public static bool IsNetBSD => RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD")); - public static bool IsNotWindows8x => !IsWindows8x; - public static bool IsNotWindowsNanoServer => !IsWindowsNanoServer; - public static bool IsNotWindowsServerCore => !IsWindowsServerCore; - public static bool IsNotWindowsIoTCore => !IsWindowsIoTCore; - public static bool IsDrawingSupported => (IsNotWindowsNanoServer && IsNotWindowsIoTCore); - public static bool IsArmProcess => RuntimeInformation.ProcessArchitecture == Architecture.Arm; - public static bool IsNotArmProcess => !IsArmProcess; - - public static bool IsNotInAppContainer => !IsInAppContainer; - public static bool IsWinRTSupported => IsWindows && !IsWindows7; - public static bool IsNotWinRTSupported => !IsWinRTSupported; - public static bool IsNotMacOsHighSierraOrHigher => !IsMacOsHighSierraOrHigher; - - public static bool IsDomainJoinedMachine => !Environment.MachineName.Equals(Environment.UserDomainName, StringComparison.OrdinalIgnoreCase); - - public static bool IsNotNetNative => !IsNetNative; - - // Windows - Schannel supports alpn from win8.1/2012 R2 and higher. - // Linux - OpenSsl supports alpn from openssl 1.0.2 and higher. - // OSX - SecureTransport doesn't expose alpn APIs. #30492 - public static bool SupportsAlpn => (IsWindows && !IsWindows7) || - (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && - (OpenSslVersion.Major >= 1 && (OpenSslVersion.Minor >= 1 || OpenSslVersion.Build >= 2))); - - // Officially, .NET Native only supports processes running in an AppContainer. However, the majority of tests still work fine - // in a normal Win32 process and we often do so as running in an AppContainer imposes a substantial tax in debuggability - // and investigatability. This predicate is used in ConditionalFacts to disable the specific tests that really need to be - // running in AppContainer when running on .NetNative. - public static bool IsNotNetNativeRunningAsConsoleApp => !(IsNetNative && !IsInAppContainer); - - private static Lazy m_isWindowsSubsystemForLinux = new Lazy(GetIsWindowsSubsystemForLinux); - - public static bool IsWindowsSubsystemForLinux => m_isWindowsSubsystemForLinux.Value; - public static bool IsNotWindowsSubsystemForLinux => !IsWindowsSubsystemForLinux; - - private static bool GetIsWindowsSubsystemForLinux() - { - // https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364 - - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - const string versionFile = "/proc/version"; - if (File.Exists(versionFile)) - { - string s = File.ReadAllText(versionFile); - - if (s.Contains("Microsoft") || s.Contains("WSL")) - { - return true; - } - } - } - - return false; - } - - private static Lazy s_largeArrayIsNotSupported = new Lazy(IsLargeArrayNotSupported); - - [MethodImpl(MethodImplOptions.NoOptimization)] - private static bool IsLargeArrayNotSupported() - { - try - { - var tmp = new byte[int.MaxValue]; - return tmp == null; - } - catch (OutOfMemoryException) - { - return true; - } - } - - public static bool IsNotIntMaxValueArrayIndexSupported => s_largeArrayIsNotSupported.Value; - - public static bool IsNonZeroLowerBoundArraySupported - { - get - { - if (s_lazyNonZeroLowerBoundArraySupported == null) - { - bool nonZeroLowerBoundArraysSupported = false; - try - { - Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 5 }); - nonZeroLowerBoundArraysSupported = true; - } - catch (PlatformNotSupportedException) - { - } - s_lazyNonZeroLowerBoundArraySupported = Tuple.Create(nonZeroLowerBoundArraysSupported); - } - return s_lazyNonZeroLowerBoundArraySupported.Item1; - } - } - - private static volatile Tuple s_lazyNonZeroLowerBoundArraySupported; - - public static bool IsReflectionEmitSupported = !PlatformDetection.IsNetNative; - - // Tracked in: https://github.com/dotnet/corert/issues/3643 in case we change our mind about this. - public static bool IsInvokingStaticConstructorsSupported => !PlatformDetection.IsNetNative; - - // System.Security.Cryptography.Xml.XmlDsigXsltTransform.GetOutput() relies on XslCompiledTransform which relies - // heavily on Reflection.Emit - public static bool IsXmlDsigXsltTransformSupported => !PlatformDetection.IsUap; - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/TestEnvironment.cs b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/TestEnvironment.cs deleted file mode 100644 index f083cd862b..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/TestEnvironment.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System -{ - public static partial class TestEnvironment - { - /// - /// Check if the stress mode is enabled. - /// - /// true if the environment variable COREFX_STRESS set to '1' or 'true'. returns false otherwise - public static bool IsStressModeEnabled - { - get - { - string value = Environment.GetEnvironmentVariable("COREFX_STRESS"); - return value != null && (value == "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase)); - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/TheoryExtensions.cs b/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/TheoryExtensions.cs deleted file mode 100644 index ed682e41a7..0000000000 --- a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/TheoryExtensions.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using Xunit; - -namespace System -{ - public static class TheoryExtensions - { - /// - /// Converts an IEnumerable into an Xunit theory compatible enumerable. - /// - public static TheoryData ToTheoryData(this IEnumerable data) - { - // Returning TheoryData rather than IEnumerable directly should - // encourage discover and usage of TheoryData classes for more - // complicated theories. Slightly easier to type as well. - return new TheoryDataAdapter(data.Select(d => new object[] { d })); - } - - private class TheoryDataAdapter : TheoryData, IEnumerable - { - private IEnumerable _data; - - public TheoryDataAdapter(IEnumerable data) - { - _data = data; - } - - public new IEnumerator GetEnumerator() => _data.GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AssertExtensions.cs b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.DotNet.XUnitExtensions/Extensions/AssertExtensions.cs similarity index 100% rename from src/Microsoft.Data.SqlClient/tests/tools/CoreFx.Private.TestUtilities/System/AssertExtensions.cs rename to src/Microsoft.Data.SqlClient/tests/tools/Microsoft.DotNet.XUnitExtensions/Extensions/AssertExtensions.cs diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSid.cs b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.DotNet.XUnitExtensions/Extensions/PlatformDetection.cs similarity index 52% rename from src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSid.cs rename to src/Microsoft.Data.SqlClient/tests/tools/Microsoft.DotNet.XUnitExtensions/Extensions/PlatformDetection.cs index d13108bfb0..1d089151aa 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Common/src/Interop/Unix/System.Native/Interop.GetSid.cs +++ b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.DotNet.XUnitExtensions/Extensions/PlatformDetection.cs @@ -4,11 +4,11 @@ using System.Runtime.InteropServices; -internal static partial class Interop +namespace System { - internal static partial class Sys + public static partial class PlatformDetection { - [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetSid")] - internal static extern int GetSid(int pid); + public static bool IsArmProcess => RuntimeInformation.ProcessArchitecture == Architecture.Arm; + public static bool IsNotArmProcess => !IsArmProcess; } } diff --git a/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.DotNet.XUnitExtensions/Microsoft.DotNet.XUnitExtensions.csproj b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.DotNet.XUnitExtensions/Microsoft.DotNet.XUnitExtensions.csproj index 5fcdbc135e..cc26e34f12 100644 --- a/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.DotNet.XUnitExtensions/Microsoft.DotNet.XUnitExtensions.csproj +++ b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.DotNet.XUnitExtensions/Microsoft.DotNet.XUnitExtensions.csproj @@ -26,6 +26,8 @@ + + @@ -46,6 +48,7 @@ + diff --git a/tools/props/Versions.props b/tools/props/Versions.props index 34ccbbaf0a..2fb7c487c7 100644 --- a/tools/props/Versions.props +++ b/tools/props/Versions.props @@ -56,6 +56,7 @@ 15.9.0 3.1.0 12.0.3 + 4.3.0 4.3.0 4.5.0 4.6.0 From 9519efaea925c00f54d1c61ccea674f303a0545d Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Fri, 28 Aug 2020 22:34:18 -0700 Subject: [PATCH 19/24] Tests | Test Lab changes to create/drop databases with pipeline jobs (#712) --- .gitignore | 2 +- build.proj | 1 + src/Microsoft.Data.SqlClient.sln | 102 ++++++++++ .../SqlConnectionStringBuilderTest.cs | 2 +- .../ManualTests/DataCommon/DataTestUtility.cs | 169 +++++----------- ....Data.SqlClient.ManualTesting.Tests.csproj | 9 +- .../SQL/ExceptionTest/ExceptionTest.cs | 7 +- .../SQL/ParameterTest/ParametersTest.cs | 1 - .../SQL/SqlBulkCopyTest/Bug84548.cs | 4 +- .../SQL/SqlBulkCopyTest/Bug85007.cs | 4 +- .../SQL/SqlBulkCopyTest/OrderHint.cs | 8 +- .../SQL/SqlBulkCopyTest/OrderHintAsync.cs | 8 +- .../OrderHintDuplicateColumn.cs | 8 +- .../OrderHintIdentityColumn.cs | 8 +- .../OrderHintMissingTargetColumn.cs | 8 +- .../SqlBulkCopyTest/OrderHintTransaction.cs | 8 +- .../SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs | 92 +++++---- .../SQL/UdtTest/SqlServerTypesTest.cs | 3 +- ...crosoft.Data.SqlClient.ExtUtilities.csproj | 11 ++ .../Runner.cs | 36 ++++ .../SqlDbManager.cs | 187 ++++++++++++++++++ .../Config.cs | 59 ++++++ ...rosoft.Data.SqlClient.TestUtilities.csproj | 21 ++ .../Utils.cs | 46 +++++ .../config.default.json | 3 +- tools/props/Versions.props | 1 + tools/testsql/createNorthwindDb.sql | 2 +- 27 files changed, 593 insertions(+), 217 deletions(-) create mode 100644 src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.ExtUtilities/Microsoft.Data.SqlClient.ExtUtilities.csproj create mode 100644 src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.ExtUtilities/Runner.cs create mode 100644 src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.ExtUtilities/SqlDbManager.cs create mode 100644 src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Config.cs create mode 100644 src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Microsoft.Data.SqlClient.TestUtilities.csproj create mode 100644 src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Utils.cs rename src/Microsoft.Data.SqlClient/tests/{ManualTests => tools/Microsoft.Data.SqlClient.TestUtilities}/config.default.json (89%) diff --git a/.gitignore b/.gitignore index a8dac2d5c7..df05bd9b0f 100644 --- a/.gitignore +++ b/.gitignore @@ -359,4 +359,4 @@ MigrationBackup/ .nuget/ # Config Json file -src/Microsoft.Data.SqlClient/tests/ManualTests/config.json +**/config.json diff --git a/build.proj b/build.proj index 32f1734db9..a1a6df03a2 100644 --- a/build.proj +++ b/build.proj @@ -40,6 +40,7 @@ + diff --git a/src/Microsoft.Data.SqlClient.sln b/src/Microsoft.Data.SqlClient.sln index 3b709a16cf..855baeedaa 100644 --- a/src/Microsoft.Data.SqlClient.sln +++ b/src/Microsoft.Data.SqlClient.sln @@ -168,6 +168,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Data.SqlClient.Do EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Data.SqlClient.NSLibrary", "Microsoft.Data.SqlClient\tests\NSLibrary\Microsoft.Data.SqlClient.NSLibrary.csproj", "{E7336BFB-8521-423A-A140-3123F9065C5D}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Data.SqlClient.TestUtilities", "Microsoft.Data.SqlClient\tests\tools\Microsoft.Data.SqlClient.TestUtilities\Microsoft.Data.SqlClient.TestUtilities.csproj", "{89D6D382-9B36-43C9-A912-03802FDA8E36}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Data.SqlClient.ExtUtilities", "Microsoft.Data.SqlClient\tests\tools\Microsoft.Data.SqlClient.ExtUtilities\Microsoft.Data.SqlClient.ExtUtilities.csproj", "{E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -1032,6 +1036,102 @@ Global {E7336BFB-8521-423A-A140-3123F9065C5D}.Release|x64.Build.0 = Release|x64 {E7336BFB-8521-423A-A140-3123F9065C5D}.Release|x86.ActiveCfg = Release|x86 {E7336BFB-8521-423A-A140-3123F9065C5D}.Release|x86.Build.0 = Release|x86 + {89D6D382-9B36-43C9-A912-03802FDA8E36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.Debug|Any CPU.Build.0 = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.Debug|x64.ActiveCfg = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.Debug|x64.Build.0 = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.Debug|x86.ActiveCfg = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.Debug|x86.Build.0 = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.net46-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.net46-Debug|Any CPU.Build.0 = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.net46-Debug|x64.ActiveCfg = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.net46-Debug|x64.Build.0 = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.net46-Debug|x86.ActiveCfg = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.net46-Debug|x86.Build.0 = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.net46-Release|Any CPU.ActiveCfg = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.net46-Release|Any CPU.Build.0 = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.net46-Release|x64.ActiveCfg = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.net46-Release|x64.Build.0 = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.net46-Release|x86.ActiveCfg = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.net46-Release|x86.Build.0 = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp2.1-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp2.1-Debug|Any CPU.Build.0 = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp2.1-Debug|x64.ActiveCfg = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp2.1-Debug|x64.Build.0 = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp2.1-Debug|x86.ActiveCfg = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp2.1-Debug|x86.Build.0 = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp2.1-Release|Any CPU.ActiveCfg = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp2.1-Release|Any CPU.Build.0 = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp2.1-Release|x64.ActiveCfg = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp2.1-Release|x64.Build.0 = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp2.1-Release|x86.ActiveCfg = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp2.1-Release|x86.Build.0 = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp3.1-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp3.1-Debug|Any CPU.Build.0 = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp3.1-Debug|x64.ActiveCfg = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp3.1-Debug|x64.Build.0 = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp3.1-Debug|x86.ActiveCfg = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp3.1-Debug|x86.Build.0 = Debug|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp3.1-Release|Any CPU.ActiveCfg = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp3.1-Release|Any CPU.Build.0 = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp3.1-Release|x64.ActiveCfg = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp3.1-Release|x64.Build.0 = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp3.1-Release|x86.ActiveCfg = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.netcoreapp3.1-Release|x86.Build.0 = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.Release|Any CPU.ActiveCfg = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.Release|Any CPU.Build.0 = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.Release|x64.ActiveCfg = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.Release|x64.Build.0 = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.Release|x86.ActiveCfg = Release|Any CPU + {89D6D382-9B36-43C9-A912-03802FDA8E36}.Release|x86.Build.0 = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.Debug|x64.ActiveCfg = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.Debug|x64.Build.0 = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.Debug|x86.ActiveCfg = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.Debug|x86.Build.0 = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.net46-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.net46-Debug|Any CPU.Build.0 = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.net46-Debug|x64.ActiveCfg = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.net46-Debug|x64.Build.0 = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.net46-Debug|x86.ActiveCfg = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.net46-Debug|x86.Build.0 = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.net46-Release|Any CPU.ActiveCfg = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.net46-Release|Any CPU.Build.0 = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.net46-Release|x64.ActiveCfg = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.net46-Release|x64.Build.0 = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.net46-Release|x86.ActiveCfg = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.net46-Release|x86.Build.0 = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp2.1-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp2.1-Debug|Any CPU.Build.0 = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp2.1-Debug|x64.ActiveCfg = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp2.1-Debug|x64.Build.0 = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp2.1-Debug|x86.ActiveCfg = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp2.1-Debug|x86.Build.0 = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp2.1-Release|Any CPU.ActiveCfg = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp2.1-Release|Any CPU.Build.0 = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp2.1-Release|x64.ActiveCfg = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp2.1-Release|x64.Build.0 = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp2.1-Release|x86.ActiveCfg = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp2.1-Release|x86.Build.0 = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp3.1-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp3.1-Debug|Any CPU.Build.0 = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp3.1-Debug|x64.ActiveCfg = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp3.1-Debug|x64.Build.0 = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp3.1-Debug|x86.ActiveCfg = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp3.1-Debug|x86.Build.0 = Debug|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp3.1-Release|Any CPU.ActiveCfg = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp3.1-Release|Any CPU.Build.0 = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp3.1-Release|x64.ActiveCfg = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp3.1-Release|x64.Build.0 = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp3.1-Release|x86.ActiveCfg = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.netcoreapp3.1-Release|x86.Build.0 = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.Release|Any CPU.Build.0 = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.Release|x64.ActiveCfg = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.Release|x64.Build.0 = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.Release|x86.ActiveCfg = Release|Any CPU + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1063,6 +1163,8 @@ Global {5A7600BD-AED8-44AB-8F2A-7CB33A8D9C02} = {71F356DC-DFA3-4163-8BFE-D268722CE189} {833157E1-1E53-4908-B4CB-5C5507A44582} = {0CC4817A-12F3-4357-912C-09315FAAD008} {E7336BFB-8521-423A-A140-3123F9065C5D} = {0CC4817A-12F3-4357-912C-09315FAAD008} + {89D6D382-9B36-43C9-A912-03802FDA8E36} = {0CC4817A-12F3-4357-912C-09315FAAD008} + {E4C08DCE-DC29-4FEB-B655-1E7287DB5A2B} = {0CC4817A-12F3-4357-912C-09315FAAD008} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {01D48116-37A2-4D33-B9EC-94793C702431} diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionStringBuilderTest.cs b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionStringBuilderTest.cs index e1eae7b608..449e8bca09 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionStringBuilderTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionStringBuilderTest.cs @@ -38,7 +38,7 @@ public class SqlConnectionStringBuilderTest [InlineData("Encrypt = true")] [InlineData("Enlist = false")] [InlineData("Initial Catalog = Northwind; Failover Partner = randomserver.sys.local")] - [InlineData("Initial Catalog = Northwind")] + [InlineData("Initial Catalog = tempdb")] [InlineData("Integrated Security = true")] [InlineData("Trusted_Connection = false")] [InlineData("Max Pool Size = 50")] diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs index 60b506533e..e65d4e6693 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs @@ -13,7 +13,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Identity.Client; -using Newtonsoft.Json; +using Microsoft.Data.SqlClient.TestUtilities; using Xunit; namespace Microsoft.Data.SqlClient.ManualTesting.Tests @@ -55,104 +55,63 @@ public static class DataTestUtility public const string AKVKeyName = "TestSqlClientAzureKeyVaultProvider"; private const string ManagedNetworkingAppContextSwitch = "Switch.Microsoft.Data.SqlClient.UseManagedNetworkingOnWindows"; - private static readonly string[] AzureSqlServerEndpoints = {".database.windows.net", - ".database.cloudapi.de", - ".database.usgovcloudapi.net", - ".database.chinacloudapi.cn"}; - private static Dictionary AvailableDatabases; private static TraceEventListener TraceListener; - private class Config - { - public string TCPConnectionString = null; - public string NPConnectionString = null; - public string TCPConnectionStringHGSVBS = null; - public string TCPConnectionStringAASVBS = null; - public string TCPConnectionStringAASSGX = null; - public string AADAuthorityURL = null; - public string AADPasswordConnectionString = null; - public string AADServicePrincipalId = null; - public string AADServicePrincipalSecret = null; - public string AzureKeyVaultURL = null; - public string AzureKeyVaultClientId = null; - public string AzureKeyVaultClientSecret = null; - public bool EnclaveEnabled = false; - public bool TracingEnabled = false; - public bool SupportsIntegratedSecurity = false; - public bool SupportsLocalDb = false; - public bool SupportsFileStream = false; - public bool UseManagedSNIOnWindows = false; - public string DNSCachingConnString = null; - public string DNSCachingServerCR = null; // this is for the control ring - public string DNSCachingServerTR = null; // this is for the tenant ring - public bool IsDNSCachingSupportedCR = false; // this is for the control ring - public bool IsDNSCachingSupportedTR = false; // this is for the tenant ring - public string EnclaveAzureDatabaseConnString = null; - } - static DataTestUtility() { - using (StreamReader r = new StreamReader("config.json")) - { - string json = r.ReadToEnd(); - Config c = JsonConvert.DeserializeObject(json); - - NPConnectionString = c.NPConnectionString; - TCPConnectionString = c.TCPConnectionString; - TCPConnectionStringHGSVBS = c.TCPConnectionStringHGSVBS; - TCPConnectionStringAASVBS = c.TCPConnectionStringAASVBS; - TCPConnectionStringAASSGX = c.TCPConnectionStringAASSGX; - AADAuthorityURL = c.AADAuthorityURL; - AADPasswordConnectionString = c.AADPasswordConnectionString; - AADServicePrincipalId = c.AADServicePrincipalId; - AADServicePrincipalSecret = c.AADServicePrincipalSecret; - SupportsLocalDb = c.SupportsLocalDb; - SupportsIntegratedSecurity = c.SupportsIntegratedSecurity; - SupportsFileStream = c.SupportsFileStream; - EnclaveEnabled = c.EnclaveEnabled; - TracingEnabled = c.TracingEnabled; - UseManagedSNIOnWindows = c.UseManagedSNIOnWindows; - - DNSCachingConnString = c.DNSCachingConnString; - DNSCachingServerCR = c.DNSCachingServerCR; - DNSCachingServerTR = c.DNSCachingServerTR; - IsDNSCachingSupportedCR = c.IsDNSCachingSupportedCR; - IsDNSCachingSupportedTR = c.IsDNSCachingSupportedTR; - - EnclaveAzureDatabaseConnString = c.EnclaveAzureDatabaseConnString; - - if (TracingEnabled) - { - TraceListener = new DataTestUtility.TraceEventListener(); - } + Config c = Config.Load(); + NPConnectionString = c.NPConnectionString; + TCPConnectionString = c.TCPConnectionString; + TCPConnectionStringHGSVBS = c.TCPConnectionStringHGSVBS; + TCPConnectionStringAASVBS = c.TCPConnectionStringAASVBS; + TCPConnectionStringAASSGX = c.TCPConnectionStringAASSGX; + AADAuthorityURL = c.AADAuthorityURL; + AADPasswordConnectionString = c.AADPasswordConnectionString; + AADServicePrincipalId = c.AADServicePrincipalId; + AADServicePrincipalSecret = c.AADServicePrincipalSecret; + SupportsLocalDb = c.SupportsLocalDb; + SupportsIntegratedSecurity = c.SupportsIntegratedSecurity; + SupportsFileStream = c.SupportsFileStream; + EnclaveEnabled = c.EnclaveEnabled; + TracingEnabled = c.TracingEnabled; + UseManagedSNIOnWindows = c.UseManagedSNIOnWindows; + DNSCachingConnString = c.DNSCachingConnString; + DNSCachingServerCR = c.DNSCachingServerCR; + DNSCachingServerTR = c.DNSCachingServerTR; + IsDNSCachingSupportedCR = c.IsDNSCachingSupportedCR; + IsDNSCachingSupportedTR = c.IsDNSCachingSupportedTR; + EnclaveAzureDatabaseConnString = c.EnclaveAzureDatabaseConnString; - if (UseManagedSNIOnWindows) - { - AppContext.SetSwitch(ManagedNetworkingAppContextSwitch, true); - Console.WriteLine($"App Context switch {ManagedNetworkingAppContextSwitch} enabled on {Environment.OSVersion}"); - } + if (TracingEnabled) + { + TraceListener = new DataTestUtility.TraceEventListener(); + } - if (IsAADPasswordConnStrSetup() && IsAADAuthorityURLSetup()) - { - string username = RetrieveValueFromConnStr(AADPasswordConnectionString, new string[] { "User ID", "UID" }); - string password = RetrieveValueFromConnStr(AADPasswordConnectionString, new string[] { "Password", "PWD" }); - AADAccessToken = GenerateAccessToken(AADAuthorityURL, username, password); - } + if (UseManagedSNIOnWindows) + { + AppContext.SetSwitch(ManagedNetworkingAppContextSwitch, true); + Console.WriteLine($"App Context switch {ManagedNetworkingAppContextSwitch} enabled on {Environment.OSVersion}"); + } - string url = c.AzureKeyVaultURL; - Uri AKVBaseUri = null; - if (!string.IsNullOrEmpty(url) && Uri.TryCreate(url, UriKind.Absolute, out AKVBaseUri)) - { - AKVBaseUri = new Uri(AKVBaseUri, "/"); - AKVBaseUrl = AKVBaseUri.AbsoluteUri; - AKVUrl = (new Uri(AKVBaseUri, $"/keys/{AKVKeyName}")).AbsoluteUri; - } + if (IsAADPasswordConnStrSetup() && IsAADAuthorityURLSetup()) + { + string username = RetrieveValueFromConnStr(AADPasswordConnectionString, new string[] { "User ID", "UID" }); + string password = RetrieveValueFromConnStr(AADPasswordConnectionString, new string[] { "Password", "PWD" }); + AADAccessToken = GenerateAccessToken(AADAuthorityURL, username, password); + } - AKVClientId = c.AzureKeyVaultClientId; - AKVClientSecret = c.AzureKeyVaultClientSecret; + string url = c.AzureKeyVaultURL; + if (!string.IsNullOrEmpty(url) && Uri.TryCreate(url, UriKind.Absolute, out Uri AKVBaseUri)) + { + AKVBaseUri = new Uri(AKVBaseUri, "/"); + AKVBaseUrl = AKVBaseUri.AbsoluteUri; + AKVUrl = (new Uri(AKVBaseUri, $"/keys/{AKVKeyName}")).AbsoluteUri; } + AKVClientId = c.AzureKeyVaultClientId; + AKVClientSecret = c.AzureKeyVaultClientSecret; + if (EnclaveEnabled) { if (!string.IsNullOrEmpty(TCPConnectionStringHGSVBS)) @@ -206,6 +165,7 @@ public static IEnumerable ConnectionStrings } } } + private static string GenerateAccessToken(string authorityURL, string aADAuthUserID, string aADAuthPassword) { return AcquireTokenAsync(authorityURL, aADAuthUserID, aADAuthPassword).Result; @@ -292,7 +252,7 @@ public static bool IsSupportedDataClassification() public static bool IsEnclaveAzureDatabaseSetup() { return EnclaveEnabled && !string.IsNullOrEmpty(EnclaveAzureDatabaseConnString); - } + } public static bool IsUdtTestDatabasePresent() => IsDatabasePresent(UdtTestDbName); @@ -323,7 +283,7 @@ public static bool IsAADAuthorityURLSetup() public static bool IsNotAzureServer() { - return AreConnStringsSetup() ? !DataTestUtility.IsAzureSqlServer(new SqlConnectionStringBuilder((DataTestUtility.TCPConnectionString)).DataSource) : true; + return !AreConnStringsSetup() || !Utils.IsAzureSqlServer(new SqlConnectionStringBuilder((DataTestUtility.TCPConnectionString)).DataSource); } public static bool IsAKVSetupAvailable() @@ -435,35 +395,6 @@ public static string GetAccessToken() public static bool IsFileStreamSetup() => SupportsFileStream; - // This method assumes dataSource parameter is in TCP connection string format. - public static bool IsAzureSqlServer(string dataSource) - { - int i = dataSource.LastIndexOf(','); - if (i >= 0) - { - dataSource = dataSource.Substring(0, i); - } - - i = dataSource.LastIndexOf('\\'); - if (i >= 0) - { - dataSource = dataSource.Substring(0, i); - } - - // trim redundant whitespace - dataSource = dataSource.Trim(); - - // check if servername end with any azure endpoints - for (i = 0; i < AzureSqlServerEndpoints.Length; i++) - { - if (dataSource.EndsWith(AzureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } - return false; - } - private static bool CheckException(Exception ex, string exceptionMessage, bool innerExceptionMustBeNull) where TException : Exception { return ((ex != null) && (ex is TException) && diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj index d4a5f5f888..877791abe3 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj @@ -13,9 +13,6 @@ $(ObjFolder)$(Configuration).$(Platform).$(AssemblyName) $(BinFolder)$(Configuration).$(Platform).$(AssemblyName) - - - @@ -203,10 +200,6 @@ PreserveNewest data.xml - - PreserveNewest - config.json - PreserveNewest MultipleResultsTest.bsl @@ -261,6 +254,7 @@ + Address @@ -286,7 +280,6 @@ - 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 47b8b081de..6f7d9ad6cd 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ExceptionTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ExceptionTest.cs @@ -57,7 +57,8 @@ private static bool EmployeesTableHasFullTextIndex() using (SqlCommand cmd = conn.CreateCommand()) { conn.Open(); - cmd.CommandText = "SELECT object_id FROM sys.fulltext_indexes WHERE object_id = object_id('Northwind.dbo.Employees')"; + string db = conn.DataSource; + cmd.CommandText = $"SELECT object_id FROM sys.fulltext_indexes WHERE object_id = object_id('{db}.dbo.Employees')"; return (cmd.ExecuteScalar() != null); } @@ -92,7 +93,7 @@ public static void WarningsBeforeRowsTest() sqlConnection.FireInfoMessageEventOnUserErrors = messagesOnErrors; // These queries should return warnings because AND here is a noise word. - SqlCommand cmd = new SqlCommand("select FirstName from Northwind.dbo.Employees where contains(FirstName, '\"Anne AND\"')" + orderClause, sqlConnection); + SqlCommand cmd = new SqlCommand("select FirstName from Employees where contains(FirstName, '\"Anne AND\"')" + orderClause, sqlConnection); using (SqlDataReader reader = cmd.ExecuteReader()) { Assert.True(reader.HasRows, "FAILED: SqlDataReader.HasRows is not correct (should be TRUE)"); @@ -107,7 +108,7 @@ public static void WarningsBeforeRowsTest() } hitWarnings = false; - cmd.CommandText = "select FirstName from Northwind.dbo.Employees where contains(FirstName, '\"NotARealPerson AND\"')" + orderClause; + cmd.CommandText = "select FirstName from Employees where contains(FirstName, '\"NotARealPerson AND\"')" + orderClause; using (SqlDataReader reader = cmd.ExecuteReader()) { Assert.False(reader.HasRows, "FAILED: SqlDataReader.HasRows is not correct (should be FALSE)"); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs index 0132b464c1..865fd62cab 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs @@ -250,7 +250,6 @@ public static void Test_WithGuidValue_ShouldReturnGuid() public static void TestParametersWithDatatablesTVPInsert() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString); - builder.InitialCatalog = "tempdb"; int x = 4, y = 5; DataTable table = new DataTable { Columns = { { "x", typeof(int) }, { "y", typeof(int) } }, Rows = { { x, y } } }; diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug84548.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug84548.cs index b41feb55fc..48c65a4247 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug84548.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug84548.cs @@ -40,7 +40,7 @@ public static void Test(string srcConstr, string dstConstr, string targettable) srcConn.Open(); // First copy the customer ID list across - SqlCommand customerCommand = new SqlCommand("SELECT CustomerID from Northwind..Customers", srcConn); + SqlCommand customerCommand = new SqlCommand("SELECT CustomerID from Customers", srcConn); using (DbDataReader reader = customerCommand.ExecuteReader()) { using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn)) @@ -50,7 +50,7 @@ public static void Test(string srcConstr, string dstConstr, string targettable) } } - SqlCommand srcCmd = new SqlCommand("select OrderID, CustomerID from Northwind..Orders where OrderId = 10643", srcConn); + SqlCommand srcCmd = new SqlCommand("select OrderID, CustomerID from Orders where OrderId = 10643", srcConn); using (DbDataReader reader = srcCmd.ExecuteReader()) { using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn)) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug85007.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug85007.cs index f9983bc8d7..26d9db5bda 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug85007.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/Bug85007.cs @@ -50,7 +50,7 @@ public static void Test(string srcConstr, string dstConstr, string dstTable) ") ON [PRIMARY]"); using (SqlConnection srcConn = new SqlConnection(srcConstr)) - using (SqlCommand customerCmd = new SqlCommand("SELECT CustomerID from Northwind..Customers", srcConn)) + using (SqlCommand customerCmd = new SqlCommand("SELECT CustomerID from Customers", srcConn)) { srcConn.Open(); @@ -90,7 +90,7 @@ public static void Test(string srcConstr, string dstConstr, string dstTable) ColumnMappings.Add("ShipCountry", "ShipCountry"); bulkcopy.WriteToServer(reader); - + DataTestUtility.AssertEqualsWithDescription(bulkcopy.RowsCopied, 830, "Unexpected number of rows."); } Helpers.VerifyResults(dstConn, dstTable, 14, 830); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHint.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHint.cs index 7145679431..fbfbb57ecd 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHint.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHint.cs @@ -19,10 +19,8 @@ public class OrderHint private static readonly string sourceQueryTemplate2 = "SELECT LastName, FirstName FROM {0}"; private static readonly string getRowCountQueryTemplate = "SELECT COUNT(*) FROM {0}"; - public static void Test(string srcConstr, string dstTable, string dstTable2) + public static void Test(string connStr, string dstTable, string dstTable2) { - srcConstr = (new SqlConnectionStringBuilder(srcConstr) { InitialCatalog = "Northwind" }).ConnectionString; - string dstConstr = (new SqlConnectionStringBuilder(srcConstr)).ConnectionString; string sourceQuery = string.Format(sourceQueryTemplate, sourceTable); string sourceQuery2 = string.Format(sourceQueryTemplate2, sourceTable2); string initialQuery = string.Format(initialQueryTemplate, dstTable); @@ -30,13 +28,13 @@ public static void Test(string srcConstr, string dstTable, string dstTable2) string getRowCountQuery = string.Format(getRowCountQueryTemplate, sourceTable); string getRowCountQuery2 = string.Format(getRowCountQueryTemplate, sourceTable2); - using (SqlConnection dstConn = new SqlConnection(dstConstr)) + using (SqlConnection dstConn = new SqlConnection(connStr)) using (SqlCommand dstCmd = dstConn.CreateCommand()) { dstConn.Open(); Helpers.TryExecute(dstCmd, initialQuery); Helpers.TryExecute(dstCmd, initialQuery2); - using (SqlConnection srcConn = new SqlConnection(srcConstr)) + using (SqlConnection srcConn = new SqlConnection(connStr)) using (SqlCommand srcCmd = new SqlCommand(getRowCountQuery, srcConn)) { srcConn.Open(); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintAsync.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintAsync.cs index d9c4515428..c818200864 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintAsync.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintAsync.cs @@ -27,10 +27,8 @@ public static void Test(string srcConstr, string dstTable, string dstTable2) Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status); } - public static async Task TestAsync(string srcConstr, string dstTable, string dstTable2) + public static async Task TestAsync(string connStr, string dstTable, string dstTable2) { - srcConstr = (new SqlConnectionStringBuilder(srcConstr) { InitialCatalog = "Northwind" }).ConnectionString; - string dstConstr = (new SqlConnectionStringBuilder(srcConstr)).ConnectionString; string sourceQuery = string.Format(sourceQueryTemplate, sourceTable); string sourceQuery2 = string.Format(sourceQueryTemplate2, sourceTable2); string initialQuery = string.Format(initialQueryTemplate, dstTable); @@ -38,13 +36,13 @@ public static async Task TestAsync(string srcConstr, string dstTable, string dst string getRowCountQuery = string.Format(getRowCountQueryTemplate, sourceTable); string getRowCountQuery2 = string.Format(getRowCountQueryTemplate, sourceTable2); - using (SqlConnection dstConn = new SqlConnection(dstConstr)) + using (SqlConnection dstConn = new SqlConnection(connStr)) using (SqlCommand dstCmd = dstConn.CreateCommand()) { await dstConn.OpenAsync(); Helpers.TryExecute(dstCmd, initialQuery); Helpers.TryExecute(dstCmd, initialQuery2); - using (SqlConnection srcConn = new SqlConnection(srcConstr)) + using (SqlConnection srcConn = new SqlConnection(connStr)) using (SqlCommand srcCmd = new SqlCommand(getRowCountQuery, srcConn)) { await srcConn.OpenAsync(); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintDuplicateColumn.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintDuplicateColumn.cs index 59e82a8a97..9e535ccae1 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintDuplicateColumn.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintDuplicateColumn.cs @@ -15,20 +15,18 @@ public class OrderHintDuplicateColumn private static readonly string sourceQueryTemplate = "SELECT CustomerID, CompanyName, ContactName FROM {0}"; private static readonly string getRowCountQueryTemplate = "SELECT COUNT(*) FROM {0}"; - public static void Test(string srcConstr, string dstTable) + public static void Test(string connStr, string dstTable) { - srcConstr = (new SqlConnectionStringBuilder(srcConstr) { InitialCatalog = "Northwind" }).ConnectionString; - string dstConstr = (new SqlConnectionStringBuilder(srcConstr)).ConnectionString; string initialQuery = string.Format(initialQueryTemplate, dstTable); string sourceQuery = string.Format(sourceQueryTemplate, sourceTable); string getRowCountQuery = string.Format(getRowCountQueryTemplate, sourceTable); - using (SqlConnection dstConn = new SqlConnection(dstConstr)) + using (SqlConnection dstConn = new SqlConnection(connStr)) using (SqlCommand dstCmd = dstConn.CreateCommand()) { dstConn.Open(); Helpers.TryExecute(dstCmd, initialQuery); - using (SqlConnection srcConn = new SqlConnection(srcConstr)) + using (SqlConnection srcConn = new SqlConnection(connStr)) using (SqlCommand srcCmd = new SqlCommand(getRowCountQuery, srcConn)) { srcConn.Open(); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintIdentityColumn.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintIdentityColumn.cs index a95c13ad36..04cd1977b4 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintIdentityColumn.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintIdentityColumn.cs @@ -14,20 +14,18 @@ public class OrderHintIdentityColumn private static readonly string sourceQueryTemplate = "SELECT CustomerId, CompanyName, ContactName FROM {0}"; private static readonly string getRowCountQueryTemplate = "SELECT COUNT(*) FROM {0}"; - public static void Test(string srcConstr, string dstTable) + public static void Test(string connStr, string dstTable) { - srcConstr = (new SqlConnectionStringBuilder(srcConstr) { InitialCatalog = "Northwind" }).ConnectionString; - string dstConstr = (new SqlConnectionStringBuilder(srcConstr)).ConnectionString; string sourceQuery = string.Format(sourceQueryTemplate, sourceTable); string initialQuery = string.Format(initialQueryTemplate, dstTable); string getRowCountQuery = string.Format(getRowCountQueryTemplate, sourceTable); - using (SqlConnection dstConn = new SqlConnection(dstConstr)) + using (SqlConnection dstConn = new SqlConnection(connStr)) using (SqlCommand dstCmd = dstConn.CreateCommand()) { dstConn.Open(); Helpers.TryExecute(dstCmd, initialQuery); - using (SqlConnection srcConn = new SqlConnection(srcConstr)) + using (SqlConnection srcConn = new SqlConnection(connStr)) using (SqlCommand srcCmd = new SqlCommand(getRowCountQuery, srcConn)) { srcConn.Open(); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintMissingTargetColumn.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintMissingTargetColumn.cs index dcfeb6e311..46a7f39eee 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintMissingTargetColumn.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintMissingTargetColumn.cs @@ -14,19 +14,17 @@ public class OrderHintMissingTargetColumn private static readonly string initialQueryTemplate = "create table {0} (CustomerID nvarchar(50), CompanyName nvarchar(50), ContactName nvarchar(50))"; private static readonly string sourceQueryTemplate = "SELECT CustomerID, CompanyName, ContactName FROM {0}"; - public static void Test(string srcConstr, string dstTable) + public static void Test(string connStr, string dstTable) { - srcConstr = (new SqlConnectionStringBuilder(srcConstr) { InitialCatalog = "Northwind" }).ConnectionString; - string dstConstr = (new SqlConnectionStringBuilder(srcConstr)).ConnectionString; string initialQuery = string.Format(initialQueryTemplate, dstTable); string sourceQuery = string.Format(sourceQueryTemplate, sourceTable); - using (SqlConnection dstConn = new SqlConnection(dstConstr)) + using (SqlConnection dstConn = new SqlConnection(connStr)) using (SqlCommand dstCmd = dstConn.CreateCommand()) { dstConn.Open(); Helpers.TryExecute(dstCmd, initialQuery); - using (SqlConnection srcConn = new SqlConnection(srcConstr)) + using (SqlConnection srcConn = new SqlConnection(connStr)) using (SqlCommand srcCmd = new SqlCommand(sourceQuery, srcConn)) { srcConn.Open(); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintTransaction.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintTransaction.cs index 73dae137aa..94bd28b02a 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintTransaction.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/OrderHintTransaction.cs @@ -12,14 +12,12 @@ class OrderHintTransaction private static readonly string initialQueryTemplate = "create table {0} (CustomerID nvarchar(50), CompanyName nvarchar(50), ContactName nvarchar(50))"; private static readonly string sourceQueryTemplate = "SELECT CustomerID, CompanyName, ContactName FROM {0}"; - public static void Test(string srcConstr, string dstTable) + public static void Test(string connStr, string dstTable) { - srcConstr = (new SqlConnectionStringBuilder(srcConstr) { InitialCatalog = "Northwind" }).ConnectionString; - string dstConstr = (new SqlConnectionStringBuilder(srcConstr)).ConnectionString; string initialQuery = string.Format(initialQueryTemplate, dstTable); string sourceQuery = string.Format(sourceQueryTemplate, sourceTable); - using (SqlConnection dstConn = new SqlConnection(dstConstr)) + using (SqlConnection dstConn = new SqlConnection(connStr)) using (SqlCommand dstCmd = dstConn.CreateCommand()) { dstConn.Open(); @@ -27,7 +25,7 @@ public static void Test(string srcConstr, string dstTable) dstCmd.Transaction = txn; Helpers.TryExecute(dstCmd, initialQuery); - using (SqlConnection srcConn = new SqlConnection(srcConstr)) + using (SqlConnection srcConn = new SqlConnection(connStr)) using (SqlCommand srcCmd = new SqlCommand(sourceQuery, srcConn)) { srcConn.Open(); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs index 965dfde9f1..9c1d60e07c 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs @@ -9,15 +9,13 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public class SqlBulkCopyTest { - private string srcConstr = null; - private string dstConstr = null; - private static bool IsAzureServer() => DataTestUtility.IsAzureSqlServer(new SqlConnectionStringBuilder((DataTestUtility.TCPConnectionString)).DataSource); + private string _connStr = null; + private static bool IsAzureServer() => !DataTestUtility.IsNotAzureServer(); private static bool AreConnectionStringsSetup() => DataTestUtility.AreConnStringsSetup(); public SqlBulkCopyTest() { - srcConstr = DataTestUtility.TCPConnectionString; - dstConstr = (new SqlConnectionStringBuilder(srcConstr) { InitialCatalog = "tempdb" }).ConnectionString; + _connStr = DataTestUtility.TCPConnectionString; } public string AddGuid(string stringin) @@ -35,254 +33,254 @@ public void AzureDistributedTransactionTest() [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopyAllFromReaderTest() { - CopyAllFromReader.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyAllFromReader")); + CopyAllFromReader.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_CopyAllFromReader")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopyAllFromReader1Test() { - CopyAllFromReader1.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyAllFromReader1")); + CopyAllFromReader1.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_CopyAllFromReader1")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopyMultipleReadersTest() { - CopyMultipleReaders.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyMultipleReaders")); + CopyMultipleReaders.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_CopyMultipleReaders")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopySomeFromReaderTest() { - CopySomeFromReader.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopySomeFromReader")); + CopySomeFromReader.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_CopySomeFromReader")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopySomeFromDataTableTest() { - CopySomeFromDataTable.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopySomeFromDataTable")); + CopySomeFromDataTable.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_CopySomeFromDataTable")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopySomeFromRowArrayTest() { - CopySomeFromRowArray.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopySomeFromRowArray")); + CopySomeFromRowArray.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_CopySomeFromRowArray")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopyWithEventTest() { - CopyWithEvent.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyWithEvent")); + CopyWithEvent.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_CopyWithEvent")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopyWithEvent1Test() { - CopyWithEvent1.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyWithEvent1")); + CopyWithEvent1.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_CopyWithEvent1")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void InvalidAccessFromEventTest() { - InvalidAccessFromEvent.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_InvalidAccessFromEvent")); + InvalidAccessFromEvent.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_InvalidAccessFromEvent")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void Bug84548Test() { - Bug84548.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Bug84548")); + Bug84548.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_Bug84548")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void MissingTargetTableTest() { - MissingTargetTable.Test(srcConstr, dstConstr, AddGuid("@SqlBulkCopyTest_MissingTargetTable")); + MissingTargetTable.Test(_connStr, _connStr, AddGuid("@SqlBulkCopyTest_MissingTargetTable")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void MissingTargetColumnTest() { - MissingTargetColumn.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_MissingTargetColumn")); + MissingTargetColumn.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_MissingTargetColumn")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void Bug85007Test() { - Bug85007.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Bug85007")); + Bug85007.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_Bug85007")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CheckConstraintsTest() { - CheckConstraints.Test(dstConstr, AddGuid("SqlBulkCopyTest_Extensionsrc"), AddGuid("SqlBulkCopyTest_Extensiondst")); + CheckConstraints.Test(_connStr, AddGuid("SqlBulkCopyTest_Extensionsrc"), AddGuid("SqlBulkCopyTest_Extensiondst")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void TransactionTest() { - Transaction.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction0")); + Transaction.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_Transaction0")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void Transaction1Test() { - Transaction1.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction1")); + Transaction1.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_Transaction1")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void Transaction2Test() { - Transaction2.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction2")); + Transaction2.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_Transaction2")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void Transaction3Test() { - Transaction3.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction3")); + Transaction3.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_Transaction3")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void Transaction4Test() { - Transaction4.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction4")); + Transaction4.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_Transaction4")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopyVariantsTest() { - CopyVariants.Test(dstConstr, AddGuid("SqlBulkCopyTest_Variants")); + CopyVariants.Test(_connStr, AddGuid("SqlBulkCopyTest_Variants")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void Bug98182Test() { - Bug98182.Test(dstConstr, AddGuid("@SqlBulkCopyTest_Bug98182 ")); + Bug98182.Test(_connStr, AddGuid("@SqlBulkCopyTest_Bug98182 ")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void FireTriggerTest() { - FireTrigger.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_FireTrigger")); + FireTrigger.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_FireTrigger")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void ErrorOnRowsMarkedAsDeletedTest() { - ErrorOnRowsMarkedAsDeleted.Test(dstConstr, AddGuid("SqlBulkCopyTest_ErrorOnRowsMarkedAsDeleted")); + ErrorOnRowsMarkedAsDeleted.Test(_connStr, AddGuid("SqlBulkCopyTest_ErrorOnRowsMarkedAsDeleted")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void SpecialCharacterNamesTest() { - SpecialCharacterNames.Test(srcConstr, dstConstr, AddGuid("@SqlBulkCopyTest_SpecialCharacterNames")); + SpecialCharacterNames.Test(_connStr, _connStr, AddGuid("@SqlBulkCopyTest_SpecialCharacterNames")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void Bug903514Test() { - Bug903514.Test(dstConstr, AddGuid("SqlBulkCopyTest_Bug903514")); + Bug903514.Test(_connStr, AddGuid("SqlBulkCopyTest_Bug903514")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void ColumnCollationTest() { - ColumnCollation.Test(dstConstr, AddGuid("SqlBulkCopyTest_ColumnCollation")); + ColumnCollation.Test(_connStr, AddGuid("SqlBulkCopyTest_ColumnCollation")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopyAllFromReaderAsyncTest() { - CopyAllFromReaderAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest1")); //Async + Reader + CopyAllFromReaderAsync.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_AsyncTest1")); //Async + Reader } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopySomeFromRowArrayAsyncTest() { - CopySomeFromRowArrayAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest2")); //Async + Some Rows + CopySomeFromRowArrayAsync.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_AsyncTest2")); //Async + Some Rows } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopySomeFromDataTableAsyncTest() { - CopySomeFromDataTableAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest3")); //Async + Some Table + CopySomeFromDataTableAsync.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_AsyncTest3")); //Async + Some Table } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopyWithEventAsyncTest() { - CopyWithEventAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest4")); //Async + Rows + Notification + CopyWithEventAsync.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_AsyncTest4")); //Async + Rows + Notification } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void CopyAllFromReaderCancelAsyncTest() { - CopyAllFromReaderCancelAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest5")); //Async + Reader + cancellation token + CopyAllFromReaderCancelAsync.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_AsyncTest5")); //Async + Reader + cancellation token } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void CopyAllFromReaderConnectionClosedAsyncTest() { - CopyAllFromReaderConnectionClosedAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest6")); //Async + Reader + Connection closed + CopyAllFromReaderConnectionClosedAsync.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_AsyncTest6")); //Async + Reader + Connection closed } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void CopyAllFromReaderConnectionClosedOnEventAsyncTest() { - CopyAllFromReaderConnectionClosedOnEventAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest7")); //Async + Reader + Connection closed during the event + CopyAllFromReaderConnectionClosedOnEventAsync.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_AsyncTest7")); //Async + Reader + Connection closed during the event } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void TransactionTestAsyncTest() { - TransactionTestAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_TransactionTestAsync")); //Async + Transaction rollback + TransactionTestAsync.Test(_connStr, _connStr, AddGuid("SqlBulkCopyTest_TransactionTestAsync")); //Async + Transaction rollback } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public void CopyWidenNullInexactNumericsTest() { - CopyWidenNullInexactNumerics.Test(srcConstr, dstConstr); + CopyWidenNullInexactNumerics.Test(_connStr, _connStr); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void DestinationTableNameWithSpecialCharTest() { - DestinationTableNameWithSpecialChar.Test(srcConstr, AddGuid("SqlBulkCopyTest_DestinationTableNameWithSpecialChar")); + DestinationTableNameWithSpecialChar.Test(_connStr, AddGuid("SqlBulkCopyTest_DestinationTableNameWithSpecialChar")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void OrderHintTest() { - OrderHint.Test(srcConstr, AddGuid("SqlBulkCopyTest_OrderHint"), AddGuid("SqlBulkCopyTest_OrderHint2")); + OrderHint.Test(_connStr, AddGuid("SqlBulkCopyTest_OrderHint"), AddGuid("SqlBulkCopyTest_OrderHint2")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void OrderHintAsyncTest() { - OrderHintAsync.Test(srcConstr, AddGuid("SqlBulkCopyTest_OrderHintAsync"), AddGuid("SqlBulkCopyTest_OrderHintAsync2")); + OrderHintAsync.Test(_connStr, AddGuid("SqlBulkCopyTest_OrderHintAsync"), AddGuid("SqlBulkCopyTest_OrderHintAsync2")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void OrderHintMissingTargetColumnTest() { - OrderHintMissingTargetColumn.Test(srcConstr, AddGuid("SqlBulkCopyTest_OrderHintMissingTargetColumn")); + OrderHintMissingTargetColumn.Test(_connStr, AddGuid("SqlBulkCopyTest_OrderHintMissingTargetColumn")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void OrderHintDuplicateColumnTest() { - OrderHintDuplicateColumn.Test(srcConstr, AddGuid("SqlBulkCopyTest_OrderHintDuplicateColumn")); + OrderHintDuplicateColumn.Test(_connStr, AddGuid("SqlBulkCopyTest_OrderHintDuplicateColumn")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void OrderHintTransactionTest() { - OrderHintTransaction.Test(srcConstr, AddGuid("SqlBulkCopyTest_OrderHintTransaction")); + OrderHintTransaction.Test(_connStr, AddGuid("SqlBulkCopyTest_OrderHintTransaction")); } [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] [ActiveIssue(12219)] public void OrderHintIdentityColumnTest() { - OrderHintIdentityColumn.Test(srcConstr, AddGuid("SqlBulkCopyTest_OrderHintIdentityColumn")); + OrderHintIdentityColumn.Test(_connStr, AddGuid("SqlBulkCopyTest_OrderHintIdentityColumn")); } } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/SqlServerTypesTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/SqlServerTypesTest.cs index bdb75348dc..ae29f5e6c4 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/SqlServerTypesTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/SqlServerTypesTest.cs @@ -19,6 +19,7 @@ public static class SqlServerTypesTest [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static void GetSchemaTableTest() { + string db = new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString).InitialCatalog; using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString)) using (SqlCommand cmd = new SqlCommand("select hierarchyid::Parse('/1/') as col0", conn)) { @@ -32,7 +33,7 @@ public static void GetSchemaTableTest() DataTestUtility.AssertEqualsWithDescription("col0", columnName, "Unexpected column name."); string dataTypeName = (string)schemaTable.Rows[0][schemaTable.Columns["DataTypeName"]]; - DataTestUtility.AssertEqualsWithDescription("Northwind.sys.hierarchyid", dataTypeName, "Unexpected data type name."); + DataTestUtility.AssertEqualsWithDescription($"{db}.sys.hierarchyid".ToUpper(), dataTypeName.ToUpper(), "Unexpected data type name."); string udtAssemblyName = (string)schemaTable.Rows[0][schemaTable.Columns["UdtAssemblyQualifiedName"]]; Assert.True(udtAssemblyName?.StartsWith("Microsoft.SqlServer.Types.SqlHierarchyId"), "Unexpected UDT assembly name: " + udtAssemblyName); diff --git a/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.ExtUtilities/Microsoft.Data.SqlClient.ExtUtilities.csproj b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.ExtUtilities/Microsoft.Data.SqlClient.ExtUtilities.csproj new file mode 100644 index 0000000000..614ab2d91e --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.ExtUtilities/Microsoft.Data.SqlClient.ExtUtilities.csproj @@ -0,0 +1,11 @@ + + + Exe + netcoreapp3.1 + Microsoft.Data.SqlClient.ExtUtilities.Runner + + + + + + diff --git a/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.ExtUtilities/Runner.cs b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.ExtUtilities/Runner.cs new file mode 100644 index 0000000000..9eda28368f --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.ExtUtilities/Runner.cs @@ -0,0 +1,36 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +namespace Microsoft.Data.SqlClient.ExtUtilities +{ + public static class Runner + { + /// + /// Runs utility tools for SqlClient Tests + /// + /// + /// SqlDbManager Tools: + /// [0] = CreateDatabase, DropDatabase + /// [1] = Name of Database + /// + public static void Main(string [] args) + { + if (args == null || args.Length < 1) + { + throw new ArgumentException("Utility name not provided."); + } + + if (args[0].Contains("Database")) + { + SqlDbManager.Run(args); + } + else + { + throw new ArgumentException("Utility not supported."); + } + } + } +} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.ExtUtilities/SqlDbManager.cs b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.ExtUtilities/SqlDbManager.cs new file mode 100644 index 0000000000..e5e460ec7e --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.ExtUtilities/SqlDbManager.cs @@ -0,0 +1,187 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.Data.SqlClient.TestUtilities; +using Microsoft.SqlServer.Management.Common; + +namespace Microsoft.Data.SqlClient.ExtUtilities +{ + public static class SqlDbManager + { + private static Config s_configJson; + private static Dictionary s_activeConnectionStrings; + + private const string DB_Northwind = "Northwind"; + private const string DB_Master = "master"; + private const string NorthWindScriptPath = @"../../../../../tools/testsql/createNorthwindDb.sql"; + private const string ConfigPath = @"../Microsoft.Data.SqlClient.TestUtilities/config.json"; + + private const string TCPConnectionString = "TCPConnectionString"; + private const string NPConnectionString = "NPConnectionString"; + private const string TCPConnectionStringAASSGX = "TCPConnectionStringAASSGX"; + private const string TCPConnectionStringAASVBS = "TCPConnectionStringAASVBS"; + private const string TCPConnectionStringHGSVBS = "TCPConnectionStringHGSVBS"; + + /// + /// Creates/ drops database as requested. + /// + /// + /// [0] = CreateDatabase, DropDatabase + /// [1] = Name of Database + /// + public static void Run(string[] args) + { + if (args == null || args.Length < 2) + { + throw new InvalidArgumentException("Incomplete arguments provided."); + } + + try + { + var dbName = args[1]; + s_configJson = Config.Load(ConfigPath); + LoadActiveConnectionStrings(); + + foreach (KeyValuePair activeConnString in s_activeConnectionStrings) + { + SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder((activeConnString.Value)); + if (!Utils.IsAzureSqlServer(builder.DataSource)) + { + builder.InitialCatalog = DB_Master; + using (SqlConnection conn = new SqlConnection(builder.ConnectionString)) + { + SqlServer.Management.Smo.Server server = new SqlServer.Management.Smo.Server(new ServerConnection(conn)); + ServerConnection context = server.ConnectionContext; + + if (args[0] == "CreateDatabase") + { + // We do not create database for HGS-VBS since SQL Server for AASVBS and HGSVBS connection strings is same. + // Do not create database for NP connection string, since server is always same as TCP + if (activeConnString.Key != TCPConnectionStringHGSVBS && activeConnString.Key != NPConnectionString) + { + //Create a new database + CreateDatabase(dbName, context); + Console.WriteLine($"Database [{dbName}] created successfully in {builder.DataSource}"); + } + // Update Config.json accordingly + builder.InitialCatalog = dbName; + UpdateConfig(activeConnString.Key, builder); + } + else if (args[0] == "DropDatabase") + { + // We do not drop database for HGS-VBS since SQL Server for AASVBS and HGSVBS connection strings is same. + // Do not drop database for NP connection string, since server is always same as TCP + if (activeConnString.Key != TCPConnectionStringHGSVBS && activeConnString.Key != NPConnectionString) + { + // Drop Northwind for test run. + DropIfExistsDatabase(dbName, context); + Console.WriteLine($"Database [{dbName}] dropped successfully in {builder.DataSource}"); + } + } + else + { + Console.WriteLine($"Utility '{args[0]}' not supported in {builder.DataSource}"); + } + } + } + else + { + Console.WriteLine($"Database Utilities are not supported for Azure SQL in {activeConnString.Key}"); + } + } + if (args[0] == "CreateDatabase") + { + // Update config.json with Initial Catalog = for "Active Connection Strings" + Config.UpdateConfig(s_configJson, ConfigPath); + } + } + catch (Exception e) + { + throw new Exception($"{args[0]} execution failed with Error: {e.Message}"); + } + } + + private static void LoadActiveConnectionStrings() + { + s_activeConnectionStrings = new Dictionary(); + if (!string.IsNullOrEmpty(s_configJson.TCPConnectionString)) + { + s_activeConnectionStrings.Add(TCPConnectionString, s_configJson.TCPConnectionString); + } + if (!string.IsNullOrEmpty(s_configJson.NPConnectionString)) + { + s_activeConnectionStrings.Add(NPConnectionString, s_configJson.NPConnectionString); + } + if (s_configJson.EnclaveEnabled) + { + if (!string.IsNullOrEmpty(s_configJson.TCPConnectionStringAASSGX)) + { + s_activeConnectionStrings.Add(TCPConnectionStringAASSGX, s_configJson.TCPConnectionStringAASSGX); + } + if (!string.IsNullOrEmpty(s_configJson.TCPConnectionStringAASVBS)) + { + s_activeConnectionStrings.Add(TCPConnectionStringAASVBS, s_configJson.TCPConnectionStringAASVBS); + } + if (!string.IsNullOrEmpty(s_configJson.TCPConnectionStringHGSVBS)) + { + s_activeConnectionStrings.Add(TCPConnectionStringHGSVBS, s_configJson.TCPConnectionStringHGSVBS); + } + } + } + + private static void UpdateConfig(string key, SqlConnectionStringBuilder builder) + { + switch (key) + { + case TCPConnectionString: + s_configJson.TCPConnectionString = builder.ConnectionString; + break; + case NPConnectionString: + s_configJson.NPConnectionString = builder.ConnectionString; + break; + case TCPConnectionStringAASSGX: + s_configJson.TCPConnectionStringAASSGX = builder.ConnectionString; + break; + case TCPConnectionStringAASVBS: + s_configJson.TCPConnectionStringAASVBS = builder.ConnectionString; + break; + case TCPConnectionStringHGSVBS: + s_configJson.TCPConnectionStringHGSVBS = builder.ConnectionString; + break; + } + } + + private static void DropIfExistsDatabase(string dbName, ServerConnection context) + { + try + { + string dropScript = $"IF EXISTS (select * from sys.databases where name = '{dbName}') BEGIN DROP DATABASE [{dbName}] END;"; + context.ExecuteNonQuery(dropScript); + } + catch + { + Console.WriteLine($"FAILED to drop database '{dbName}'"); + } + } + + private static void CreateDatabase(string dbName, ServerConnection context) + { + DropIfExistsDatabase(dbName, context); + string createScript = File.ReadAllText(NorthWindScriptPath); + + try + { + createScript = createScript.Replace(DB_Northwind, dbName); + context.ExecuteNonQuery(createScript); + } + catch (Exception) + { + throw; + } + } + } +} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Config.cs b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Config.cs new file mode 100644 index 0000000000..611037ae92 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Config.cs @@ -0,0 +1,59 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.IO; +using Newtonsoft.Json; + +namespace Microsoft.Data.SqlClient.TestUtilities +{ + public class Config + { + public string TCPConnectionString = null; + public string NPConnectionString = null; + public string TCPConnectionStringHGSVBS = null; + public string TCPConnectionStringAASVBS = null; + public string TCPConnectionStringAASSGX = null; + public string AADAuthorityURL = null; + public string AADPasswordConnectionString = null; + public string AADServicePrincipalId = null; + public string AADServicePrincipalSecret = null; + public string AzureKeyVaultURL = null; + public string AzureKeyVaultClientId = null; + public string AzureKeyVaultClientSecret = null; + public bool EnclaveEnabled = false; + public bool TracingEnabled = false; + public bool SupportsIntegratedSecurity = false; + public bool SupportsLocalDb = false; + public bool SupportsFileStream = false; + public bool UseManagedSNIOnWindows = false; + public string DNSCachingConnString = null; + public string DNSCachingServerCR = null; // this is for the control ring + public string DNSCachingServerTR = null; // this is for the tenant ring + public bool IsDNSCachingSupportedCR = false; // this is for the control ring + public bool IsDNSCachingSupportedTR = false; // this is for the tenant ring + public string EnclaveAzureDatabaseConnString = null; + + public static Config Load(string configPath = @"config.json") + { + try + { + using (StreamReader r = new StreamReader(configPath)) + { + return JsonConvert.DeserializeObject(r.ReadToEnd()); + } + } + catch + { + throw; + } + } + + public static void UpdateConfig(Config updatedConfig, string configPath = @"config.json") + { + string config = JsonConvert.SerializeObject(updatedConfig); + File.WriteAllText(configPath, config); + } + } +} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Microsoft.Data.SqlClient.TestUtilities.csproj b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Microsoft.Data.SqlClient.TestUtilities.csproj new file mode 100644 index 0000000000..d6e934cae7 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Microsoft.Data.SqlClient.TestUtilities.csproj @@ -0,0 +1,21 @@ + + + net46;netcoreapp2.1 + netcoreapp + netfx + Debug;Release;net46-Release;net46-Debug;netcoreapp2.1-Debug;netcoreapp2.1-Release; + AnyCPU;x86;x64 + $(ObjFolder)$(Configuration).$(Platform)\$(AssemblyName) + $(BinFolder)$(Configuration).$(Platform)\$(AssemblyName) + + + + + + + PreserveNewest + config.json + + + + \ No newline at end of file diff --git a/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Utils.cs b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Utils.cs new file mode 100644 index 0000000000..5d708e757d --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Utils.cs @@ -0,0 +1,46 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; + +namespace Microsoft.Data.SqlClient.TestUtilities +{ + public static class Utils + { + private static readonly string[] s_azureSqlServerEndpoints = {".database.windows.net", + ".database.cloudapi.de", + ".database.usgovcloudapi.net", + ".database.chinacloudapi.cn"}; + + // This method assumes dataSource parameter is in TCP connection string format. + public static bool IsAzureSqlServer(string dataSource) + { + int i = dataSource.LastIndexOf(','); + if (i >= 0) + { + dataSource = dataSource.Substring(0, i); + } + + i = dataSource.LastIndexOf('\\'); + if (i >= 0) + { + dataSource = dataSource.Substring(0, i); + } + + // trim redundant whitespace + dataSource = dataSource.Trim(); + + // check if server name end with any azure endpoints + for (i = 0; i < s_azureSqlServerEndpoints.Length; i++) + { + if (dataSource.EndsWith(s_azureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + return false; + } + } +} diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/config.default.json b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/config.default.json similarity index 89% rename from src/Microsoft.Data.SqlClient/tests/ManualTests/config.default.json rename to src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/config.default.json index 681c3b309d..e80b223ea9 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/config.default.json +++ b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/config.default.json @@ -16,5 +16,6 @@ "SupportsIntegratedSecurity": true, "SupportsLocalDb": false, "SupportsFileStream": false, - "UseManagedSNIOnWindows": false + "UseManagedSNIOnWindows": false, + "EnclaveAzureDatabaseConnString": "" } diff --git a/tools/props/Versions.props b/tools/props/Versions.props index 2fb7c487c7..044d79f9d2 100644 --- a/tools/props/Versions.props +++ b/tools/props/Versions.props @@ -64,6 +64,7 @@ 2.4.1 5.0.0-beta.20206.4 2.0.8 + 161.41011.9 $(NugetPackageVersion) diff --git a/tools/testsql/createNorthwindDb.sql b/tools/testsql/createNorthwindDb.sql index 01f48aaec6..fa3a2271fb 100644 --- a/tools/testsql/createNorthwindDb.sql +++ b/tools/testsql/createNorthwindDb.sql @@ -4318,7 +4318,7 @@ SELECT @isFullTextSearchingEnabled = FULLTEXTSERVICEPROPERTY('IsFullTextInstalle IF(@isFullTextSearchingEnabled = 1) BEGIN Use [Northwind] - CREATE FULLTEXT CATALOG Northwind_Employee_FTC AS DEFAULT; + CREATE FULLTEXT CATALOG [Northwind_Employee_FTC] AS DEFAULT; CREATE FULLTEXT INDEX ON Employees (FirstName, Title, City) KEY INDEX PK_Employees; PRINT N'Successfully Created FULLTEXT INDEX ON Employees (FirstName, Title, City)' From 3f1f95a6a5c94fce9a51e13cc6e9a3118a13b657 Mon Sep 17 00:00:00 2001 From: Wei Hu Date: Mon, 31 Aug 2020 23:53:07 +0800 Subject: [PATCH 20/24] Change file map link to absolute path to retire filemap_share_depots (#713) --- .../SqlBulkCopyColumnOrderHint.xml | 8 ++++---- .../SqlBulkCopyColumnOrderHintCollection.xml | 12 ++++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHint.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHint.xml index 8a7b04cf68..ff7a7130f4 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHint.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHint.xml @@ -31,7 +31,7 @@ The following example bulk copies data from a source table in the **AdventureWor A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column. > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](~/docs/framework/data/adonet/sql/bulk-copy-example-setup.md). +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. @@ -58,7 +58,7 @@ The following example bulk copies data from a source table in the **AdventureWor A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column. > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](~/docs/framework/data/adonet/sql/bulk-copy-example-setup.md). +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. @@ -88,7 +88,7 @@ The following example bulk copies data from a source table in the **AdventureWor A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column. > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](~/docs/framework/data/adonet/sql/bulk-copy-example-setup.md). +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. @@ -118,7 +118,7 @@ The following example bulk copies data from a source table in the **AdventureWor A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column. > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](~/docs/framework/data/adonet/sql/bulk-copy-example-setup.md). +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHintCollection.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHintCollection.xml index 094205866b..662ad0e652 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHintCollection.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlBulkCopyColumnOrderHintCollection.xml @@ -29,7 +29,7 @@ The following example bulk copies data from a source table in the **AdventureWor object to specify order hints for the bulk copy operation. > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](~/docs/framework/data/adonet/sql/bulk-copy-example-setup.md). +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. @@ -51,7 +51,7 @@ The following example bulk copies data from a source table in the **AdventureWor A SqlBulkCopyColumnOrderHint object is used to define the sort order for the **ProductNumber** destination column. > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](~/docs/framework/data/adonet/sql/bulk-copy-example-setup.md). +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. @@ -78,7 +78,7 @@ The following example bulk copies data from a source table in the **AdventureWor A SqlBulkCopyColumnOrderHint object is added to the by providing the destination column name and its sort order. > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](~/docs/framework/data/adonet/sql/bulk-copy-example-setup.md). +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. @@ -107,7 +107,7 @@ The example defines a column order hint for each bulk copy operation. The method must be used after the first bulk copy is performed and before the next bulk copy's order hint is defined. > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](~/docs/framework/data/adonet/sql/bulk-copy-example-setup.md). +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. @@ -176,7 +176,7 @@ The following example performs two bulk copy operations. The first operation cop The example defines a column order hint for the **OrderDate** column in the first bulk copy operation. The hint is removed before the second bulk copy operation. > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](~/docs/framework/data/adonet/sql/bulk-copy-example-setup.md). +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. @@ -208,7 +208,7 @@ The following example performs two bulk copy operations. The first operation cop The example defines a column order hint for the **OrderDate** column in the first bulk copy operation. The hint is removed before the second bulk copy operation. > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](~/docs/framework/data/adonet/sql/bulk-copy-example-setup.md). +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/dotnet/framework/data/adonet/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. From 9c8d7c69102316acbd5c20361426b528525372e2 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Wed, 2 Sep 2020 15:19:14 -0700 Subject: [PATCH 21/24] Update support.md (#720) --- SUPPORT.md | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/SUPPORT.md b/SUPPORT.md index 0119e22ff2..861787eb5b 100644 --- a/SUPPORT.md +++ b/SUPPORT.md @@ -4,16 +4,11 @@ Microsoft.Data.SqlClient library follows the latest .NET Core support policy for [View the .NET Core Support Policy](https://dotnet.microsoft.com/platform/support/policy/dotnet-core) -## Microsoft.Data.SqlClient release cadence - -We will publish new GA (stable) releases every 6 months on a regular cadence beginning with v2.0 along with 2-3 preview releases in between. LTS releases will be chosen by stakeholders and maintainers based on a few qualifications and customer response. +[View SqlClient Support Policy on Microsoft Documentation](https://docs.microsoft.com/sql/connect/ado-net/sqlclient-driver-support-lifecycle) -## Release Life Cycles +## Microsoft.Data.SqlClient release cadence -| Version | Official Release Date | Latest Patch Version | Patch Release Date | Support Level | End of Support | -| -- | -- | -- | -- | -- | -- | -| v1.1 | November 20, 2019 | | | Current | | -| v1.0 | August 28, 2019 | v1.0.19269.1 | September 26, 2019 | Current | February 20, 2020 | +New stable (GA) releases will be published every six months on a regular cadence beginning with version 1.2, along with 2 to 3 preview releases in between. Long Term Support (LTS) releases will be chosen by stakeholders and maintainers based on a few qualifications and customer response. ## Long Term Support (LTS) Releases From 1103108350698fb5909742c4aa21c3c525c668d2 Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Wed, 2 Sep 2020 17:16:41 -0700 Subject: [PATCH 22/24] Tests | Fix Test lab failures related to access token acquiry (#721) --- .../ManualTests/DataCommon/DataTestUtility.cs | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs index e65d4e6693..a3437647fa 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs @@ -29,7 +29,6 @@ public static class DataTestUtility public static readonly string AADPasswordConnectionString = null; public static readonly string AADServicePrincipalId = null; public static readonly string AADServicePrincipalSecret = null; - public static readonly string AADAccessToken = null; public static readonly string AKVBaseUrl = null; public static readonly string AKVUrl = null; public static readonly string AKVClientId = null; @@ -51,6 +50,7 @@ public static class DataTestUtility public static readonly string EnclaveAzureDatabaseConnString = null; + public static string AADAccessToken = null; public const string UdtTestDbName = "UdtTestDb"; public const string AKVKeyName = "TestSqlClientAzureKeyVaultProvider"; private const string ManagedNetworkingAppContextSwitch = "Switch.Microsoft.Data.SqlClient.UseManagedNetworkingOnWindows"; @@ -83,9 +83,11 @@ static DataTestUtility() IsDNSCachingSupportedTR = c.IsDNSCachingSupportedTR; EnclaveAzureDatabaseConnString = c.EnclaveAzureDatabaseConnString; + System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12; + if (TracingEnabled) { - TraceListener = new DataTestUtility.TraceEventListener(); + TraceListener = new TraceEventListener(); } if (UseManagedSNIOnWindows) @@ -94,13 +96,6 @@ static DataTestUtility() Console.WriteLine($"App Context switch {ManagedNetworkingAppContextSwitch} enabled on {Environment.OSVersion}"); } - if (IsAADPasswordConnStrSetup() && IsAADAuthorityURLSetup()) - { - string username = RetrieveValueFromConnStr(AADPasswordConnectionString, new string[] { "User ID", "UID" }); - string password = RetrieveValueFromConnStr(AADPasswordConnectionString, new string[] { "Password", "PWD" }); - AADAccessToken = GenerateAccessToken(AADAuthorityURL, username, password); - } - string url = c.AzureKeyVaultURL; if (!string.IsNullOrEmpty(url) && Uri.TryCreate(url, UriKind.Absolute, out Uri AKVBaseUri)) { @@ -130,8 +125,6 @@ static DataTestUtility() AEConnStrings.Add(TCPConnectionStringAASSGX); AEConnStringsSetup.Add(TCPConnectionStringAASSGX); } - - System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12; } else { @@ -177,13 +170,14 @@ private static Task AcquireTokenAsync(string authorityURL, string userID string scope = "https://database.windows.net//.default"; string applicationName = "Microsoft Data SqlClient Manual Tests"; string clientVersion = "1.0.0.0"; - string adoClientId = "4d079b4c-cab7-4b7c-a115-8fd51b6f8239"; + string adoClientId = "2fd908ad-0664-4344-b9be-cd3e8b574c38"; IPublicClientApplication app = PublicClientApplicationBuilder.Create(adoClientId) .WithAuthority(authorityURL) .WithClientName(applicationName) .WithClientVersion(clientVersion) .Build(); + AuthenticationResult result; string[] scopes = new string[] { scope }; @@ -283,7 +277,7 @@ public static bool IsAADAuthorityURLSetup() public static bool IsNotAzureServer() { - return !AreConnStringsSetup() || !Utils.IsAzureSqlServer(new SqlConnectionStringBuilder((DataTestUtility.TCPConnectionString)).DataSource); + return !AreConnStringsSetup() || !Utils.IsAzureSqlServer(new SqlConnectionStringBuilder((TCPConnectionString)).DataSource); } public static bool IsAKVSetupAvailable() @@ -300,7 +294,7 @@ public static bool IsUTF8Supported() bool retval = false; if (AreConnStringsSetup()) { - using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) + using (SqlConnection connection = new SqlConnection(TCPConnectionString)) using (SqlCommand command = new SqlCommand()) { command.Connection = connection; @@ -387,6 +381,12 @@ public static void DropStoredProcedure(SqlConnection sqlConnection, string spNam public static string GetAccessToken() { + if (null == AADAccessToken && 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; } From 5934db45582cb94a9107e34d13283d8a83135a3d Mon Sep 17 00:00:00 2001 From: Cheena Malhotra Date: Wed, 16 Sep 2020 15:10:15 -0700 Subject: [PATCH 23/24] Tests | Update Test Lab for Azure Synapse compatible test suite (#723) --- BUILDGUIDE.md | 19 +-- .../AlwaysEncrypted/CoreCryptoTests.cs | 6 +- .../AlwaysEncrypted/CspProviderExt.cs | 2 +- .../DDBasics/DDAsyncTest/DDAsyncTest.cs | 8 +- .../DDDataTypesTest/DDDataTypesTest.cs | 6 +- .../DDBasics/DDMARSTest/DDMARSTest.cs | 3 +- .../ManualTests/DataCommon/DataTestUtility.cs | 24 +++- .../ProviderAgnostic/ReaderTest/ReaderTest.cs | 3 +- .../SQL/AdapterTest/AdapterTest.cs | 49 ++++--- .../AsyncCancelledConnectionsTest.cs | 1 - .../ManualTests/SQL/AsyncTest/AsyncTest.cs | 2 +- .../SQL/AsyncTest/BeginExecAsyncTest.cs | 6 +- .../SQL/AsyncTest/BeginExecReaderAsyncTest.cs | 6 +- .../SQL/AsyncTest/XmlReaderAsyncTest.cs | 6 +- .../ConnectionPoolTest/ConnectionPoolTest.cs | 3 +- .../SQL/ConnectivityTests/ConnectivityTest.cs | 14 +- .../TcpDefaultForAzureTest.cs | 7 +- .../DataClassificationTest.cs | 7 +- .../SQL/DataReaderTest/DataReaderTest.cs | 7 +- .../SQL/DataStreamTest/DataStreamTest.cs | 3 +- .../SQL/DateTimeTest/DateTimeTest.cs | 3 +- .../SQL/ExceptionTest/ExceptionTest.cs | 8 +- .../MARSSessionPoolingTest.cs | 18 ++- .../ManualTests/SQL/MARSTest/MARSTest.cs | 123 +++++++++--------- .../ConnectionOnMirroringTest.cs | 3 +- .../ParallelTransactionsTest.cs | 6 +- .../SQL/ParameterTest/ParametersTest.cs | 13 +- .../ParameterTest/SqlAdapterUpdateBatch.cs | 3 +- .../ManualTests/SQL/ParameterTest/TvpTest.cs | 3 +- .../SQL/SplitPacketTest/SplitPacketTest.cs | 2 +- .../DataConversionErrorMessageTest.cs | 5 +- .../SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs | 20 ++- .../SQL/SqlCommand/SqlCommandCancelTest.cs | 29 +++-- .../SQL/SqlCommand/SqlCommandSetTest.cs | 3 +- .../SqlStatisticsTest/SqlStatisticsTest.cs | 2 +- .../TransactionEnlistmentTest.cs | 17 ++- .../SQL/TransactionTest/TransactionTest.cs | 3 +- .../SQL/UdtTest/SqlServerTypesTest.cs | 39 ++++-- .../tests/ManualTests/SQL/UdtTest/UdtTest2.cs | 1 + .../SQL/Utf8SupportTest/Utf8SupportTest.cs | 5 +- .../SQL/WeakRefTest/WeakRefTest.cs | 3 +- .../WeakRefTestYukonSpecific.cs | 3 +- .../TracingTests/DiagnosticTest.cs | 6 +- .../TracingTests/EventSourceTest.cs | 2 +- .../Config.cs | 1 + .../config.default.json | 3 +- 46 files changed, 312 insertions(+), 194 deletions(-) diff --git a/BUILDGUIDE.md b/BUILDGUIDE.md index 6f56080aa0..a6d2d04564 100644 --- a/BUILDGUIDE.md +++ b/BUILDGUIDE.md @@ -74,22 +74,22 @@ Once the environment is setup properly, execute the desired set of commands belo ## Run Functional Tests -Windows (`netfx x86`): +Windows (`netfx x86`): ```bash > dotnet test "src\Microsoft.Data.SqlClient\tests\FunctionalTests\Microsoft.Data.SqlClient.Tests.csproj" /p:Platform="Win32" /p:Configuration="Release" /p:TestTargetOS="Windowsnetfx" --no-build -v n --filter "category!=nonnetfxtests&category!=failing&category!=nonwindowstests" ``` -Windows (`netfx x64`): +Windows (`netfx x64`): ```bash > dotnet test "src\Microsoft.Data.SqlClient\tests\FunctionalTests\Microsoft.Data.SqlClient.Tests.csproj" /p:Platform="x64" /p:Configuration="Release" /p:TestTargetOS="Windowsnetfx" --no-build -v n --filter "category!=nonnetfxtests&category!=failing&category!=nonwindowstests" ``` -Windows (`netcoreapp`): +Windows (`netcoreapp`): ```bash > dotnet test "src\Microsoft.Data.SqlClient\tests\FunctionalTests\Microsoft.Data.SqlClient.Tests.csproj" /p:Platform="AnyCPU" /p:Configuration="Release" /p:TestTargetOS="Windowsnetcoreapp" --no-build -v n --filter "category!=nonnetcoreapptests&category!=failing&category!=nonwindowstests" ``` -Unix (`netcoreapp`): +Unix (`netcoreapp`): ```bash > dotnet test "src/Microsoft.Data.SqlClient/tests/FunctionalTests/Microsoft.Data.SqlClient.Tests.csproj" /p:Platform="AnyCPU" /p:Configuration="Release" /p:TestTargetOS="Unixnetcoreapp" --no-build -v n --filter "category!=nonnetcoreapptests&category!=failing&category!=nonlinuxtests&category!=nonuaptests" ``` @@ -118,25 +118,26 @@ Manual Tests require the below setup to run: |SupportsIntegratedSecurity | (Optional) Whether or not the USER running tests has integrated security access to the target SQL Server.| `true` OR `false`| |SupportsFileStream | (Optional) Whether or not FileStream is enabled on SQL Server| `true` OR `false`| |UseManagedSNIOnWindows | (Optional) Enables testing with Managed SNI on Windows| `true` OR `false`| +|IsAzureSynpase | (Optional) When set to 'true', test suite runs compatible tests for Azure Synapse/Parallel Data Warehouse. | `true` OR `false`| Commands to run tests: -Windows (`netfx x86`): +Windows (`netfx x86`): ```bash > dotnet test "src\Microsoft.Data.SqlClient\tests\ManualTests\Microsoft.Data.SqlClient.ManualTesting.Tests.csproj" /p:Platform="Win32" /p:Configuration="Release" /p:TestTargetOS="Windowsnetfx" --no-build -v n --filter "category!=nonnetfxtests&category!=failing&category!=nonwindowstests" ``` -Windows (`netfx x64`): +Windows (`netfx x64`): ```bash > dotnet test "src\Microsoft.Data.SqlClient\tests\ManualTests\Microsoft.Data.SqlClient.ManualTesting.Tests.csproj" /p:Platform="x64" /p:Configuration="Release" /p:TestTargetOS="Windowsnetfx" --no-build -v n --filter "category!=nonnetfxtests&category!=failing&category!=nonwindowstests" ``` -Windows (`netcoreapp`): +Windows (`netcoreapp`): ```bash > dotnet test "src\Microsoft.Data.SqlClient\tests\ManualTests\Microsoft.Data.SqlClient.ManualTesting.Tests.csproj" /p:Platform="AnyCPU" /p:Configuration="Release" /p:TestTargetOS="Windowsnetcoreapp" --no-build -v n --filter "category!=nonnetcoreapptests&category!=failing&category!=nonwindowstests" ``` -Unix (`netcoreapp`): +Unix (`netcoreapp`): ```bash > dotnet test "src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj" /p:Platform="AnyCPU" /p:Configuration="Release" /p:TestTargetOS="Unixnetcoreapp" --no-build -v n --filter "category!=nonnetcoreapptests&category!=failing&category!=nonlinuxtests&category!=nonuaptests" ``` @@ -156,7 +157,7 @@ Tests can be built and run with custom "Reference Type" property that enables di - "NetStandardPackage" => Build and run tests with Microsoft.Data.SqlClient as Package Reference via .NET Standard Library > ************** IMPORTANT NOTE BEFORE PROCEEDING WITH "PACKAGE" AND "NETSTANDARDPACKAGE" REFERENCE TYPES *************** -> CREATE A NUGET PACKAGE WITH BELOW COMMAND AND ADD TO LOCAL FOLDER + UPDATE NUGET CONFIG FILE TO READ FROM THAT LOCATION +> CREATE A NUGET PACKAGE WITH BELOW COMMAND AND ADD TO LOCAL FOLDER + UPDATE NUGET CONFIG FILE TO READ FROM THAT LOCATION > ``` > > msbuild /p:configuration=Release > ``` diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/CoreCryptoTests.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/CoreCryptoTests.cs index a7e019ba43..82456e8636 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/CoreCryptoTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/CoreCryptoTests.cs @@ -11,7 +11,8 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted { public class CoreCryptoTests : IClassFixture { - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Always Encrypted not supported in Azure Synapse. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] [PlatformSpecific(TestPlatforms.Windows)] public void TestAeadCryptoWithNativeBaseline() { @@ -45,7 +46,8 @@ public void TestAeadCryptoWithNativeBaseline() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Always Encrypted not supported in Azure Synapse. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] [PlatformSpecific(TestPlatforms.Windows)] public void TestRsaCryptoWithNativeBaseline() { diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/CspProviderExt.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/CspProviderExt.cs index 1944b79f17..49dd608d99 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/CspProviderExt.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/CspProviderExt.cs @@ -144,7 +144,7 @@ public void TestRoundTripWithCSPAndCertStoreProvider() } } - [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringSetupForAE))] [ClassData(typeof(AEConnectionStringProvider))] public void TestEncryptDecryptWithCSP(string connectionString) { diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/DDBasics/DDAsyncTest/DDAsyncTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/DDBasics/DDAsyncTest/DDAsyncTest.cs index b837f3983e..d1f7ed0a24 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/DDBasics/DDAsyncTest/DDAsyncTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/DDBasics/DDAsyncTest/DDAsyncTest.cs @@ -15,7 +15,7 @@ public static class DDAsyncTest [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static void OpenConnection_WithAsyncTrue_ThrowsNotSupportedException() { - //Fails on NetCore + //Passes on NetCore var asyncConnectionString = DataTestUtility.TCPConnectionString + ";async=true"; Assert.Throws(() => { new SqlConnection(asyncConnectionString); }); } @@ -30,7 +30,8 @@ public static void OpenConnection_WithAsyncTrue() } #region <> - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove dependency on Northwind database by creating required table in setup. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void ExecuteCommand_WithNewConnection_ShouldPerformAsyncByDefault() { var executedProcessList = new List(); @@ -75,7 +76,8 @@ private static async Task ExecuteCommandWithNewConnectionAsync(string processNam #endregion #region <> - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parallel query execution on the same connection is not supported. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void ExecuteCommand_WithSharedConnection_ShouldPerformAsyncByDefault() { var executedProcessList = new List(); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/DDBasics/DDDataTypesTest/DDDataTypesTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/DDBasics/DDDataTypesTest/DDDataTypesTest.cs index 8c028c9c1c..0d1e0e7e68 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/DDBasics/DDDataTypesTest/DDDataTypesTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/DDBasics/DDDataTypesTest/DDDataTypesTest.cs @@ -12,7 +12,8 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public static class DDDataTypesTest { - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Cannot find data type 'XML'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void XmlTest() { string tempTable = "xml_" + Guid.NewGuid().ToString().Replace('-', '_'); @@ -73,7 +74,8 @@ public static void XmlTest() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: The statement failed. Column 'col1' has a data type that cannot participate in a columnstore index. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void MaxTypesTest() { string tempTable = "max_" + Guid.NewGuid().ToString().Replace('-', '_'); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/DDBasics/DDMARSTest/DDMARSTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/DDBasics/DDMARSTest/DDMARSTest.cs index c88eba6a3f..ad057e587d 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/DDBasics/DDMARSTest/DDMARSTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/DDBasics/DDMARSTest/DDMARSTest.cs @@ -8,7 +8,8 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public static class DDMARSTest { - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove dependency from Northwind database + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestMain() { string connstr = (new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString) { MultipleActiveResultSets = true }).ConnectionString; diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs index a3437647fa..65727fbc66 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/DataCommon/DataTestUtility.cs @@ -41,7 +41,7 @@ public static class DataTestUtility public static readonly bool SupportsLocalDb = false; public static readonly bool SupportsFileStream = false; public static readonly bool UseManagedSNIOnWindows = false; - + public static readonly bool IsAzureSynapse = false; public static readonly string DNSCachingConnString = null; public static readonly string DNSCachingServerCR = null; // this is for the control ring public static readonly string DNSCachingServerTR = null; // this is for the tenant ring @@ -79,6 +79,7 @@ static DataTestUtility() DNSCachingConnString = c.DNSCachingConnString; DNSCachingServerCR = c.DNSCachingServerCR; DNSCachingServerTR = c.DNSCachingServerTR; + IsAzureSynapse = c.IsAzureSynapse; IsDNSCachingSupportedCR = c.IsDNSCachingSupportedCR; IsDNSCachingSupportedTR = c.IsDNSCachingSupportedTR; EnclaveAzureDatabaseConnString = c.EnclaveAzureDatabaseConnString; @@ -243,21 +244,28 @@ public static bool IsSupportedDataClassification() public static bool IsDNSCachingSetup() => !string.IsNullOrEmpty(DNSCachingConnString); + // Synapse: Always Encrypted is not supported with Azure Synapse. + // Ref: https://feedback.azure.com/forums/307516-azure-synapse-analytics/suggestions/17858869-support-always-encrypted-in-sql-data-warehouse public static bool IsEnclaveAzureDatabaseSetup() { - return EnclaveEnabled && !string.IsNullOrEmpty(EnclaveAzureDatabaseConnString); + return EnclaveEnabled && !string.IsNullOrEmpty(EnclaveAzureDatabaseConnString) && IsNotAzureSynapse(); } - public static bool IsUdtTestDatabasePresent() => IsDatabasePresent(UdtTestDbName); + public static bool IsNotAzureSynapse() => !IsAzureSynapse; + + // Synapse: UDT Test Database not compatible with Azure Synapse. + public static bool IsUdtTestDatabasePresent() => IsDatabasePresent(UdtTestDbName) && IsNotAzureSynapse(); public static bool AreConnStringsSetup() { return !string.IsNullOrEmpty(NPConnectionString) && !string.IsNullOrEmpty(TCPConnectionString); } + // Synapse: Always Encrypted is not supported with Azure Synapse. + // Ref: https://feedback.azure.com/forums/307516-azure-synapse-analytics/suggestions/17858869-support-always-encrypted-in-sql-data-warehouse public static bool AreConnStringSetupForAE() { - return AEConnStrings.Count > 0; + return AEConnStrings.Count > 0 && IsNotAzureSynapse(); } public static bool IsAADPasswordConnStrSetup() @@ -280,19 +288,23 @@ public static bool IsNotAzureServer() return !AreConnStringsSetup() || !Utils.IsAzureSqlServer(new SqlConnectionStringBuilder((TCPConnectionString)).DataSource); } + // Synapse: Always Encrypted is not supported with Azure Synapse. + // Ref: https://feedback.azure.com/forums/307516-azure-synapse-analytics/suggestions/17858869-support-always-encrypted-in-sql-data-warehouse public static bool IsAKVSetupAvailable() { - return !string.IsNullOrEmpty(AKVUrl) && !string.IsNullOrEmpty(AKVClientId) && !string.IsNullOrEmpty(AKVClientSecret); + return !string.IsNullOrEmpty(AKVUrl) && !string.IsNullOrEmpty(AKVClientId) && !string.IsNullOrEmpty(AKVClientSecret) && IsNotAzureSynapse(); } public static bool IsUsingManagedSNI() => UseManagedSNIOnWindows; public static bool IsUsingNativeSNI() => !IsUsingManagedSNI(); + // Synapse: UTF8 collations are not supported with Azure Synapse. + // Ref: https://feedback.azure.com/forums/307516-azure-synapse-analytics/suggestions/40103791-utf-8-collations-should-be-supported-in-azure-syna public static bool IsUTF8Supported() { bool retval = false; - if (AreConnStringsSetup()) + if (AreConnStringsSetup() && IsNotAzureSynapse()) { using (SqlConnection connection = new SqlConnection(TCPConnectionString)) using (SqlCommand command = new SqlCommand()) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/ProviderAgnostic/ReaderTest/ReaderTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/ProviderAgnostic/ReaderTest/ReaderTest.cs index b2ecfdcec9..054d495760 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/ProviderAgnostic/ReaderTest/ReaderTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/ProviderAgnostic/ReaderTest/ReaderTest.cs @@ -11,7 +11,8 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public static class ReaderTest { - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove dependency from Northwind database + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestMain() { string connectionString = DataTestUtility.TCPConnectionString; 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 c12d8ba220..6249c4fae3 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AdapterTest/AdapterTest.cs @@ -64,7 +64,8 @@ public AdapterTest() InitDataValues(); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove Northwind dependency by creating required tables in setup. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void SimpleFillTest() { using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -85,7 +86,8 @@ public void SimpleFillTest() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove Northwind dependency by creating required tables in setup. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void PrepUnprepTest() { // share the connection @@ -171,7 +173,8 @@ public void PrepUnprepTest() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Create table statement contains a data type that is unsupported in Parallel Data Warehouse. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void SqlVariantTest() { string tableName = DataTestUtility.GenerateObjectName(); @@ -265,7 +268,8 @@ public void SqlVariantTest() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: The RETURN statement can only be used in user-defined functions. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void ParameterTest_AllTypes() { string procName = DataTestUtility.GenerateObjectName(); @@ -477,7 +481,8 @@ public void ParameterTest_AllTypes() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: The RETURN statement can only be used in user-defined functions. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void ParameterTest_InOut() { string procName = DataTestUtility.GetUniqueName("P"); @@ -574,7 +579,8 @@ public void ParameterTest_InOut() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove Northwind dependency by creating required tables in setup. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void UpdateTest() { using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -658,7 +664,8 @@ public void UpdateTest() // these next texts verify that 'bulk' operations work. If each command type modifies more than three rows, then we do a Prep/Exec instead of // adhoc ExecuteSql. - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove Northwind dependency by creating required tables in setup. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void BulkUpdateTest() { using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -755,7 +762,8 @@ public void BulkUpdateTest() // Makes sure that we can refresh an identity column in the dataSet // for a newly inserted row - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Must declare the scalar variable "@@IDENTITY". + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void UpdateRefreshTest() { string createIdentTable = @@ -849,7 +857,8 @@ public void UpdateRefreshTest() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Create table statement contains a data type that is unsupported in Parallel Data Warehouse. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void UpdateNullTest() { string tableName = DataTestUtility.GenerateObjectName(); @@ -905,7 +914,8 @@ public void UpdateNullTest() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Create table statement contains a data type that is unsupported in Parallel Data Warehouse. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void UpdateOffsetTest() { string tableName = DataTestUtility.GenerateObjectName(); @@ -981,16 +991,17 @@ public void UpdateOffsetTest() public void SelectAllTest() { // Test exceptions - using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(new SqlCommand("select * from orders", new SqlConnection(DataTestUtility.TCPConnectionString)))) + using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(new SqlCommand("select * from sys.columns", new SqlConnection(DataTestUtility.TCPConnectionString)))) { DataSet dataset = new DataSet(); - sqlAdapter.TableMappings.Add("Table", "orders"); + sqlAdapter.TableMappings.Add("View", "sys.columns"); sqlAdapter.Fill(dataset); } } // AutoGen test - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove Northwind dependency by creating required tables in setup. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void AutoGenUpdateTest() { using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -1061,7 +1072,8 @@ public void AutoGenUpdateTest() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Dynamic SQL generation is not supported against a SelectCommand that does not return any base table information. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void AutoGenErrorTest() { string createIdentTable = @@ -1104,9 +1116,11 @@ public void AutoGenErrorTest() } } - // These next tests verify that 'bulk' operations work. If each command type modifies more than three rows, then we do a Prep/Exec instead of + // These next tests verify that 'bulk' operations work. + // If each command type modifies more than three rows, then we do a Prep/Exec instead of // adhoc ExecuteSql. - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove Northwind dependency nu creating required tables in setup. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void AutoGenBulkUpdateTest() { using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -1256,7 +1270,8 @@ public void TestDeriveParameters() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 65: Incorrect syntax near 'as'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void TestReadOnlyColumnMetadata() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/AsyncCancelledConnectionsTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/AsyncCancelledConnectionsTest.cs index 5578e968ce..c3cc2d6b07 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/AsyncCancelledConnectionsTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/AsyncCancelledConnectionsTest.cs @@ -21,7 +21,6 @@ public AsyncCancelledConnectionsTest(ITestOutputHelper output) this._output = output; } - [ActiveIssue(490)] // This test seems to fail regularly in pipelines due to deadlocks. But it's still useful for local testing. [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void CancelAsyncConnections() { diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/AsyncTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/AsyncTest.cs index 2b475c7a7c..080a66b394 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/AsyncTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/AsyncTest.cs @@ -10,7 +10,7 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public static class AsyncTest { - [ActiveIssue(5533)] + [ActiveIssue(5533)] // Async Operations slower than Sync operations [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static void TestReadAsyncTimeConsumed() { diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecAsyncTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecAsyncTest.cs index 2c0673d507..4f7956745f 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecAsyncTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecAsyncTest.cs @@ -30,7 +30,8 @@ private static string GenerateCommandText() return commandText; } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 201: Incorrect syntax near ';'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void ExecuteTest() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -68,7 +69,8 @@ public static void ExecuteTest() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 201: Incorrect syntax near ';'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void FailureTest() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecReaderAsyncTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecReaderAsyncTest.cs index 87bbef247b..daa58b1851 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecReaderAsyncTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/BeginExecReaderAsyncTest.cs @@ -33,7 +33,8 @@ private static string GenerateCommandText() return commandText; } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 198: Incorrect syntax near ';'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void ExecuteTest() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -51,7 +52,8 @@ public static void ExecuteTest() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 198: Incorrect syntax near ';'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void BeginExecuteReaderWithCallback() { object state = new object(); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/XmlReaderAsyncTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/XmlReaderAsyncTest.cs index f72f474a78..52a5dde8f3 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/XmlReaderAsyncTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/AsyncTest/XmlReaderAsyncTest.cs @@ -13,7 +13,8 @@ public static class XmlReaderAsyncTest private static string commandText = "SELECT * from dbo.Customers FOR XML AUTO, XMLDATA;"; - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 29: Incorrect syntax near 'FOR'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void ExecuteTest() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -34,7 +35,8 @@ public static void ExecuteTest() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Northwind dependency + Parse error at line: 1, column: 29: Incorrect syntax near 'FOR'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void ExceptionTest() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectionPoolTest/ConnectionPoolTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectionPoolTest/ConnectionPoolTest.cs index 872d5d385c..2696f354aa 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectionPoolTest/ConnectionPoolTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectionPoolTest/ConnectionPoolTest.cs @@ -21,7 +21,8 @@ public static void ConnectionPool_NonMars() RunDataTestForSingleConnString(_TCPConnectionString); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Fix this test for Azure Synapse. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void ConnectionPool_Mars() { RunDataTestForSingleConnString(_tcpMarsConnStr); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/ConnectivityTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/ConnectivityTest.cs index ba9777a432..3e338a3b1e 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/ConnectivityTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/ConnectivityTest.cs @@ -26,7 +26,9 @@ public static class ConnectivityTest private static readonly string s_selectTableCmd = $"SELECT COUNT(*) FROM {s_tableName}"; private static readonly string s_dropDatabaseCmd = $"DROP DATABASE {s_databaseName}"; - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Stored procedure sp_who2 does not exist or is not supported. + // Synapse: SqlConnection.ServerProcessId is always retrieved as 0. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void EnvironmentHostNameSPIDTest() { SqlConnectionStringBuilder builder = (new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString) { Pooling = true }); @@ -44,6 +46,7 @@ public static void EnvironmentHostNameSPIDTest() reader.Read(); sessionSpid = reader.GetInt16(0); } + // Confirm Server process id is same as result of SELECT @@SPID Assert.Equal(sessionSpid, sqlClientSPID); @@ -113,7 +116,8 @@ public static void ConnectionTimeoutTestWithThread() Assert.True(timeElapsed < threshold); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Catalog view 'sysprocesses' is not supported in this version. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void LocalProcessIdTest() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString); @@ -205,6 +209,7 @@ public void SqlConnectionOpen() } } + // Synapse: Parse error at line: 1, column: 59: Incorrect syntax near 'SINGLE_USER' - No support for MULTI_USER [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public static void ConnectionKilledTest() { @@ -235,7 +240,8 @@ public static void ConnectionKilledTest() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: KILL not supported on Azure Synapse - Parse error at line: 1, column: 6: Incorrect syntax near '105'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void ConnectionResiliencySPIDTest() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString); @@ -249,7 +255,7 @@ public static void ConnectionResiliencySPIDTest() InternalConnectionWrapper wrapper = new InternalConnectionWrapper(conn, true, builder.ConnectionString); using (SqlCommand cmd = conn.CreateCommand()) { - cmd.CommandText = "SELECT TOP 1 * FROM dbo.Employees"; + cmd.CommandText = "SELECT @@SPID"; wrapper.KillConnectionByTSql(); bool cmdSuccess = false; try diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/TcpDefaultForAzureTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/TcpDefaultForAzureTest.cs index 8ebec2932c..0128571616 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/TcpDefaultForAzureTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ConnectivityTests/TcpDefaultForAzureTest.cs @@ -33,8 +33,11 @@ static TcpDefaultForAzureTest() builder.ConnectTimeout = 1; } - [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // Cannot retrieve UseManagedSNI flag via reflection on UAP - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Named Pipes not supported for Azure Synapse + // Expected protocol TCP Provider in the error message, but received: A network-related or instance-specific error occurred while establishing a connection to SQL Server. + // The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. + // (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void NonAzureNoProtocolConnectionTest() { builder.DataSource = InvalidHostname; 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 51ff126410..8119bd2586 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataClassificationTest/DataClassificationTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataClassificationTest/DataClassificationTest.cs @@ -14,7 +14,8 @@ public static class DataClassificationTest { private static string s_tableName; - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsSupportedDataClassification))] + // Synapse: Azure Synapse does not support RANK + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse), nameof(DataTestUtility.IsSupportedDataClassification))] public static void TestDataClassificationResultSetRank() { s_tableName = DataTestUtility.GetUniqueNameForSqlServer("DC"); @@ -98,11 +99,11 @@ private static void VerifySensitivityClassification(SqlDataReader reader, bool r { if (columnPos == 1 || columnPos == 2) { - Assert.True(sp.SensitivityRank == SensitivityRank.LOW); + Assert.Equal(SensitivityRank.LOW, sp.SensitivityRank); } else if (columnPos == 6 || columnPos == 7) { - Assert.True(sp.SensitivityRank == SensitivityRank.MEDIUM); + Assert.Equal(SensitivityRank.MEDIUM, sp.SensitivityRank); } } else diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs index 2e1c32c716..723fafc2a2 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataReaderTest/DataReaderTest.cs @@ -69,7 +69,8 @@ public static void MultiQuerySchema() // Checks for the IsColumnSet bit in the GetSchemaTable for Sparse columns - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Cannot find data type 'xml'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void CheckSparseColumnBit() { const int sparseColumns = 4095; @@ -130,6 +131,7 @@ public static void CheckSparseColumnBit() } } + // Synapse: Statement 'Drop Database' is not supported in this version of SQL Server. [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public static void CollatedDataReaderTest() { @@ -210,7 +212,8 @@ private static bool IsColumnBitSet(SqlConnection con, string selectQuery, int in return columnSetPresent; } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Enforced unique constraints are not supported. To create an unenforced unique constraint you must include the NOT ENFORCED syntax as part of your statement. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void CheckHiddenColumns() { // hidden columns can be found by using CommandBehavior.KeyInfo or at the sql level diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataStreamTest/DataStreamTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataStreamTest/DataStreamTest.cs index 1eab7e65c3..2dc5dfcb89 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataStreamTest/DataStreamTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DataStreamTest/DataStreamTest.cs @@ -37,7 +37,8 @@ public static void RunAllTestsForSingleServer_TCP() RunAllTestsForSingleServer(DataTestUtility.TCPConnectionString); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: The statement failed. Column 'foo' has a data type that cannot participate in a columnstore index. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static async Task AsyncMultiPacketStreamRead() { int packetSize = 514; // force small packet size so we can quickly check multi packet reads diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DateTimeTest/DateTimeTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DateTimeTest/DateTimeTest.cs index 421f374bb4..af3e5d39b4 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DateTimeTest/DateTimeTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/DateTimeTest/DateTimeTest.cs @@ -55,7 +55,8 @@ public static void SQLBU503290Test() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: CREATE or ALTER PROCEDURE statement uses syntax or features that are not supported in SQL Server PDW. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void ReaderParameterTest() { string tableName = "#t_" + Guid.NewGuid().ToString().Replace('-', '_'); 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 6f7d9ad6cd..150e256435 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ExceptionTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ExceptionTest/ExceptionTest.cs @@ -50,7 +50,8 @@ public static void WarningTest() private static bool EmployeesTableHasFullTextIndex() { - if (DataTestUtility.TCPConnectionString == null) + // Test case not supported on Azure Synapse. + if (DataTestUtility.TCPConnectionString == null || DataTestUtility.IsAzureSynapse) return false; using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -64,6 +65,7 @@ private static bool EmployeesTableHasFullTextIndex() } } + // TODO Synapse: Remove dependency from Northwind database. [ConditionalFact(nameof(EmployeesTableHasFullTextIndex))] public static void WarningsBeforeRowsTest() { @@ -149,6 +151,7 @@ private static bool CheckThatExceptionsAreDistinctButHaveSameData(SqlException e return true; } + // Synapse: 110003;Invalid user or password [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public static void ExceptionTests() { @@ -183,7 +186,8 @@ public static void ExceptionTests() VerifyConnectionFailure(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14)); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: 110003;Invalid user or password + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void VariousExceptionTests() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MARSSessionPoolingTest/MARSSessionPoolingTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MARSSessionPoolingTest/MARSSessionPoolingTest.cs index 0df83abb9f..b205ee0af2 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MARSSessionPoolingTest/MARSSessionPoolingTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MARSSessionPoolingTest/MARSSessionPoolingTest.cs @@ -32,21 +32,24 @@ public static class MARSSessionPoolingTest MultipleActiveResultSets = true }).ConnectionString; - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Catalog view 'dm_exec_connections' is not supported in this version. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void MarsExecuteScalar_AllFlavors() { TestMARSSessionPooling("Case: Text, ExecuteScalar", _testConnString, CommandType.Text, ExecuteType.ExecuteScalar, ReaderTestType.ReaderClose, GCType.Wait); TestMARSSessionPooling("Case: RPC, ExecuteScalar", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteScalar, ReaderTestType.ReaderClose, GCType.Wait); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Catalog view 'dm_exec_connections' is not supported in this version. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void MarsExecuteNonQuery_AllFlavors() { TestMARSSessionPooling("Case: Text, ExecuteNonQuery", _testConnString, CommandType.Text, ExecuteType.ExecuteNonQuery, ReaderTestType.ReaderClose, GCType.Wait); TestMARSSessionPooling("Case: RPC, ExecuteNonQuery", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteNonQuery, ReaderTestType.ReaderClose, GCType.Wait); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Catalog view 'dm_exec_connections' is not supported in this version. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void MarsExecuteReader_Text_NoGC() { TestMARSSessionPooling("Case: Text, ExecuteReader, ReaderClose", _testConnString, CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.ReaderClose, GCType.Wait); @@ -54,7 +57,8 @@ public static void MarsExecuteReader_Text_NoGC() TestMARSSessionPooling("Case: Text, ExecuteReader, ConnectionClose", _testConnString, CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.ConnectionClose, GCType.Wait); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Stored procedure sp_who does not exist or is not supported. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void MarsExecuteReader_RPC_NoGC() { TestMARSSessionPooling("Case: RPC, ExecuteReader, ReaderClose", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ReaderClose, GCType.Wait); @@ -62,16 +66,18 @@ public static void MarsExecuteReader_RPC_NoGC() TestMARSSessionPooling("Case: RPC, ExecuteReader, ConnectionClose", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ConnectionClose, GCType.Wait); } + // Synapse: Catalog view 'dm_exec_connections' is not supported in this version. [ActiveIssue(11167)] - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void MarsExecuteReader_Text_WithGC() { TestMARSSessionPooling("Case: Text, ExecuteReader, GC-Wait", _testConnString, CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.ReaderGC, GCType.Wait); TestMARSSessionPooling("Case: Text, ExecuteReader, GC-NoWait", _testConnString, CommandType.Text, ExecuteType.ExecuteReader, ReaderTestType.ReaderGC, GCType.NoWait); } + // Synapse: Stored procedure sp_who does not exist or is not supported. [ActiveIssue(8959)] - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void MarsExecuteReader_StoredProcedure_WithGC() { TestMARSSessionPooling("Case: RPC, ExecuteReader, GC-Wait", _testConnString, CommandType.StoredProcedure, ExecuteType.ExecuteReader, ReaderTestType.ReaderGC, GCType.Wait); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MARSTest/MARSTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MARSTest/MARSTest.cs index 0bd02d35b9..4003ffec00 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MARSTest/MARSTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MARSTest/MARSTest.cs @@ -35,7 +35,7 @@ public static void NamedPipesMARSTest() } #if DEBUG - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void MARSAsyncTimeoutTest() { using (SqlConnection connection = new SqlConnection(_connStr)) @@ -132,33 +132,36 @@ public static void MARSSyncTimeoutTest() [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static void MARSSyncBusyReaderTest() { + var query = "SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10"; + var rowCount = 10; + using (SqlConnection conn = new SqlConnection(_connStr)) { conn.Open(); - using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) + using (SqlDataReader reader1 = (new SqlCommand(query, conn)).ExecuteReader()) { int rows1 = 0; while (reader1.Read()) { rows1++; - if (rows1 == 415) + if (rows1 == rowCount / 2) break; } - Assert.True(rows1 == 415, "MARSSyncBusyReaderTest Failure, #1"); + Assert.True(rows1 == rowCount / 2, "MARSSyncBusyReaderTest Failure, #1"); - using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) + using (SqlDataReader reader2 = (new SqlCommand(query, conn)).ExecuteReader()) { int rows2 = 0; while (reader2.Read()) { rows2++; - if (rows2 == 415) + if (rows2 == rowCount / 2) break; } - Assert.True(rows2 == 415, "MARSSyncBusyReaderTest Failure, #2"); + Assert.True(rows2 == rowCount / 2, "MARSSyncBusyReaderTest Failure, #2"); - for (int i = 415; i < 830; i++) + for (int i = rowCount / 2; i < rowCount; i++) { Assert.True(reader1.Read() && reader2.Read(), "MARSSyncBusyReaderTest Failure #3"); Assert.True(reader1.GetInt32(0) == reader2.GetInt32(0), @@ -180,11 +183,11 @@ public static void MARSSyncExecuteNonQueryTest() { conn.Open(); - using (SqlCommand comm1 = new SqlCommand("select * from Orders", conn)) - using (SqlCommand comm2 = new SqlCommand("select * from Orders", conn)) - using (SqlCommand comm3 = new SqlCommand("select * from Orders", conn)) - using (SqlCommand comm4 = new SqlCommand("select * from Orders", conn)) - using (SqlCommand comm5 = new SqlCommand("select * from Orders", conn)) + using (SqlCommand comm1 = new SqlCommand("select 1", conn)) + using (SqlCommand comm2 = new SqlCommand("select 1", conn)) + using (SqlCommand comm3 = new SqlCommand("select 1", conn)) + using (SqlCommand comm4 = new SqlCommand("select 1", conn)) + using (SqlCommand comm5 = new SqlCommand("select 1", conn)) { comm1.ExecuteNonQuery(); comm2.ExecuteNonQuery(); @@ -198,50 +201,53 @@ public static void MARSSyncExecuteNonQueryTest() [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static void MARSSyncExecuteReaderTest1() { + var query = "SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10"; + var rowCount = 10; + using (SqlConnection conn = new SqlConnection(_connStr)) { conn.Open(); - using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) - using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) - using (SqlDataReader reader3 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) - using (SqlDataReader reader4 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) - using (SqlDataReader reader5 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) + using (SqlDataReader reader1 = (new SqlCommand(query, conn)).ExecuteReader()) + using (SqlDataReader reader2 = (new SqlCommand(query, conn)).ExecuteReader()) + using (SqlDataReader reader3 = (new SqlCommand(query, conn)).ExecuteReader()) + using (SqlDataReader reader4 = (new SqlCommand(query, conn)).ExecuteReader()) + using (SqlDataReader reader5 = (new SqlCommand(query, conn)).ExecuteReader()) { int rows = 0; while (reader1.Read()) { rows++; } - Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #1"); + Assert.True(rows == rowCount, "MARSSyncExecuteReaderTest1 failure, #1"); rows = 0; while (reader2.Read()) { rows++; } - Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #2"); + Assert.True(rows == rowCount, "MARSSyncExecuteReaderTest1 failure, #2"); rows = 0; while (reader3.Read()) { rows++; } - Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #3"); + Assert.True(rows == rowCount, "MARSSyncExecuteReaderTest1 failure, #3"); rows = 0; while (reader4.Read()) { rows++; } - Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #4"); + Assert.True(rows == rowCount, "MARSSyncExecuteReaderTest1 failure, #4"); rows = 0; while (reader5.Read()) { rows++; } - Assert.True(rows == 830, "MARSSyncExecuteReaderTest1 failure, #5"); + Assert.True(rows == rowCount, "MARSSyncExecuteReaderTest1 failure, #5"); } } } @@ -254,17 +260,13 @@ public static void MARSSyncExecuteReaderTest2() { conn.Open(); - using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) - using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) - using (SqlDataReader reader3 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) - using (SqlDataReader reader4 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) - using (SqlDataReader reader5 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) + using (SqlDataReader reader1 = (new SqlCommand("select 1", conn)).ExecuteReader()) + using (SqlDataReader reader2 = (new SqlCommand("select 1", conn)).ExecuteReader()) + using (SqlDataReader reader3 = (new SqlCommand("select 1", conn)).ExecuteReader()) + using (SqlDataReader reader4 = (new SqlCommand("select 1", conn)).ExecuteReader()) + using (SqlDataReader reader5 = (new SqlCommand("select 1", conn)).ExecuteReader()) { - for (int i = 0; i < 830; i++) - { - Assert.True(reader1.Read() && reader2.Read() && reader3.Read() && reader4.Read() && reader5.Read(), "MARSSyncExecuteReaderTest2 Failure #1"); - } - + Assert.True(reader1.Read() && reader2.Read() && reader3.Read() && reader4.Read() && reader5.Read(), "MARSSyncExecuteReaderTest2 Failure #1"); Assert.False(reader1.Read() || reader2.Read() || reader3.Read() || reader4.Read() || reader5.Read(), "MARSSyncExecuteReaderTest2 Failure #2"); } } @@ -277,28 +279,25 @@ public static void MARSSyncExecuteReaderTest3() { conn.Open(); - using (SqlDataReader reader1 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) - using (SqlDataReader reader2 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) - using (SqlDataReader reader3 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) - using (SqlDataReader reader4 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) - using (SqlDataReader reader5 = (new SqlCommand("select * from Orders", conn)).ExecuteReader()) + using (SqlDataReader reader1 = (new SqlCommand("select 1", conn)).ExecuteReader()) + using (SqlDataReader reader2 = (new SqlCommand("select 1", conn)).ExecuteReader()) + using (SqlDataReader reader3 = (new SqlCommand("select 1", conn)).ExecuteReader()) + using (SqlDataReader reader4 = (new SqlCommand("select 1", conn)).ExecuteReader()) + using (SqlDataReader reader5 = (new SqlCommand("select 1", conn)).ExecuteReader()) { - for (int i = 0; i < 830; i++) - { - Assert.True(reader1.Read() && reader2.Read() && reader3.Read() && reader4.Read() && reader5.Read(), "MARSSyncExecuteReaderTest3 Failure #1"); - - // All reads succeeded - check values. - Assert.True(reader1.GetInt32(0) == reader2.GetInt32(0) && - reader2.GetInt32(0) == reader3.GetInt32(0) && - reader3.GetInt32(0) == reader4.GetInt32(0) && - reader4.GetInt32(0) == reader5.GetInt32(0), - "MARSSyncExecuteReaderTest3, Failure #2" + "\n" + - "reader1.GetInt32(0): " + reader1.GetInt32(0) + "\n" + - "reader2.GetInt32(0): " + reader2.GetInt32(0) + "\n" + - "reader3.GetInt32(0): " + reader3.GetInt32(0) + "\n" + - "reader4.GetInt32(0): " + reader4.GetInt32(0) + "\n" + - "reader5.GetInt32(0): " + reader5.GetInt32(0)); - } + Assert.True(reader1.Read() && reader2.Read() && reader3.Read() && reader4.Read() && reader5.Read(), "MARSSyncExecuteReaderTest3 Failure #1"); + + // All reads succeeded - check values. + Assert.True(reader1.GetInt32(0) == reader2.GetInt32(0) && + reader2.GetInt32(0) == reader3.GetInt32(0) && + reader3.GetInt32(0) == reader4.GetInt32(0) && + reader4.GetInt32(0) == reader5.GetInt32(0), + "MARSSyncExecuteReaderTest3, Failure #2" + "\n" + + "reader1.GetInt32(0): " + reader1.GetInt32(0) + "\n" + + "reader2.GetInt32(0): " + reader2.GetInt32(0) + "\n" + + "reader3.GetInt32(0): " + reader3.GetInt32(0) + "\n" + + "reader4.GetInt32(0): " + reader4.GetInt32(0) + "\n" + + "reader5.GetInt32(0): " + reader5.GetInt32(0)); Assert.False(reader1.Read() || reader2.Read() || reader3.Read() || reader4.Read() || reader5.Read(), "MARSSyncExecuteReaderTest3 Failure #3"); } @@ -312,15 +311,15 @@ public static void MARSSyncExecuteReaderTest4() { conn.Open(); - using (SqlDataReader reader1 = (new SqlCommand("select * from Orders where OrderID = 10248", conn)).ExecuteReader()) - using (SqlDataReader reader2 = (new SqlCommand("select * from Orders where OrderID = 10249", conn)).ExecuteReader()) - using (SqlDataReader reader3 = (new SqlCommand("select * from Orders where OrderID = 10250", conn)).ExecuteReader()) + using (SqlDataReader reader1 = (new SqlCommand("select 1", conn)).ExecuteReader()) + using (SqlDataReader reader2 = (new SqlCommand("select 2", conn)).ExecuteReader()) + using (SqlDataReader reader3 = (new SqlCommand("select 3", conn)).ExecuteReader()) { Assert.True(reader1.Read() && reader2.Read() && reader3.Read(), "MARSSyncExecuteReaderTest4 failure #1"); - Assert.True(reader1.GetInt32(0) == 10248 && - reader2.GetInt32(0) == 10249 && - reader3.GetInt32(0) == 10250, + Assert.True(reader1.GetInt32(0) == 1 && + reader2.GetInt32(0) == 2 && + reader3.GetInt32(0) == 3, "MARSSyncExecuteReaderTest4 failure #2"); Assert.False(reader1.Read() || reader2.Read() || reader3.Read(), "MARSSyncExecuteReaderTest4 failure #3"); @@ -331,7 +330,7 @@ public static void MARSSyncExecuteReaderTest4() [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public static void MARSMultiDataReaderErrTest() { - string queryString = "SELECT TOP 3 OrderID, CustomerID FROM dbo.Orders"; + string queryString = "SELECT 1"; // With MARS on, one SqlCommand cannot have multiple DataReaders using (SqlConnection conn = new SqlConnection(_connStr)) @@ -374,5 +373,3 @@ public static void MARSMultiDataReaderErrTest() } } } - - diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MirroringTest/ConnectionOnMirroringTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MirroringTest/ConnectionOnMirroringTest.cs index 412cac5858..93101d5d38 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MirroringTest/ConnectionOnMirroringTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/MirroringTest/ConnectionOnMirroringTest.cs @@ -14,7 +14,8 @@ public static class ConnectionOnMirroringTest { private static ManualResetEvent workerCompletedEvent = new ManualResetEvent(false); - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] + // Synapse: Invalid object name 'sys.database_mirroring'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestMultipleConnectionToMirroredServer() { string mirroringStateDesc; diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParallelTransactionsTest/ParallelTransactionsTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParallelTransactionsTest/ParallelTransactionsTest.cs index 000206a43b..efc99ea757 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParallelTransactionsTest/ParallelTransactionsTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParallelTransactionsTest/ParallelTransactionsTest.cs @@ -10,7 +10,8 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests public static class ParallelTransactionsTest { #region <> - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove dependency from Northwind database + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void BasicParallelTest_shouldThrowsUnsupported() { string connectionString = DataTestUtility.TCPConnectionString; @@ -66,7 +67,8 @@ private static void BasicParallelTest(string connectionString, string tempTableN #endregion #region <> - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Remove dependency from Northwind database + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void MultipleExecutesInSameTransactionTest_shouldThrowsUnsupported() { string connectionString = DataTestUtility.TCPConnectionString; diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs index 865fd62cab..b179b82d6a 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs @@ -103,7 +103,8 @@ public static void CodeCoverageSqlClient() DataTestUtility.AssertThrowsWrapper(() => new SqlCommand().Parameters.Remove(new SqlParameter()), "Attempted to remove an SqlParameter that is not contained by this SqlParameterCollection."); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Parse error at line: 1, column: 12: Incorrect syntax near 'IF'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void Test_Copy_SqlParameter() { using (var conn = new SqlConnection(s_connString)) @@ -153,7 +154,8 @@ public static void Test_Copy_SqlParameter() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove dependency on Northwind database + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void Test_SqlParameter_Constructor() { using (var conn = new SqlConnection(s_connString)) @@ -232,7 +234,8 @@ public static void Test_WithDecimalValue_ShouldReturnDecimal() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Unsupported parameter type found while parsing RPC request. The request has been terminated. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void Test_WithGuidValue_ShouldReturnGuid() { using (var conn = new SqlConnection(s_connString)) @@ -246,6 +249,7 @@ public static void Test_WithGuidValue_ShouldReturnGuid() } } + // Synapse: Parse error at line: 1, column: 8: Incorrect syntax near 'TYPE'. [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public static void TestParametersWithDatatablesTVPInsert() { @@ -382,7 +386,8 @@ public static void TestScaledDecimalParameter_BulkCopy(string connectionString, } } - [Theory] + // Synapse: Parse error at line: 2, column: 8: Incorrect syntax near 'TYPE'. + [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.IsNotAzureSynapse))] [ClassData(typeof(ConnectionStringsProvider))] public static void TestScaledDecimalTVP_CommandSP(string connectionString, bool truncateScaledDecimal) { diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlAdapterUpdateBatch.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlAdapterUpdateBatch.cs index e30f019282..90d413a66d 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlAdapterUpdateBatch.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/SqlAdapterUpdateBatch.cs @@ -11,7 +11,8 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public class SqlAdapterUpdateBatch { - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Incorrect syntax near 'IF'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void SqlAdapterTest() { string tableName = DataTestUtility.GetUniqueNameForSqlServer("Adapter"); 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 2dbb2648ac..7c4e81cfd5 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/TvpTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/TvpTest.cs @@ -41,7 +41,8 @@ public class TvpTest // data value and server consts private string _connStr; - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: The statement failed. Column 'blob' has a data type that cannot participate in a columnstore index. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void TestMain() { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); // To keep things consistent since we output dates as strings diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SplitPacketTest/SplitPacketTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SplitPacketTest/SplitPacketTest.cs index ffbd4ab7ec..4d4313a000 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SplitPacketTest/SplitPacketTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SplitPacketTest/SplitPacketTest.cs @@ -11,7 +11,7 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests { - [ActiveIssue(5538)] + [ActiveIssue(5538)] // Only testable on localhost public class SplitPacketTest { private int Port = -1; diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/DataConversionErrorMessageTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/DataConversionErrorMessageTest.cs index 9b56183ccf..f9d32952d0 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/DataConversionErrorMessageTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/DataConversionErrorMessageTest.cs @@ -101,7 +101,10 @@ public DataConversionErrorMessageTest(InitialDatabase fixture) _fixture = fixture; } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Column count in target table does not match column count specified in input. + // If BCP command, ensure format file column count matches destination table. + // If SSIS data import, check column mappings are consistent with target. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void StringToIntErrorMessageTest() { Assert.True(StringToIntTest(_fixture.Connection, _fixture.TableName, SourceType.DataTable), "Did not get any exceptions for DataTable when converting data from 'string' to 'int' datatype!"); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs index 9c1d60e07c..6669132ae5 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlBulkCopyTest/SqlBulkCopyTest.cs @@ -11,6 +11,7 @@ public class SqlBulkCopyTest { private string _connStr = null; private static bool IsAzureServer() => !DataTestUtility.IsNotAzureServer(); + private static bool IsNotAzureSynapse => DataTestUtility.IsNotAzureSynapse(); private static bool AreConnectionStringsSetup() => DataTestUtility.AreConnStringsSetup(); public SqlBulkCopyTest() @@ -24,7 +25,8 @@ public string AddGuid(string stringin) return stringin; } - [ConditionalFact(nameof(AreConnectionStringsSetup), nameof(IsAzureServer))] + // Synapse: Promote Transaction not supported by Azure Synapse + [ConditionalFact(nameof(AreConnectionStringsSetup), nameof(IsNotAzureSynapse), nameof(IsAzureServer))] public void AzureDistributedTransactionTest() { AzureDistributedTransaction.Test(); @@ -246,31 +248,37 @@ public void DestinationTableNameWithSpecialCharTest() DestinationTableNameWithSpecialChar.Test(_connStr, AddGuid("SqlBulkCopyTest_DestinationTableNameWithSpecialChar")); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove dependency on Northwind database + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void OrderHintTest() { OrderHint.Test(_connStr, AddGuid("SqlBulkCopyTest_OrderHint"), AddGuid("SqlBulkCopyTest_OrderHint2")); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Cannot create more than one clustered index on table ''. + // Drop the existing clustered index 'ClusteredIndex_fe3d8c967ac142468ec4f81ff1faaa50' before creating another. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void OrderHintAsyncTest() { OrderHintAsync.Test(_connStr, AddGuid("SqlBulkCopyTest_OrderHintAsync"), AddGuid("SqlBulkCopyTest_OrderHintAsync2")); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Remove dependency on Northwind database. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void OrderHintMissingTargetColumnTest() { OrderHintMissingTargetColumn.Test(_connStr, AddGuid("SqlBulkCopyTest_OrderHintMissingTargetColumn")); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Remove dependency on Northwind database. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void OrderHintDuplicateColumnTest() { OrderHintDuplicateColumn.Test(_connStr, AddGuid("SqlBulkCopyTest_OrderHintDuplicateColumn")); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: 111212;Operation cannot be performed within a transaction. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void OrderHintTransactionTest() { OrderHintTransaction.Test(_connStr, AddGuid("SqlBulkCopyTest_OrderHintTransaction")); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlCommand/SqlCommandCancelTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlCommand/SqlCommandCancelTest.cs index accf28148a..601bffa42a 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlCommand/SqlCommandCancelTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlCommand/SqlCommandCancelTest.cs @@ -16,7 +16,8 @@ public static class SqlCommandCancelTest private static readonly string tcp_connStr = (new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString) { PacketSize = 512 }).ConnectionString; private static readonly string np_connStr = (new SqlConnectionStringBuilder(DataTestUtility.NPConnectionString) { PacketSize = 512 }).ConnectionString; - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Remove dependency on Northwind database + WAITFOR not supported + ';' not supported + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void PlainCancelTest() { PlainCancel(tcp_connStr); @@ -28,8 +29,9 @@ public static void PlainCancelTestNP() { PlainCancel(np_connStr); } - - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + + // Synapse: Remove dependency on Northwind database + WAITFOR not supported + ';' not supported + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void PlainMARSCancelTest() { PlainCancel((new SqlConnectionStringBuilder(tcp_connStr) { MultipleActiveResultSets = true }).ConnectionString); @@ -42,7 +44,8 @@ public static void PlainMARSCancelTestNP() PlainCancel((new SqlConnectionStringBuilder(np_connStr) { MultipleActiveResultSets = true }).ConnectionString); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Remove dependency on Northwind database + WAITFOR not supported + ';' not supported + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void PlainCancelTestAsync() { PlainCancelAsync(tcp_connStr); @@ -55,7 +58,8 @@ public static void PlainCancelTestAsyncNP() PlainCancelAsync(np_connStr); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Remove dependency from Northwind database + WAITFOR not supported + ';' not supported. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void PlainMARSCancelTestAsync() { PlainCancelAsync((new SqlConnectionStringBuilder(tcp_connStr) { MultipleActiveResultSets = true }).ConnectionString); @@ -118,7 +122,8 @@ private static void PlainCancelAsync(string connString) } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Remove dependency from Northwind database + WAITFOR not supported + ';' not supported. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public static void MultiThreadedCancel_NonAsync() { MultiThreadedCancel(tcp_connStr, false); @@ -131,7 +136,8 @@ public static void MultiThreadedCancel_NonAsyncNP() MultiThreadedCancel(np_connStr, false); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Remove dependency from Northwind database + WAITFOR not supported + ';' not supported. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void MultiThreadedCancel_Async() { MultiThreadedCancel(tcp_connStr, true); @@ -144,7 +150,8 @@ public static void MultiThreadedCancel_AsyncNP() MultiThreadedCancel(np_connStr, true); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: WAITFOR not supported + ';' not supported. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public static void TimeoutCancel() { TimeoutCancel(tcp_connStr); @@ -186,7 +193,8 @@ public static void TimeOutDuringReadNP() TimeOutDuringRead(np_connStr); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: WAITFOR not supported + ';' not supported. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void CancelDoesNotWait() { CancelDoesNotWait(tcp_connStr); @@ -199,7 +207,8 @@ public static void CancelDoesNotWaitNP() CancelDoesNotWait(np_connStr); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: WAITFOR not supported + ';' not supported. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void AsyncCancelDoesNotWait() { AsyncCancelDoesNotWait(tcp_connStr).Wait(); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlCommand/SqlCommandSetTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlCommand/SqlCommandSetTest.cs index e6810aa025..26b11055c2 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlCommand/SqlCommandSetTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlCommand/SqlCommandSetTest.cs @@ -11,7 +11,8 @@ public class SqlCommandSetTest { private static Assembly mds = Assembly.GetAssembly(typeof(SqlConnection)); - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: The statement failed. Column 'ByteArrayColumn' has a data type that cannot participate in a columnstore index. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void TestByteArrayParameters() { string tableName = DataTestUtility.GetUniqueNameForSqlServer("CMD"); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlStatisticsTest/SqlStatisticsTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlStatisticsTest/SqlStatisticsTest.cs index 133ac55411..f04bc38a4d 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlStatisticsTest/SqlStatisticsTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/SqlStatisticsTest/SqlStatisticsTest.cs @@ -20,7 +20,7 @@ public static void TestRetrieveStatistics() { startTime = DateTime.Now; SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString); - string text = "SELECT TOP 2000 * from [dbo].[Order Details]"; + string text = "SELECT TOP 2000 * from [sys].[all_views]"; using (SqlCommand command = new SqlCommand(text)) { connection.StatisticsEnabled = true; diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionEnlistmentTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionEnlistmentTest.cs index 82b1914a1b..98a4cb755d 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionEnlistmentTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionEnlistmentTest.cs @@ -11,39 +11,41 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public class TransactionEnlistmentTest { + // TODO Synapse: Cannot find data type 'text'. [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public static void TestAutoEnlistment_TxScopeComplete() { RunTestSet(TestCase_AutoEnlistment_TxScopeComplete); } + // TODO Synapse: Cannot find data type 'text'. [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureServer))] public static void TestAutoEnlistment_TxScopeNonComplete() { RunTestSet(TestCase_AutoEnlistment_TxScopeNonComplete); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Cannot find data type 'text'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestManualEnlistment_Enlist() { RunTestSet(TestCase_ManualEnlistment_Enlist); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Cannot find data type 'text'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestManualEnlistment_NonEnlist() { RunTestSet(TestCase_ManualEnlistment_NonEnlist); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Cannot find data type 'text'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestManualEnlistment_Enlist_TxScopeComplete() { RunTestSet(TestCase_ManualEnlistment_Enlist_TxScopeComplete); } - - - private static void TestCase_AutoEnlistment_TxScopeComplete() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString); @@ -166,9 +168,6 @@ private static void TestCase_ManualEnlistment_Enlist_TxScopeComplete() Assert.True(string.Equals(result.Rows[0][0], InputCol2)); } - - - private static string TestTableName; private static string ConnectionString; private const int InputCol1 = 1; diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.cs index 6f2407a01f..b223a709e9 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionTest.cs @@ -10,7 +10,8 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public static class TransactionTest { - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Enforced unique constraints are not supported. To create an unenforced unique constraint you must include the NOT ENFORCED syntax as part of your statement. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestMain() { new TransactionTestWorker((new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString) { MultipleActiveResultSets = true }).ConnectionString).StartTest(); diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/SqlServerTypesTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/SqlServerTypesTest.cs index ae29f5e6c4..1d90c31261 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/SqlServerTypesTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/SqlServerTypesTest.cs @@ -16,7 +16,8 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public static class SqlServerTypesTest { - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 48: Incorrect syntax near 'hierarchyid'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void GetSchemaTableTest() { string db = new SqlConnectionStringBuilder(DataTestUtility.TCPConnectionString).InitialCatalog; @@ -41,8 +42,9 @@ public static void GetSchemaTableTest() } } + // Synapse: Parse error at line: 1, column: 48: Incorrect syntax near 'hierarchyid'. [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void GetValueTestThrowsExceptionOnNetCore() { using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -60,8 +62,9 @@ public static void GetValueTestThrowsExceptionOnNetCore() } } + // Synapse: Parse error at line: 1, column: 48: Incorrect syntax near 'hierarchyid'. [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp)] - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void GetValueTest() { using (SqlConnection conn = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -77,7 +80,8 @@ public static void GetValueTest() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 8: Incorrect syntax near 'hierarchyid'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestUdtZeroByte() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -96,13 +100,15 @@ public static void TestUdtZeroByte() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 8: Incorrect syntax near 'hierarchyid'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestUdtSqlDataReaderGetSqlBytesSequentialAccess() { TestUdtSqlDataReaderGetSqlBytes(CommandBehavior.SequentialAccess); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 8: Incorrect syntax near 'hierarchyid'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestUdtSqlDataReaderGetSqlBytes() { TestUdtSqlDataReaderGetSqlBytes(CommandBehavior.Default); @@ -139,13 +145,15 @@ private static void TestUdtSqlDataReaderGetSqlBytes(CommandBehavior behavior) } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 8: Incorrect syntax near 'hierarchyid'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestUdtSqlDataReaderGetBytesSequentialAccess() { TestUdtSqlDataReaderGetBytes(CommandBehavior.SequentialAccess); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 8: Incorrect syntax near 'hierarchyid'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestUdtSqlDataReaderGetBytes() { TestUdtSqlDataReaderGetBytes(CommandBehavior.Default); @@ -195,13 +203,15 @@ private static void TestUdtSqlDataReaderGetBytes(CommandBehavior behavior) } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 8: Incorrect syntax near 'hierarchyid'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestUdtSqlDataReaderGetStreamSequentialAccess() { TestUdtSqlDataReaderGetStream(CommandBehavior.SequentialAccess); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 8: Incorrect syntax near 'hierarchyid'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestUdtSqlDataReaderGetStream() { TestUdtSqlDataReaderGetStream(CommandBehavior.Default); @@ -259,7 +269,8 @@ private static void TestUdtSqlDataReaderGetStream(CommandBehavior behavior) } } #if netcoreapp - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 41: Incorrect syntax near 'hierarchyid'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestUdtSchemaMetadata() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -297,7 +308,8 @@ public static void TestUdtSchemaMetadata() } } #endif - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 8: Incorrect syntax near 'geometry'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestUdtParameterSetSqlByteValue() { const string ExpectedPointValue = "POINT (1 1)"; @@ -331,7 +343,8 @@ public static void TestUdtParameterSetSqlByteValue() } } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 8: Incorrect syntax near 'geometry'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestUdtParameterSetRawByteValue() { const string ExpectedPointValue = "POINT (1 1)"; diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest2.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest2.cs index 740793e702..f34dc2833a 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest2.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest2.cs @@ -12,6 +12,7 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests { [ActiveIssue(5536)] + // TODO Synapse: Remove dependency from UDTTest Database public class UdtTest2 { private string _connStr = null; diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Utf8SupportTest/Utf8SupportTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Utf8SupportTest/Utf8SupportTest.cs index d324c7e3ac..c6bc56d9f4 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Utf8SupportTest/Utf8SupportTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Utf8SupportTest/Utf8SupportTest.cs @@ -8,7 +8,8 @@ namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public static class Utf8SupportTest { - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsUTF8Supported))] + // Synapse: 'CONNECTIONPROPERTY' is not a recognized built-in function name. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsUTF8Supported), nameof(DataTestUtility.IsNotAzureSynapse))] public static void CheckSupportUtf8ConnectionProperty() { using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) @@ -27,5 +28,7 @@ public static void CheckSupportUtf8ConnectionProperty() } } } + + // TODO: Write tests using UTF8 collations } } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/WeakRefTest/WeakRefTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/WeakRefTest/WeakRefTest.cs index 7505b6648d..13692fac8d 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/WeakRefTest/WeakRefTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/WeakRefTest/WeakRefTest.cs @@ -41,7 +41,8 @@ private enum TransactionTestType TransactionGCConnectionClose, } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // TODO Synapse: Remove dependency on Northwind database + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestReaderNonMars() { string connString = diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/WeakRefTestYukonSpecific/WeakRefTestYukonSpecific.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/WeakRefTestYukonSpecific/WeakRefTestYukonSpecific.cs index 504e26bf5f..5835bb9e69 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/WeakRefTestYukonSpecific/WeakRefTestYukonSpecific.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/WeakRefTestYukonSpecific/WeakRefTestYukonSpecific.cs @@ -16,8 +16,9 @@ public static class WeakRefTestYukonSpecific private const string DATABASE_NAME = "master"; private const int CONCURRENT_COMMANDS = 5; + // TODO Synapse: Remove dependency on Northwind database [ActiveIssue(6643, TestPlatforms.AnyUnix)] - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public static void TestReaderMars() { string connectionString = diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/TracingTests/DiagnosticTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/TracingTests/DiagnosticTest.cs index c95cd8c1df..7595506444 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/TracingTests/DiagnosticTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/TracingTests/DiagnosticTest.cs @@ -201,7 +201,8 @@ public void ExecuteReaderWithCommandBehaviorTest() }).Dispose(); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 27: Incorrect syntax near 'for'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void ExecuteXmlReaderTest() { RemoteExecutor.Invoke(cs => @@ -388,7 +389,8 @@ public void ExecuteReaderAsyncErrorTest() }).Dispose(); } - [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] + // Synapse: Parse error at line: 1, column: 27: Incorrect syntax near 'for'. + [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup), nameof(DataTestUtility.IsNotAzureSynapse))] public void ExecuteXmlReaderAsyncTest() { RemoteExecutor.Invoke(cs => diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/TracingTests/EventSourceTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/TracingTests/EventSourceTest.cs index a6a1d2287c..8156dd6237 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/TracingTests/EventSourceTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/TracingTests/EventSourceTest.cs @@ -17,7 +17,7 @@ public void EventSourceTestAll() using (SqlConnection connection = new SqlConnection(DataTestUtility.TCPConnectionString)) { connection.Open(); - using (SqlCommand command = new SqlCommand("SELECT * From [Customers]", connection)) + using (SqlCommand command = new SqlCommand("SELECT @@VERSION", connection)) using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) diff --git a/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Config.cs b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Config.cs index 611037ae92..f0e71edadb 100644 --- a/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Config.cs +++ b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/Config.cs @@ -31,6 +31,7 @@ public class Config public string DNSCachingConnString = null; public string DNSCachingServerCR = null; // this is for the control ring public string DNSCachingServerTR = null; // this is for the tenant ring + public bool IsAzureSynapse = false; // True for Azure Data Warehouse/Synapse public bool IsDNSCachingSupportedCR = false; // this is for the control ring public bool IsDNSCachingSupportedTR = false; // this is for the tenant ring public string EnclaveAzureDatabaseConnString = null; diff --git a/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/config.default.json b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/config.default.json index e80b223ea9..2d1fa10a65 100644 --- a/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/config.default.json +++ b/src/Microsoft.Data.SqlClient/tests/tools/Microsoft.Data.SqlClient.TestUtilities/config.default.json @@ -17,5 +17,6 @@ "SupportsLocalDb": false, "SupportsFileStream": false, "UseManagedSNIOnWindows": false, - "EnclaveAzureDatabaseConnString": "" + "IsAzureSynapse": false, + "EnclaveAzureDatabaseConnString": "" } From 81052d61693b96b76c9ef830de8819211a1cebc6 Mon Sep 17 00:00:00 2001 From: Erik Ejlskov Jensen Date: Fri, 18 Sep 2020 02:19:18 +0200 Subject: [PATCH 24/24] Feature | Add "Command Timeout" connection string option (#722) --- .../Microsoft.Data.SqlClient/SqlCommand.xml | 1 + .../SqlConnection.xml | 18 ++++ .../SqlConnectionStringBuilder.xml | 17 ++++ .../netcore/ref/Microsoft.Data.SqlClient.cs | 7 ++ .../Data/Common/DbConnectionStringCommon.cs | 4 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 16 +++- .../Microsoft/Data/SqlClient/SqlConnection.cs | 10 +++ .../Data/SqlClient/SqlConnectionString.cs | 13 +++ .../SqlClient/SqlConnectionStringBuilder.cs | 28 +++++++ .../netfx/ref/Microsoft.Data.SqlClient.cs | 7 ++ .../Data/Common/DbConnectionStringCommon.cs | 4 +- .../Microsoft/Data/SqlClient/SqlCommand.cs | 17 ++-- .../Microsoft/Data/SqlClient/SqlConnection.cs | 14 ++++ .../Data/SqlClient/SqlConnectionString.cs | 12 +++ .../SqlClient/SqlConnectionStringBuilder.cs | 32 ++++++++ .../tests/FunctionalTests/SqlCommandTest.cs | 16 ++++ .../SqlConnectionStringBuilderTest.cs | 3 + .../FunctionalTests/SqlConnectionTest.cs | 82 +++++++++++++++++++ 18 files changed, 288 insertions(+), 13 deletions(-) diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml index a79ccebf4e..4dbe1f6511 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlCommand.xml @@ -1240,6 +1240,7 @@ For example, with a 30 second time out, if + The value set is less than 0. diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml index 8e7e927187..24aac534e4 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml @@ -472,6 +472,23 @@ The connection string contains . The list of trusted master key paths for the column encryption. To be added. + + + Gets the default wait time (in seconds) before terminating the attempt to execute a command and generating an error. The default is 30 seconds. + + + The time in seconds to wait for the command to execute. The default is 30 seconds. + + + + + Gets or sets the string used to open a SQL Server database. The connection string that includes the source database name, and other parameters needed to establish the initial connection. The default value is an empty string. @@ -517,6 +534,7 @@ The connection string contains . |AttachDBFilename

-or-

Extended Properties

-or-

Initial File Name|N/A|The name of the primary database file, including the full path name of an attachable database. AttachDBFilename is only supported for primary data files with an .mdf extension.

If the value of the AttachDBFileName key is specified in the connection string, the database is attached and becomes the default database for the connection.

If this key is not specified and if the database was previously attached, the database will not be reattached. The previously attached database will be used as the default database for the connection.

If this key is specified together with the AttachDBFileName key, the value of this key will be used as the alias. However, if the name is already used in another attached database, the connection will fail.

The path may be absolute or relative by using the DataDirectory substitution string. If DataDirectory is used, the database file must exist within a subdirectory of the directory pointed to by the substitution string. **Note:** Remote server, HTTP, and UNC path names are not supported.

The database name must be specified with the keyword 'database' (or one of its aliases) as in the following:

"AttachDbFileName=|DataDirectory|\data\YourDB.mdf;integrated security=true;database=YourDatabase"

An error will be generated if a log file exists in the same directory as the data file and the 'database' keyword is used when attaching the primary data file. In this case, remove the log file. Once the database is attached, a new log file will be automatically generated based on the physical path.| |Authentication|N/A|The authentication method used for [Connecting to SQL Database By Using Azure Active Directory Authentication](https://azure.microsoft.com/documentation/articles/sql-database-aad-authentication/#7-connect-to-your-database-by-using-azure-active-directory-identities).

Valid values are:

`Active Directory Integrated`, `Active Directory Interactive`, `Active Directory Password`, `Sql Password`. Currently `Active Directory Integrated` and `Active Directory Interactive` modes of authentication are supported only for .NET Framework. | |Column Encryption Setting|N/A|Enables or disables [Always Encrypted](/sql/relational-databases/security/encryption/always-encrypted-database-engine?view=sql-server-2017) functionality for the connection.| +|Command Timeout|30|The default wait time (in seconds) before terminating the attempt to execute a command and generating an error.

Valid values are greater than or equal to 0 and less than or equal to 2147483647.| |Connect Timeout

-or-

Connection Timeout

-or-

Timeout|15|The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.

Valid values are greater than or equal to 0 and less than or equal to 2147483647.

When opening a connection to a Azure SQL Database, set the connection timeout to 30 seconds.| |Connection Lifetime

-or-

Load Balance Timeout|0|When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by `Connection Lifetime`. This is useful in clustered configurations to force load balancing between a running server and a server just brought online.

A value of zero (0) causes pooled connections to have the maximum connection timeout.| |Connect Retry Count

-or-

ConnectRetryCount|1|Controls the number of reconnection attempts after the client identifies an idle connection failure. Valid values are 0 to 255. The default is 1. 0 means do not attempt to reconnect (disable connection resiliency).

For additional information about idle connection resiliency, see [Technical Article - Idle Connection Resiliency](https://go.microsoft.com/fwlink/?LinkId=393996).| diff --git a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionStringBuilder.xml b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionStringBuilder.xml index 1992da198a..98d4d5cc70 100644 --- a/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionStringBuilder.xml +++ b/doc/snippets/Microsoft.Data.SqlClient/SqlConnectionStringBuilder.xml @@ -195,6 +195,23 @@ Modified: Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security The column encryption settings for the connection string builder. To be added. + + + The default wait time (in seconds) before terminating the attempt to execute a command and generating an error. The default is 30 seconds. + + + The time in seconds to wait for the command to execute. The default is 30 seconds. + + + connection string. + + ]]> + + The value set is less than 0. + Obsolete. Gets or sets a Boolean value that indicates whether the connection is reset when drawn from the connection pool. The value of the property, or true if no value has been supplied. diff --git a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs index 47c806d387..3a75ca8d09 100644 --- a/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs +++ b/src/Microsoft.Data.SqlClient/netcore/ref/Microsoft.Data.SqlClient.cs @@ -590,6 +590,9 @@ public SqlConnection(string connectionString, Microsoft.Data.SqlClient.SqlCreden internal string SQLDNSCachingSupportedStateBeforeRedirect { get { throw null; } } object System.ICloneable.Clone() { throw null; } + /// + [System.ComponentModel.DesignerSerializationVisibilityAttribute(0)] + public int CommandTimeout { get { throw null; } } /// [System.ComponentModel.DefaultValueAttribute("")] [System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] @@ -712,6 +715,10 @@ public SqlConnectionStringBuilder(string connectionString) { } [System.ComponentModel.DisplayNameAttribute("Authentication")] [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public Microsoft.Data.SqlClient.SqlAuthenticationMethod Authentication { get { throw null; } set { } } + /// + [System.ComponentModel.DisplayNameAttribute("Command Timeout")] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] + public int CommandTimeout { get { throw null; } set { } } /// [System.ComponentModel.DisplayNameAttribute("Connect Retry Count")] [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionStringCommon.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionStringCommon.cs index 7bd9f2c909..66a04e5ff5 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionStringCommon.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/Common/DbConnectionStringCommon.cs @@ -487,7 +487,7 @@ internal static ApplicationIntent ConvertToApplicationIntent(string keyword, obj internal static bool IsValidAuthenticationTypeValue(SqlAuthenticationMethod value) { - Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 6, "SqlAuthenticationMethod enum has changed, update needed"); + Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 7, "SqlAuthenticationMethod enum has changed, update needed"); return value == SqlAuthenticationMethod.SqlPassword || value == SqlAuthenticationMethod.ActiveDirectoryPassword || value == SqlAuthenticationMethod.ActiveDirectoryIntegrated @@ -676,6 +676,7 @@ internal static partial class DbConnectionStringDefaults internal const ApplicationIntent ApplicationIntent = Microsoft.Data.SqlClient.ApplicationIntent.ReadWrite; internal const string ApplicationName = "Core Microsoft SqlClient Data Provider"; internal const string AttachDBFilename = ""; + internal const int CommandTimeout = 30; internal const int ConnectTimeout = 15; internal const string CurrentLanguage = ""; internal const string DataSource = ""; @@ -719,6 +720,7 @@ internal static partial class DbConnectionStringKeywords internal const string ApplicationName = "Application Name"; internal const string AsynchronousProcessing = "Asynchronous Processing"; internal const string AttachDBFilename = "AttachDbFilename"; + internal const string CommandTimeout = "Command Timeout"; internal const string ConnectTimeout = "Connect Timeout"; internal const string ConnectionReset = "Connection Reset"; internal const string ContextConnection = "Context Connection"; 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 526459baca..ae7db9afeb 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 @@ -65,7 +65,7 @@ protected override void AfterCleared(SqlCommand owner) } private CommandType _commandType; - private int _commandTimeout = ADP.DefaultCommandTimeout; + private int? _commandTimeout; private UpdateRowSource _updatedRowSource = UpdateRowSource.Both; private bool _designTimeInvisible; @@ -572,7 +572,7 @@ override public int CommandTimeout { get { - return _commandTimeout; + return _commandTimeout ?? DefaultCommandTimeout; } set { @@ -592,10 +592,18 @@ override public int CommandTimeout /// public void ResetCommandTimeout() { - if (ADP.DefaultCommandTimeout != _commandTimeout) + if (ADP.DefaultCommandTimeout != CommandTimeout) { PropertyChanging(); - _commandTimeout = ADP.DefaultCommandTimeout; + _commandTimeout = DefaultCommandTimeout; + } + } + + private int DefaultCommandTimeout + { + get + { + return _activeConnection?.CommandTimeout ?? ADP.DefaultCommandTimeout; } } 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 c1fa77b989..d120c08634 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 @@ -505,6 +505,16 @@ public override int ConnectionTimeout } } + /// + public int CommandTimeout + { + get + { + SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; + return ((null != constr) ? constr.CommandTimeout : SqlConnectionString.DEFAULT.Command_Timeout); + } + } + /// // AccessToken: To be used for token based authentication public string AccessToken diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionString.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionString.cs index 90010dc058..9a87f2feed 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionString.cs @@ -23,6 +23,7 @@ internal static partial class DEFAULT internal const ApplicationIntent ApplicationIntent = DbConnectionStringDefaults.ApplicationIntent; internal const string Application_Name = TdsEnums.SQL_PROVIDER_NAME; internal const string AttachDBFilename = ""; + internal const int Command_Timeout = ADP.DefaultCommandTimeout; internal const int Connect_Timeout = ADP.DefaultConnectionTimeout; internal const string Current_Language = ""; internal const string Data_Source = ""; @@ -67,6 +68,8 @@ internal static class KEY internal const string ColumnEncryptionSetting = "column encryption setting"; internal const string EnclaveAttestationUrl = "enclave attestation url"; internal const string AttestationProtocol = "attestation protocol"; + + internal const string Command_Timeout = "command timeout"; internal const string Connect_Timeout = "connect timeout"; internal const string Connection_Reset = "connection reset"; internal const string Context_Connection = "context connection"; @@ -210,6 +213,7 @@ internal static class TRANSACTIONBINDING private readonly string _enclaveAttestationUrl; private readonly SqlConnectionAttestationProtocol _attestationProtocol; + private readonly int _commandTimeout; private readonly int _connectTimeout; private readonly int _loadBalanceTimeout; private readonly int _maxPoolSize; @@ -265,6 +269,7 @@ internal SqlConnectionString(string connectionString) : base(connectionString, G _userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance); _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover); + _commandTimeout = ConvertValueToInt32(KEY.Command_Timeout, DEFAULT.Command_Timeout); _connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout); _loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout); _maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size); @@ -307,6 +312,11 @@ internal SqlConnectionString(string connectionString) : base(connectionString, G throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout); } + if (_commandTimeout < 0) + { + throw ADP.InvalidConnectionOptionValue(KEY.Command_Timeout); + } + if (_maxPoolSize < 1) { throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size); @@ -490,6 +500,7 @@ internal SqlConnectionString(SqlConnectionString connectionOptions, string dataS _pooling = connectionOptions._pooling; _replication = connectionOptions._replication; _userInstance = userInstance; + _commandTimeout = connectionOptions._commandTimeout; _connectTimeout = connectionOptions._connectTimeout; _loadBalanceTimeout = connectionOptions._loadBalanceTimeout; #if netcoreapp @@ -545,6 +556,7 @@ internal SqlConnectionString(SqlConnectionString connectionOptions, string dataS internal bool Replication { get { return _replication; } } internal bool UserInstance { get { return _userInstance; } } + internal int CommandTimeout { get { return _commandTimeout; } } internal int ConnectTimeout { get { return _connectTimeout; } } internal int LoadBalanceTimeout { get { return _loadBalanceTimeout; } } internal int MaxPoolSize { get { return _maxPoolSize; } } @@ -633,6 +645,7 @@ internal static Dictionary GetParseSynonyms() #if netcoreapp { KEY.PoolBlockingPeriod, KEY.PoolBlockingPeriod}, #endif + { KEY.Command_Timeout, KEY.Command_Timeout }, { KEY.Connect_Timeout, KEY.Connect_Timeout }, { KEY.Connection_Reset, KEY.Connection_Reset }, { KEY.Context_Connection, KEY.Context_Connection }, diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionStringBuilder.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionStringBuilder.cs index 2353243a1a..a2a327ea51 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionStringBuilder.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SqlConnectionStringBuilder.cs @@ -69,6 +69,8 @@ private enum Keywords EnclaveAttestationUrl, AttestationProtocol, + CommandTimeout, + // keep the count value last KeywordsCount } @@ -93,6 +95,7 @@ private enum Keywords private string _userID = DbConnectionStringDefaults.UserID; private string _workstationID = DbConnectionStringDefaults.WorkstationID; + private int _commandTimeout = DbConnectionStringDefaults.CommandTimeout; private int _connectTimeout = DbConnectionStringDefaults.ConnectTimeout; private int _loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout; private int _maxPoolSize = DbConnectionStringDefaults.MaxPoolSize; @@ -125,6 +128,7 @@ private static string[] CreateValidKeywords() #if netcoreapp validKeywords[(int)Keywords.PoolBlockingPeriod] = DbConnectionStringKeywords.PoolBlockingPeriod; #endif + validKeywords[(int)Keywords.CommandTimeout] = DbConnectionStringKeywords.CommandTimeout; validKeywords[(int)Keywords.ConnectTimeout] = DbConnectionStringKeywords.ConnectTimeout; validKeywords[(int)Keywords.CurrentLanguage] = DbConnectionStringKeywords.CurrentLanguage; validKeywords[(int)Keywords.DataSource] = DbConnectionStringKeywords.DataSource; @@ -168,6 +172,7 @@ private static Dictionary CreateKeywordsDictionary() #if netcoreapp hash.Add(DbConnectionStringKeywords.PoolBlockingPeriod, Keywords.PoolBlockingPeriod); #endif + hash.Add(DbConnectionStringKeywords.CommandTimeout, Keywords.CommandTimeout); hash.Add(DbConnectionStringKeywords.ConnectTimeout, Keywords.ConnectTimeout); hash.Add(DbConnectionStringKeywords.CurrentLanguage, Keywords.CurrentLanguage); hash.Add(DbConnectionStringKeywords.DataSource, Keywords.DataSource); @@ -298,6 +303,9 @@ public override object this[string keyword] WorkstationID = ConvertToString(value); break; + case Keywords.CommandTimeout: + CommandTimeout = ConvertToInt32(value); + break; case Keywords.ConnectTimeout: ConnectTimeout = ConvertToInt32(value); break; @@ -416,6 +424,21 @@ public string AttachDBFilename } } + /// + public int CommandTimeout + { + get { return _commandTimeout; } + set + { + if (value < 0) + { + throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.CommandTimeout); + } + SetValue(DbConnectionStringKeywords.CommandTimeout, value); + _commandTimeout = value; + } + } + /// public int ConnectTimeout { @@ -905,6 +928,8 @@ private object GetAt(Keywords index) #if netcoreapp case Keywords.PoolBlockingPeriod: return PoolBlockingPeriod; #endif + case Keywords.CommandTimeout: + return CommandTimeout; case Keywords.ConnectTimeout: return ConnectTimeout; case Keywords.CurrentLanguage: @@ -1021,6 +1046,9 @@ private void Reset(Keywords index) _poolBlockingPeriod = DbConnectionStringDefaults.PoolBlockingPeriod; break; #endif + case Keywords.CommandTimeout: + _commandTimeout = DbConnectionStringDefaults.CommandTimeout; + break; case Keywords.ConnectTimeout: _connectTimeout = DbConnectionStringDefaults.ConnectTimeout; break; diff --git a/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs b/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs index 1fe8a00ea2..6f29fe813c 100644 --- a/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs +++ b/src/Microsoft.Data.SqlClient/netfx/ref/Microsoft.Data.SqlClient.cs @@ -744,6 +744,9 @@ public SqlConnection(string connectionString, Microsoft.Data.SqlClient.SqlCreden /// [System.ComponentModel.DefaultValueAttribute(null)] public static System.Collections.Generic.IDictionary> ColumnEncryptionTrustedMasterKeyPaths { get { throw null; } } + /// + [System.ComponentModel.DesignerSerializationVisibilityAttribute(0)] + public int CommandTimeout { get { throw null; } } /// [System.ComponentModel.DefaultValueAttribute("")] [System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] @@ -912,6 +915,10 @@ public SqlConnectionStringBuilder(string connectionString) { } [System.ComponentModel.DisplayNameAttribute("Column Encryption Setting")] [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public Microsoft.Data.SqlClient.SqlConnectionColumnEncryptionSetting ColumnEncryptionSetting { get { throw null; } set { } } + /// + [System.ComponentModel.DisplayNameAttribute("Command Timeout")] + [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] + public int CommandTimeout { get { throw null; } set { } } /// [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DisplayNameAttribute("Connection Reset")] diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionStringCommon.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionStringCommon.cs index 9979e9f6de..b3ba200bdd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionStringCommon.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/Common/DbConnectionStringCommon.cs @@ -648,7 +648,7 @@ internal static string ColumnEncryptionSettingToString(SqlConnectionColumnEncryp internal static bool IsValidAuthenticationTypeValue(SqlAuthenticationMethod value) { - Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 6, "SqlAuthenticationMethod enum has changed, update needed"); + Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 7, "SqlAuthenticationMethod enum has changed, update needed"); return value == SqlAuthenticationMethod.SqlPassword || value == SqlAuthenticationMethod.ActiveDirectoryPassword || value == SqlAuthenticationMethod.ActiveDirectoryIntegrated @@ -1011,6 +1011,7 @@ internal static class DbConnectionStringDefaults internal const string ApplicationName = "Framework Microsoft SqlClient Data Provider"; internal const bool AsynchronousProcessing = false; internal const string AttachDBFilename = ""; + internal const int CommandTimeout = 30; internal const int ConnectTimeout = 15; internal const bool ConnectionReset = true; internal const bool ContextConnection = false; @@ -1094,6 +1095,7 @@ internal static class DbConnectionStringKeywords internal const string AsynchronousProcessing = "Asynchronous Processing"; internal const string AttachDBFilename = "AttachDbFilename"; internal const string ConnectTimeout = "Connect Timeout"; + internal const string CommandTimeout = "Command Timeout"; internal const string ConnectionReset = "Connection Reset"; internal const string ContextConnection = "Context Connection"; internal const string CurrentLanguage = "Current Language"; 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 d0a9d96be7..dfe71c8351 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 @@ -39,7 +39,7 @@ public sealed class SqlCommand : DbCommand, ICloneable private string _commandText; private CommandType _commandType; - private int _commandTimeout = ADP.DefaultCommandTimeout; + private int? _commandTimeout; private UpdateRowSource _updatedRowSource = UpdateRowSource.Both; private bool _designTimeInvisible; @@ -762,7 +762,7 @@ override public int CommandTimeout { // V1.2.3300, XXXCommand V1.0.5000 get { - return _commandTimeout; + return _commandTimeout ?? DefaultCommandTimeout; } set { @@ -783,16 +783,19 @@ override public int CommandTimeout /// public void ResetCommandTimeout() { // V1.2.3300 - if (ADP.DefaultCommandTimeout != _commandTimeout) + if (ADP.DefaultCommandTimeout != CommandTimeout) { PropertyChanging(); - _commandTimeout = ADP.DefaultCommandTimeout; + _commandTimeout = DefaultCommandTimeout; } } - private bool ShouldSerializeCommandTimeout() - { // V1.2.3300 - return (ADP.DefaultCommandTimeout != _commandTimeout); + private int DefaultCommandTimeout + { + get + { + return _activeConnection?.CommandTimeout ?? ADP.DefaultCommandTimeout; + } } /// 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 491ff0cc0a..6682ccbb90 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 @@ -642,6 +642,20 @@ public string AccessToken } } + /// + [ + DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), + ResDescriptionAttribute(StringsHelper.ResourceNames.SqlConnection_ConnectionTimeout), + ] + public int CommandTimeout + { + get + { + SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; + return ((null != constr) ? constr.CommandTimeout : SqlConnectionString.DEFAULT.Command_Timeout); + } + } + /// [ DefaultValue(""), diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionString.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionString.cs index d696512b51..2f24e0dabd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionString.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionString.cs @@ -24,6 +24,7 @@ internal static class DEFAULT internal const bool Asynchronous = false; internal const string AttachDBFilename = ""; internal const PoolBlockingPeriod PoolBlockingPeriod = DbConnectionStringDefaults.PoolBlockingPeriod; + internal const int Command_Timeout = ADP.DefaultCommandTimeout; internal const int Connect_Timeout = ADP.DefaultConnectionTimeout; internal const bool Connection_Reset = true; internal const bool Context_Connection = false; @@ -74,6 +75,7 @@ internal static class KEY internal const string EnclaveAttestationUrl = "enclave attestation url"; internal const string AttestationProtocol = "attestation protocol"; internal const string Connect_Timeout = "connect timeout"; + internal const string Command_Timeout = "command timeout"; internal const string Connection_Reset = "connection reset"; internal const string Context_Connection = "context connection"; internal const string Current_Language = "current language"; @@ -235,6 +237,7 @@ internal static class TRANSACIONBINDING private readonly string _enclaveAttestationUrl; private readonly SqlConnectionAttestationProtocol _attestationProtocol; + private readonly int _commandTimeout; private readonly int _connectTimeout; private readonly int _loadBalanceTimeout; private readonly int _maxPoolSize; @@ -296,6 +299,7 @@ internal SqlConnectionString(string connectionString) : base(connectionString, G _transparentNetworkIPResolution = ConvertValueToBoolean(KEY.TransparentNetworkIPResolution, DEFAULT.TransparentNetworkIPResolution); _connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout); + _commandTimeout = ConvertValueToInt32(KEY.Command_Timeout, DEFAULT.Command_Timeout); _loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout); _maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size); _minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size); @@ -376,6 +380,11 @@ internal SqlConnectionString(string connectionString) : base(connectionString, G throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout); } + if (_commandTimeout < 0) + { + throw ADP.InvalidConnectionOptionValue(KEY.Command_Timeout); + } + if (_maxPoolSize < 1) { throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size); @@ -601,6 +610,7 @@ internal SqlConnectionString(SqlConnectionString connectionOptions, string dataS _pooling = connectionOptions._pooling; _replication = connectionOptions._replication; _userInstance = userInstance; + _commandTimeout = connectionOptions._commandTimeout; _connectTimeout = connectionOptions._connectTimeout; _loadBalanceTimeout = connectionOptions._loadBalanceTimeout; _poolBlockingPeriod = connectionOptions._poolBlockingPeriod; @@ -671,6 +681,7 @@ internal SqlConnectionString(SqlConnectionString connectionOptions, string dataS internal bool Replication { get { return _replication; } } internal bool UserInstance { get { return _userInstance; } } + internal int CommandTimeout { get { return _commandTimeout; } } internal int ConnectTimeout { get { return _connectTimeout; } } internal int LoadBalanceTimeout { get { return _loadBalanceTimeout; } } internal int MaxPoolSize { get { return _maxPoolSize; } } @@ -764,6 +775,7 @@ internal static Hashtable GetParseSynonyms() hash.Add(KEY.AttachDBFilename, KEY.AttachDBFilename); hash.Add(KEY.PoolBlockingPeriod, KEY.PoolBlockingPeriod); hash.Add(KEY.Connect_Timeout, KEY.Connect_Timeout); + hash.Add(KEY.Command_Timeout, KEY.Command_Timeout); hash.Add(KEY.Connection_Reset, KEY.Connection_Reset); hash.Add(KEY.Context_Connection, KEY.Context_Connection); hash.Add(KEY.Current_Language, KEY.Current_Language); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionStringBuilder.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionStringBuilder.cs index 5cf2cfdb9a..fb17b8df03 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionStringBuilder.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnectionStringBuilder.cs @@ -81,6 +81,8 @@ private enum Keywords EnclaveAttestationUrl, AttestationProtocol, + CommandTimeout, + #if ADONET_CERT_AUTH Certificate, #endif @@ -108,6 +110,7 @@ private enum Keywords private string _userID = DbConnectionStringDefaults.UserID; private string _workstationID = DbConnectionStringDefaults.WorkstationID; + private int _commandTimeout = DbConnectionStringDefaults.CommandTimeout; private int _connectTimeout = DbConnectionStringDefaults.ConnectTimeout; private int _loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout; private int _maxPoolSize = DbConnectionStringDefaults.MaxPoolSize; @@ -151,6 +154,7 @@ static SqlConnectionStringBuilder() validKeywords[(int)Keywords.ConnectionReset] = DbConnectionStringKeywords.ConnectionReset; validKeywords[(int)Keywords.ContextConnection] = DbConnectionStringKeywords.ContextConnection; validKeywords[(int)Keywords.ConnectTimeout] = DbConnectionStringKeywords.ConnectTimeout; + validKeywords[(int)Keywords.CommandTimeout] = DbConnectionStringKeywords.CommandTimeout; validKeywords[(int)Keywords.CurrentLanguage] = DbConnectionStringKeywords.CurrentLanguage; validKeywords[(int)Keywords.DataSource] = DbConnectionStringKeywords.DataSource; validKeywords[(int)Keywords.Encrypt] = DbConnectionStringKeywords.Encrypt; @@ -195,6 +199,7 @@ static SqlConnectionStringBuilder() hash.Add(DbConnectionStringKeywords.AttachDBFilename, Keywords.AttachDBFilename); hash.Add(DbConnectionStringKeywords.PoolBlockingPeriod, Keywords.PoolBlockingPeriod); hash.Add(DbConnectionStringKeywords.ConnectTimeout, Keywords.ConnectTimeout); + hash.Add(DbConnectionStringKeywords.CommandTimeout, Keywords.CommandTimeout); hash.Add(DbConnectionStringKeywords.ConnectionReset, Keywords.ConnectionReset); hash.Add(DbConnectionStringKeywords.ContextConnection, Keywords.ContextConnection); hash.Add(DbConnectionStringKeywords.CurrentLanguage, Keywords.CurrentLanguage); @@ -336,6 +341,9 @@ public override object this[string keyword] WorkstationID = ConvertToString(value); break; + case Keywords.CommandTimeout: + CommandTimeout = ConvertToInt32(value); + break; case Keywords.ConnectTimeout: ConnectTimeout = ConvertToInt32(value); break; @@ -521,6 +529,25 @@ public PoolBlockingPeriod PoolBlockingPeriod } } + /// + [DisplayName(DbConnectionStringKeywords.CommandTimeout)] + [ResCategory(StringsHelper.ResourceNames.DataCategory_Initialization)] + [ResDescription(StringsHelper.ResourceNames.DbCommand_CommandTimeout)] + [RefreshProperties(RefreshProperties.All)] + public int CommandTimeout + { + get { return _commandTimeout; } + set + { + if (value < 0) + { + throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.CommandTimeout); + } + SetValue(DbConnectionStringKeywords.CommandTimeout, value); + _commandTimeout = value; + } + } + /// [Browsable(false)] [DisplayName(DbConnectionStringKeywords.ConnectionReset)] @@ -1268,6 +1295,8 @@ private object GetAt(Keywords index) return PoolBlockingPeriod; case Keywords.ConnectTimeout: return ConnectTimeout; + case Keywords.CommandTimeout: + return CommandTimeout; #pragma warning disable 618 // Obsolete ConnectionReset case Keywords.ConnectionReset: return ConnectionReset; @@ -1430,6 +1459,9 @@ private void Reset(Keywords index) case Keywords.ConnectTimeout: _connectTimeout = DbConnectionStringDefaults.ConnectTimeout; break; + case Keywords.CommandTimeout: + _commandTimeout = DbConnectionStringDefaults.CommandTimeout; + break; case Keywords.ConnectionReset: _connectionReset = DbConnectionStringDefaults.ConnectionReset; break; diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlCommandTest.cs b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlCommandTest.cs index ae9e097dfd..a01badc8ed 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlCommandTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlCommandTest.cs @@ -136,6 +136,22 @@ public void Constructor3() Assert.Equal(UpdateRowSource.Both, cmd.UpdatedRowSource); } + [Theory] + [InlineData(0)] + [InlineData(30)] + [InlineData(15)] + public void Constructor3_CommandTimeout(int timeout) + { + SqlConnection conn = new SqlConnection($"Command Timeout = {timeout}"); + SqlCommand cmd; + + cmd = new SqlCommand(COMMAND_TEXT, conn); + Assert.Equal(timeout, cmd.CommandTimeout); + + cmd.CommandTimeout = timeout + 10; + Assert.Equal(timeout + 10, cmd.CommandTimeout); + } + [Fact] public void Constructor4() { diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionStringBuilderTest.cs b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionStringBuilderTest.cs index 449e8bca09..9f6061e40c 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionStringBuilderTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionStringBuilderTest.cs @@ -17,6 +17,9 @@ public class SqlConnectionStringBuilderTest [InlineData("Attestation Protocol = HGS")] [InlineData("Authentication = Active Directory Password ")] [InlineData("Authentication = ActiveDirectoryPassword ")] + [InlineData("Command Timeout = 5")] + [InlineData("Command Timeout = 15")] + [InlineData("Command Timeout = 0")] [InlineData("ConnectRetryCount = 5")] [InlineData("Connect Retry Count = 0")] [InlineData("ConnectRetryInterval = 10")] diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.cs b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.cs index f2870aae1e..9289f23768 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.cs @@ -24,6 +24,7 @@ public void Constructor1() Assert.Equal(string.Empty, cn.ConnectionString); Assert.Equal(15, cn.ConnectionTimeout); + Assert.Null(cn.Container); Assert.Equal(string.Empty, cn.Database); Assert.Equal(string.Empty, cn.DataSource); @@ -43,6 +44,7 @@ public void Constructor2() SqlConnection cn = new SqlConnection(connectionString); Assert.Equal(connectionString, cn.ConnectionString); Assert.Equal(15, cn.ConnectionTimeout); + Assert.Equal(30, cn.CommandTimeout); Assert.Null(cn.Container); Assert.Equal("dotNet", cn.Database); Assert.Equal("SQLSRV", cn.DataSource); @@ -56,6 +58,7 @@ public void Constructor2() cn = new SqlConnection((string)null); Assert.Equal(string.Empty, cn.ConnectionString); Assert.Equal(15, cn.ConnectionTimeout); + Assert.Equal(30, cn.CommandTimeout); Assert.Null(cn.Container); Assert.Equal(string.Empty, cn.Database); Assert.Equal(string.Empty, cn.DataSource); @@ -722,6 +725,85 @@ public void ConnectionString_ConnectTimeout_Invalid() } } + [Fact] + public void ConnectionString_CommandTimeout() + { + SqlConnection cn = new SqlConnection(); + cn.ConnectionString = "Command Timeout=45"; + Assert.Equal(45, cn.CommandTimeout); + cn.ConnectionString = "Command Timeout=40"; + Assert.Equal(40, cn.CommandTimeout); + cn.ConnectionString = "command timeout="; + Assert.Equal(30, cn.CommandTimeout); + cn.ConnectionString = "Command Timeout=2147483647"; + Assert.Equal(int.MaxValue, cn.CommandTimeout); + cn.ConnectionString = "Command Timeout=0"; + Assert.Equal(0, cn.CommandTimeout); + } + + [Fact] + public void ConnectionString_CommandTimeout_Invalid() + { + SqlConnection cn = new SqlConnection(); + + // negative number + try + { + cn.ConnectionString = "Command timeout=-1"; + } + catch (ArgumentException ex) + { + // Invalid value for key 'connect timeout' + Assert.Equal(typeof(ArgumentException), ex.GetType()); + Assert.Null(ex.InnerException); + Assert.NotNull(ex.Message); + Assert.True(ex.Message.IndexOf("'command timeout'") != -1); + Assert.Null(ex.ParamName); + } + + // invalid number + try + { + cn.ConnectionString = "command Timeout=BB"; + } + catch (ArgumentException ex) + { + // Invalid value for key 'connect timeout' + Assert.Equal(typeof(ArgumentException), ex.GetType()); + Assert.NotNull(ex.InnerException); + Assert.Equal(typeof(FormatException), ex.InnerException.GetType()); + Assert.NotNull(ex.Message); + Assert.True(ex.Message.IndexOf("'command timeout'") != -13); + Assert.Null(ex.ParamName); + + // Input string was not in a correct format + FormatException fe = (FormatException)ex.InnerException; + Assert.Null(fe.InnerException); + Assert.NotNull(fe.Message); + } + + // overflow + try + { + cn.ConnectionString = "command timeout=2147483648"; + } + catch (ArgumentException ex) + { + // Invalid value for key 'command timeout' + Assert.Equal(typeof(ArgumentException), ex.GetType()); + Assert.NotNull(ex.InnerException); + Assert.Equal(typeof(OverflowException), ex.InnerException.GetType()); + Assert.NotNull(ex.Message); + Assert.True(ex.Message.IndexOf("'command timeout'") != -1); + Assert.Null(ex.ParamName); + + // Value was either too large or too small for an Int32 + OverflowException oe = (OverflowException)ex.InnerException; + Assert.Null(oe.InnerException); + Assert.NotNull(oe.Message); + } + } + [Fact] public void ConnectionString_Database_Synonyms() {